HTTPS on localhost using NextJS + Express
You just need to use the createServer
method of https
module.
const { createServer } = require('https');const { parse } = require('url');const { readFileSync } = require('fs');const next = require('next');const port = 3000;const dev = process.env.NODE_ENV !== 'production';const app = next({ dev });const handle = app.getRequestHandler();const httpsOptions = { key: readFileSync('./certificates/key.pem'), cert: readFileSync('./certificates/cert.pem')};app.prepare() .then(() => { createServer(httpsOptions, (req, res) => { const parsedUrl = parse(req.url, true); handle(req, res, parsedUrl); }).listen(port, err => { if (err) throw err; console.log(`> Ready on https://localhost:${port}`); }) });
Other answer seemed to just drop express... Found a solution after some difficulty with both server code and certificate so hopefully can save someone else the trouble!
First of all, solid advice for creating localhost certificate here:https://letsencrypt.org/docs/certificates-for-localhost/
Secondly, simple code that offers HTTP/HTTPS with next js and express:
const next = require('next');const express = require('express');const http = require('http');const https = require('https');const fs = require('fs');const ports = { http: 3080, https: 3443}const dev = process.env.NODE_ENV !== 'production';const app = next({ dev });const handle = app.getRequestHandler();const server = express(); const options = { key: fs.readFileSync('localhost.key'), cert: fs.readFileSync('localhost.crt'), };app.prepare().then(() => { server.all('*', (req, res) => { return handle(req, res) }); http.createServer(server).listen(ports.http); https.createServer(options, server).listen(ports.https);});
It is worth noting that one could omit or redirect either port.
Below work for me very well for next server with https;
Using this official documentation of node js https module Creating HTTPS Server
const { createServer } = require('http')const { parse } = require('url')const next = require('next')const { readFileSync } = require('fs');const port = parseInt(process.env.PORT, 10) || 3000const dev = process.env.NODE_ENV !== 'production'const app = next({ dev })const handle = app.getRequestHandler()const httpsOptions = { pfx: readFileSync('./certificates/AMB.pfx'), passphrase: 'Testabc$' };app.prepare().then(() => { createServer(httpsOptions, (req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl if (pathname === '/login') { app.render(req, res, '/login', query) } else { handle(req, res, parsedUrl) } }).listen(port, err => { if (err) throw err console.log(`> Ready on https://localhost:${port}`) })})