I’ll show you how to start HTTP and HTTPS servers simultaneously in NestJS.
I encountered a case where SSL/TLS was required in the local environment with NestJS, so I wrote sample code to start an HTTPS server.
I issued the local environment SSL/TLS server certificates like localhost-key.pem and localhost.pem using mkcert.
Here’s how to start HTTP and HTTPS servers simultaneously in NestJS:
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import * as express from 'express';
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
async function bootstrap() {
const privateKey = fs.readFileSync('/your_path/localhost-key.pem', 'utf8');
const certificate = fs.readFileSync('/your_path/localhost.pem', 'utf8');
const httpsOptions = { key: privateKey, cert: certificate };
const server = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
await app.init();
http.createServer(server).listen(3000);
https.createServer(httpsOptions, server).listen(443);
}
bootstrap();
That’s all from the Gemba.