查看: 54|回覆: 0

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

[複製鏈接]

3

主題

1

回帖

0

積分

热心网友

金币
1
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-3-22
發表於 2021-4-15 10:50:00 | 顯示全部樓層 |閲讀模式

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.
 


来源:https://www.cnblogs.com/clblacksmith/p/14661471.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部