Secure your local development server with HTTPS (Next.JS)

https://anmagpie.medium.com/secure-your-local-development-server-with-https-next-js-81ac6b8b3d68

Create certificate

Creating a certificate for localhost is easy with openssl . Just put the following command in the terminal. The output will be two files: localhost.key and localhost.crt

openssl req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj '/CN=localhost' -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

Click on the crt file, on macOS the keychain app will open, add the key to it.

Now double click on it and under the trust section you will see “When using this certificate” select “Always Trust”.

Next.js

Now in Next.js we have to create our own server.js file if not already.

const { createServer } = require('https');
const { parse } = require('url');
const next = require('next');
const fs = require('fs');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const httpsOptions = {
  key: fs.readFileSync('./certificates/localhost.key'),
  cert: fs.readFileSync('./certificates/localhost.crt')
};

app.prepare().then(() => {
  createServer(httpsOptions, (req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
    
  }).listen(3000, err => {
    if (err) throw err;
    console.log('> Ready on https://localhost:3000');
  });
});


Modify the package.json:

"scripts": {
  "dev": "node server.js",
  "build": "next build",
  "start": "cross-env NODE_ENV=production node server.js"
},


Run the server, you now have a secure connection to localhost.
 
posted @ 2021-04-15 10:50  耕读编码  阅读(101)  评论(0编辑  收藏  举报