HTTPS on localhost using NextJS + Express

后端 未结 4 1950
灰色年华
灰色年华 2021-02-06 15:39

System Information

  • Express: 4.16.4
  • NextJS: 8.0.3
  • React: 16.8.4
  • ReactDOM: 16.8.4

Goal

4条回答
  •  轮回少年
    2021-02-06 16:33

    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.

提交回复
热议问题