Création d’une application Nest avec support HTTPS
HTTPS
Pour créer une application qui utilise le protocole HTTPS, définissez la propriété httpsOptions
dans l’objet d’options passé à la méthode create()
de la classe 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(3000);
Si vous utilisez l’FastifyAdapter
, créez l’application comme suit :
const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter({ https: httpsOptions }),);
Serveurs simultanés multiples
La recette suivante montre comment instancier une application Nest qui écoute sur plusieurs ports (par exemple, sur un port non HTTPS et un port HTTPS) simultanément.
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);
Puisque nous avons appelé http.createServer
/ https.createServer
nous-mêmes, NestJS ne les ferme pas lorsque nous appelons app.close
/ à la réception d’un signal d’arrêt. Nous devons le faire nous-mêmes :
@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);