Nest: How do you set up SSL?

Created on 15 Jul 2017  路  6Comments  路  Source: nestjs/nest

Is there a way to start the Nest application with SSL cert options so I can have a HTTPS server?

For now I manually call the init() function on the Nest app and start the HTTPS server with express app manually.


let options = {
    key: fs.readFileSync(Config.SSL_KEY_PATH),
    cert: fs.readFileSync(Config.SSL_CERT_PATH)
};

let httpsServer = https.createServer(options, expressApp);

const app = NestFactory.create(ApplicationModule, expressApp);
app.useGlobalPipes(new ValidatorPipe());
app.init();

httpsServer.listen(httpsPort);

I was just wondering if there is any standard way of doing SSL with Nest. Couldn't find it in the documentation.

question 馃檶

Most helpful comment

For me was enough this code in the main.ts:

async function bootstrap() {
  const fs = require('fs');
  const keyFile  = fs.readFileSync(__dirname + '/../ssl/mydomain.com.key.pem');
  const certFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.crt.pem');

  const app = await NestFactory.create(AppModule, {
    httpsOptions: {
      key: keyFile,
      cert: certFile,
    }});

//...
}

All 6 comments

Hey @jiminssy,
Yep, that's why the init() method exists. Your solution is the example how to use HTTPS, there's no other option right now.

For me was enough this code in the main.ts:

async function bootstrap() {
  const fs = require('fs');
  const keyFile  = fs.readFileSync(__dirname + '/../ssl/mydomain.com.key.pem');
  const certFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.crt.pem');

  const app = await NestFactory.create(AppModule, {
    httpsOptions: {
      key: keyFile,
      cert: certFile,
    }});

//...
}

Thanks @camposmiguel for the above answer. If I wish to run it locally on my machine over https, then how can i generate the key and crt certificates? I know this may sound trivial, but I am new to this party

It's possible to generate a Let' encrypt free certificate to use in localhost. Here you have the Let's Encrypt documentation: https://letsencrypt.org/docs/certificates-for-localhost/

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings