HTTPS

To create an application that uses the HTTPS protocol, set the httpsOptions property in the options object passed to the create() method of the NestFactory class:

  1. const httpsOptions = {
  2. key: fs.readFileSync('./secrets/private-key.pem'),
  3. cert: fs.readFileSync('./secrets/public-certificate.pem'),
  4. };
  5. const app = await NestFactory.create(AppModule, {
  6. httpsOptions,
  7. });
  8. await app.listen(3000);

If you use the FastifyAdapter, create the application as follows:

  1. const app = await NestFactory.create<NestFastifyApplication>(
  2. AppModule,
  3. new FastifyAdapter({ https: httpsOptions }),
  4. );

Multiple simultaneous servers

The following recipe shows how to instantiate a Nest application that listens on multiple ports (for example, on a non-HTTPS port and an HTTPS port) simultaneously.

  1. const httpsOptions = {
  2. key: fs.readFileSync('./secrets/private-key.pem'),
  3. cert: fs.readFileSync('./secrets/public-certificate.pem'),
  4. };
  5. const server = express();
  6. const app = await NestFactory.create(
  7. AppModule,
  8. new ExpressAdapter(server),
  9. );
  10. await app.init();
  11. http.createServer(server).listen(3000);
  12. https.createServer(httpsOptions, server).listen(443);

info Hint The ExpressAdapter is imported from the @nestjs/platform-express package. The http and https packages are native Node.js packages.

Warning This recipe does not work with GraphQL Subscriptions.