# Configuration

Configuration lets you quickly configure your server via decorator. This decorator takes your configuration and merges it with the default server configuration.

The default configuration is as follows:

{
  "env": "development",
  "port": 8080,
  "debug": false,
  "httpsPort": 8000,
  "uploadDir": "./uploads"
}
1
2
3
4
5
6
7

You can customize your configuration as follows on Server.tslevel:

import {Configuration} from "@tsed/di";
import {MyController} from "./controllers/manual/MyController";

@Configuration({
  mount: {
    "/rest": [
      `./controllers/current/**/*.ts`, // deprecated
      MyController // support manual import
    ],
    "/rest/v0": [
      // versioning
      `./controllers/v0/users/*.js`, // deprecated
      `!./controllers/v0/groups/old/*.ts` // Exclusion
    ]
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

or when you bootstrap your Server (e.g. index.ts):

import {$log} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./server";

async function bootstrap() {
  try {
    $log.debug("Start server...");
    const platform = await PlatformExpress.bootstrap(Server, {
      // extra settings
    });

    await platform.listen();
    $log.debug("Server initialized");
  } catch (er) {
    $log.error(er);
  }
}

bootstrap();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Note

Ts.ED supports ts-node (opens new window). Ts extension will be replaced by a Js extension if ts-node isn't the runtime.

# Load configuration from file

Ts.ED doesn't provide solution to load configuration from files. Because, there is many solution to achieve this, we consider this part as the developer responsibility.

By using node-config (opens new window) or dotenv (opens new window), it's possible to load your configuration from file as following:

    # Options

    # rootDir

    • type: string

    The root directory where you build run project. By default, it is equal to process.cwd().

    import {Configuration} from "@tsed/di";
    
    @Configuration({
      rootDir: process.cwd()
    })
    export class Server {}
    
    1
    2
    3
    4
    5
    6

    # env

    The environment profiles. By default the environment profile is equal to NODE_ENV.

    import {Env} from "@tsed/core";
    import {Configuration, Constant} from "@tsed/di";
    
    @Configuration({
      env: Env.PROD
    })
    export class Server {
      @Constant("env")
      env: Env;
    
      $beforeRoutesInit() {
        if (this.env === Env.PROD) {
          // do something
        }
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    # httpPort

    • type: string | number | false

    Port number for the HTTP.Server (opens new window). Set false to disable the http port.

    # httpsPort

    • type: string | number | false

    Port number for the HTTPs.Server (opens new window).

    # httpsOptions

    • type: Https.ServerOptions (opens new window)
      • key <string> | <string[]> | <Buffer> (opens new window) | <Object[]>: The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as a plain array of key strings or an array of objects in the format {pem: key, passphrase: passphrase}. This option is required for ciphers making use of private keys.
      • passphrase <string> A string containing the passphrase for the private key or pfx.
      • cert <string> | <string[]> | <Buffer> (opens new window) | <Buffer[]> (opens new window): A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)
      • ca <string> | <string[]> | <Buffer> (opens new window) | <Buffer[]> (opens new window): A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.

    See the HTTPs project example (opens new window)

    # mount

    Mount all given controllers and map controllers to the corresponding endpoints.

    Ts.ED provides the possibility to mount multiple Rest paths instead of the default path /rest. This option will allow you to define a version for an endpoint and select which controllers you want to associate with the given path.

    import {Configuration} from "@tsed/di";
    import * as v1Controllers from "./controllers/v1/index";
    import * as v0Controllers from "./controllers/v0/index";
    
    @Configuration({
      mount: {
        "/rest/v1": [...Object.values(v1Controllers)],
        "/rest/v0": [...Object.values(v0Controllers)]
      }
    })
    export class Server {}
    
    // v1/index.ts
    export * from "./users/UserControllers";
    export * from "./groups/GroupsControllers";
    
    // v0/index.ts
    export * from "./users/UserControllers";
    export * from "./groups/GroupsControllers";
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    It is also possible to split the configuration by using the Module :

      # componentsScan (deprecated)

      • type: string[]

      List of glob pattern to scan directories which contains Services or Middlewares.

      # middlewares v6.28.0+

      • type: PlatformMiddlewareSettings[]

      A middleware list (Express.js, Ts.ED, Koa, etc...) must be loaded on the $beforeRoutesInit hook or on the specified hook. In addition, it's also possible to configure the environment for which the middleware should be loaded.

      Here is an example to load middlewares with the previous version (this example will be always available!):

      import {Configuration, ProviderScope, ProviderType} from "@tsed/di";
      import {Env} from "@tsed/core";
      
      @Configuration({})
      export class Server {
        $afterInit() {
          this.app.use(helmet({contentSecurityPolicy: false}));
        }
      
        $beforeRoutesInit() {
          if (this.env === Env.PROD) {
            this.app.use(EnsureHttpsMiddleware);
          }
      
          this.app.use(cors()).use(cookieParser()).use(compress({})).use(methodOverride()).use(AuthTokenMiddleware);
      
          return null;
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19

      After v6.28.0, you can use the middlewares options as follows:

      import {Configuration, ProviderScope, ProviderType} from "@tsed/di";
      
      @Configuration({
        middlewares: [
          {hook: "$afterInit", use: helmet({contentSecurityPolicy: false})},
          {env: Env.PROD, use: EnsureHttpsMiddleware},
          cors(),
          cookieParser(),
          compress({}),
          methodOverride(),
          AuthTokenMiddleware
        ]
      })
      export class Server {}
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14

      Order priority

      The middlewares added through middlewares options will always be registered after the middlewares registered through the hook methods!

      # imports

      • type: Type<any>[]

      Add providers or modules here. These modules or provider will be built before the server itself.

        # exclude (deprecated)

        • type: string[]

        List of glob patterns. Exclude all files that match with this list when the Server scans all components with the mount or scanComponents options.

        # scopes

        • type: {[key: string]: ProviderScope}

        Change the default scope for a given provider. See injection scopes for more details.

        import {Configuration, ProviderScope, ProviderType} from "@tsed/di";
        
        @Configuration({
          scopes: {
            [ProviderType.CONTROLLER]: ProviderScope.REQUEST
          }
        })
        export class Server {}
        
        1
        2
        3
        4
        5
        6
        7
        8

        # logger

        Logger configuration. See logger section for more detail.

        # resolvers - External DI

        Ts.ED has its own DI container, but sometimes you have to work with other DI like Inversify or TypeDI. The version 5.39.0+ now allows you to configure multiple external DI by using the resolvers options.

        The resolvers options can be configured as following:

        import {Configuration} from "@tsed/di";
        import {myContainer} from "./inversify.config";
        
        @Configuration({
          resolvers: [
            {
              get(token: any) {
                return myContainer.get(token);
              }
            }
          ]
        })
        export class Server {}
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13

        It's also possible to register resolvers with the Module decorator:

        import {Module} from "@tsed/di";
        import {myContainer} from "./inversify.config";
        
        @Module({
          resolvers: [
            {
              get(token: any) {
                return myContainer.get(token);
              }
            }
          ]
        })
        export class MyModule {}
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13

        # views

        Object to configure Views engines with Ts.ED engines or Consolidate (deprecated). See more on View engine.

        # acceptMimes

        Configure the mimes accepted by default for each request by the server.

        # responseFilters

        A list of response filters must be called before returning a response to the consumer. See more on Response filters.

        # multer

        Object configure Multer. See more on Upload file.

        # jsonMapper

        @Configuration({
          jsonMapper: {
            additionalProperties: false,
            disableUnsecureConstructor: false,
          }
        })
        
        1
        2
        3
        4
        5
        6

        # jsonMapper.additionalProperties

        Enable additional properties on model. By default, false. Enable this option is dangerous and may be a potential security issue.

        # jsonMapper.disableUnsecureConstructor

        Pass the plain object to the model constructor. By default, false.

        It may be a potential security issue if you have as constructor with this followings code:

        class MyModel {
          constructor(obj: any = {}) {
            Object.assign(this, obj); // potential prototype pollution
          }
        }
        
        1
        2
        3
        4
        5

        Note

        Recommended: Set this options to true in your new project.

        In v7 this option will be set to true by default.

        # Platform Options

        These options are specific for each framework (Express.js, Koa.js, etc...):

          # HTTP & HTTPs server

          # Change address

          It's possible to change the HTTP and HTTPS server address as follows:

          import {Configuration} from "@tsed/common";
          
          @Configuration({
            httpPort: "127.0.0.1:8081",
            httpsPort: "127.0.0.2:8082"
          })
          export class Server {}
          
          1
          2
          3
          4
          5
          6
          7

          # Random port

          Random port assignment can be enable with the value 0. The port assignment will be delegated to the OS.

          import {Configuration} from "@tsed/common";
          
          @Configuration({
            httpPort: "127.0.0.1:0",
            httpsPort: "127.0.0.2:0"
          })
          export class Server {}
          
          1
          2
          3
          4
          5
          6
          7

          Or:

          import {Configuration} from "@tsed/common";
          
          @Configuration({
            httpPort: 0,
            httpsPort: 0
          })
          export class Server {}
          
          1
          2
          3
          4
          5
          6
          7

          # Disable HTTP

          import {Configuration} from "@tsed/common";
          
          @Configuration({
            httpPort: false
          })
          export class Server {}
          
          1
          2
          3
          4
          5
          6

          # Disable HTTPS

          import {Configuration} from "@tsed/common";
          
          @Configuration({
            httpsPort: false
          })
          export class Server {}
          
          1
          2
          3
          4
          5
          6

          # Get configuration

          The configuration can be reused throughout your application in different ways.

          # From service (DI)

          import {Configuration, Injectable} from "@tsed/di";
          
          @Injectable() // or Controller or Middleware
          export class MyService {
            constructor(@Configuration() configuration: Configuration) {}
          }
          
          1
          2
          3
          4
          5
          6

          # From decorators

          Decorators Constant and Value can be used in all classes including:

          Constant and Value accepts an expression as parameters to inspect the configuration object and return the value.

          import {Constant, Value} from "@tsed/di";
          import {Env} from "@tsed/core";
          
          export class MyClass {
            @Constant("env")
            env: Env;
          
            @Value("swagger.path")
            swaggerPath: string;
          
            $onInit() {
              console.log(this.env);
            }
          }
          
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14

          WARNING

          Constant returns an Object.freeze() value.

          NOTE

          The values for the decorated properties aren't available on constructor. Use $onInit() hook to use the value.

          Last Updated: 8/26/2022, 1:43:42 PM

          Other topics