Nest: Support for multiple simultaneous servers (e.g. HTTP and HTTPS)

Created on 3 May 2017  路  2Comments  路  Source: nestjs/nest

The current implementation of NestApplication.listen() does not support easily adding multiple Server backends, since it directly calls .listen() on the Express Application (which only creates an HTTP server).

At the very least, it would be helpful to add a public method on NestApplication that calls the setup functions (setupMiddleswares, setupRoutes, etc.) without calling express.listen().

For anyone else having this issue, a workaround is below:

const expressInstance = express();

const app = NestFactory.create(ApplicationModule, expressInstance);

app.listen(80, () => {
    console.log("HTTP server listening on port 80");
});

let httpsOptions = {
    key: fs.readFileSync("./secrets/private-key.pem"),
    cert: fs.readFileSync("./secrets/public-certificate.pem")
};

const httpsServer = https.createServer(httpsOptions);
httpsServer.addListener("request", expressInstance);
httpsServer.listen(443, () => {
    console.log("HTTPS server listening on port 443");
});
type

Most helpful comment

Hi @Jephery,
Since version 2.1.0 it is possible to directly call init() method on NestApplication instance. However, listen() method is backwards compatible. Example:

let httpsOptions = {
    key: fs.readFileSync("./secrets/private-key.pem"),
    cert: fs.readFileSync("./secrets/public-certificate.pem")
};

const server = express();
const app = NestFactory.create(ApplicationModule, server);
app.init();

http.createServer(server).listen(3000);
https.createServer(httpsOptions, server).listen(443);

All 2 comments

Hi @Jephery,
Since version 2.1.0 it is possible to directly call init() method on NestApplication instance. However, listen() method is backwards compatible. Example:

let httpsOptions = {
    key: fs.readFileSync("./secrets/private-key.pem"),
    cert: fs.readFileSync("./secrets/public-certificate.pem")
};

const server = express();
const app = NestFactory.create(ApplicationModule, server);
app.init();

http.createServer(server).listen(3000);
https.createServer(httpsOptions, server).listen(443);

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

Related issues

anyx picture anyx  路  3Comments

thohoh picture thohoh  路  3Comments

cojack picture cojack  路  3Comments

marshall007 picture marshall007  路  3Comments

janckerchen picture janckerchen  路  3Comments