본문 바로가기

JavaScript/Next.js

Next.js 에서 https 사용법

1. 터미널에 아래와 같이 입력

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")

 

2. server.js에 https 서버 추가

const { createServer: https } = require('https');
const { createServer: http } = require('http');
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 ports = {
  http: 3080,
  https: 3443,
};

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

app.prepare().then(() => {
  http((req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
  }).listen(ports.http, (err) => {
    if (err) throw err;
    console.log(`> HTTP: Ready on http://localhost:${ports.http}`);
  });

  https(httpsOptions, (req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
  }).listen(ports.https, (err) => {
    if (err) throw err;
    console.log(`> HTTPS: Ready on https://localhost:${ports.https}`);
  });
});

 

3. 서버 작동

node server.js

'JavaScript > Next.js' 카테고리의 다른 글

내가 정리하는 Next.js  (0) 2021.11.06
Next.js Scripts  (0) 2021.11.03
React.js와 Next.js의 서버 배포 차이  (0) 2021.10.22
Next.js "window,document is not defined" 해결하는 법  (0) 2021.06.03
[next.js] setting  (0) 2021.05.21