[Next.js] 로컬(localhost)에 https 적용하기

hzn·2023년 5월 7일
1

PROJECT🏝

목록 보기
22/24
post-thumbnail

1. HTTPS 사설 인증서 발급받기

  • mkcert라는 프로그램을 이용해서 로컬 환경(내 컴퓨터)에서 신뢰할 수 있는 인증서 만들 수 있다.

설치하기

brew install mkcert

인증서 생성

  • 로컬(내 컴퓨터)을 인증된 발급 기관으로 추가
mkcert -install
  • (localhost로 대표되는) 로컬 환경에 대한 인증서를 만들기
mkcert -key-file key.pem -cert-file cert.pem localhost 127.0.0.1 ::1

👉🏽 옵션으로 추가한 localhost, 127.0.0.1(IPv4), ::1(IPv6)에서 사용할 수 있는 인증서가 완성됨.
👉🏽 cert.pem, key.pem 이라는 파일이 생성된다.

프로젝트에 인증서 추가

  • 생성된 cert.pem, key.pem 파일을 프로젝트의 root 디렉토리에 넣어준다

2. 프로젝트에 적용하기

Next.js에서 custom server 사용하기

  • 프로젝트의 root 디렉토리에 server.js를 만든다

server.js (https 적용 전 / http 서버만 있는 상태)

const http = require("http");
const { parse } = require("url");
const next = require("next");

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

const PORT = 3000;

app.prepare().then(() => {
  http
    .createServer((req, res) => {
      // Be sure to pass `true` as the second argument to `url.parse`.
      // This tells it to parse the query portion of the URL.
      const parsedUrl = parse(req.url, true);
      handle(req, res, parsedUrl);
    })
    .listen(PORT, (err) => {
      if (err) throw err;
      console.log(`> Ready on http://localhost:${PORT}`);
    });
});
  • http://localhost:3000 으로만 접속 가능한 상태

server.js (https 적용 후)

const http = require('http');
const { parse } = require('url');
const next = require('next');

const https = require('https');
const fs = require('fs');

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

const PORT = 3000;

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

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

  // https 서버 추가
  https
    .createServer(httpsOptions, (req, res) => {
      const parsedUrl = parse(req.url, true);
      handle(req, res, parsedUrl);
    })
    .listen(PORT + 1, (err) => {
      if (err) throw err;
      console.log(`> HTTPS: Ready on https://localhost:${PORT + 1}`);
    });
});
  • http://localhost:3000, https://localhost:3001 으로 접속 가능

3. script 변경

  • package.json에서 dev script를 next dev에서 node server.js로 변경한다.
  • 이제 yarn dev를 실행하면 http://localhost:3000 또는 https://localhost:3001 으로 접근 가능하다.


레퍼런스

0개의 댓글