查看: 125|回复: 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:dzh188@hotmail.com

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

在本版发帖返回顶部