Để tạo một application dùng giao thức HTTPS, đặt thuộc tính httpsOptions trong options object truyền vào phương thức create() của class NestFactory:
const httpsOptions = {
key: fs.readFileSync('./secrets/private-key.pem'),
cert: fs.readFileSync('./secrets/public-certificate.pem'),
};
const app = await NestFactory.create(AppModule, {
httpsOptions,
});
await app.listen(process.env.PORT ?? 3000);
Nếu bạn dùng FastifyAdapter, hãy tạo application như sau:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ https: httpsOptions }),
);
Nhiều server đồng thời
Công thức sau đây cho thấy cách khởi tạo một Nest application lắng nghe trên nhiều port (ví dụ: một port không phải HTTPS và một port HTTPS) cùng lúc.
const httpsOptions = {
key: fs.readFileSync('./secrets/private-key.pem'),
cert: fs.readFileSync('./secrets/public-certificate.pem'),
};
const server = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
await app.init();
const httpServer = http.createServer(server).listen(3000);
const httpsServer = https.createServer(httpsOptions, server).listen(443);
Vì chúng ta tự gọi http.createServer / https.createServer, NestJS sẽ không tự đóng chúng khi gọi app.close / khi nhận tín hiệu kết thúc (termination signal). Chúng ta cần tự xử lý việc này:
@Injectable()
export class ShutdownObserver implements OnApplicationShutdown {
private httpServers: http.Server[] = [];
public addHttpServer(server: http.Server): void {
this.httpServers.push(server);
}
public async onApplicationShutdown(): Promise<void> {
await Promise.all(
this.httpServers.map(
(server) =>
new Promise((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
} else {
resolve(null);
}
});
}),
),
);
}
}
const shutdownObserver = app.get(ShutdownObserver);
shutdownObserver.addHttpServer(httpServer);
shutdownObserver.addHttpServer(httpsServer);
Gợi ý ExpressAdapter được import từ package @nestjs/platform-express. Các package http và https là package gốc (native) của Node.js.
Ghi chú người dịch Bình thường Nest tự quản lý vòng đời server (mở/đóng) thông qua adapter khi bạn gọi app.listen(). Ở đây vì bạn tự gọi http.createServer(server)/https.createServer(...) để bọc thêm một layer bên ngoài, Nest không biết đến 2 server này nên không thể tự đóng chúng khi shutdown — đó là lý do phải tự viết ShutdownObserver để đóng thủ công.
Cảnh báo Công thức này không hoạt động với GraphQL Subscriptions.