티스토리 뷰

728x90
반응형

nextjs 기반의 프로젝트는 아래의 명령어를 통해 로컬 개발서버를 실행하게 됩니다

 

npm run dev
yarn dev

 

그런데 다른 목적으로 http 서버를 직접 커스텀하여 실행해야하는 경우가 있는데요

 

대표적인예가 SSL인증서를 등록하여 https 서버를 실행하는 경우가 있겠네요

 

nextjs 공식문서에는 이를 위한 고급안내 문서가 있습니다

 

https://nextjs.org/docs/advanced-features/custom-server

 

Advanced Features: Custom Server | Next.js

Start a Next.js app programmatically using a custom server.

nextjs.org

 

 

기본적인 구조는 다음과 같습니다

 

// server.js
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = 3000
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      // 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)
      const { pathname, query } = parsedUrl

      if (pathname === '/a') {
        await app.render(req, res, '/a', query)
      } else if (pathname === '/b') {
        await app.render(req, res, '/b', query)
      } else {
        await handle(req, res, parsedUrl)
      }
    } catch (err) {
      console.error('Error occurred handling', req.url, err)
      res.statusCode = 500
      res.end('internal server error')
    }
  }).listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://${hostname}:${port}`)
  })
})

 

 

이렇게 코드를 작성하여 프로젝트의 루트에 server.js 라는 파일을 생성하고

 

package.json 파일의 명령어로 이 파일을 실행하는 명령어를 넣으면 됩니다

 

"scripts": {
  "dev:custom": "node server.js",
}

 

SSL인증서를 등록하여 https 서버를 실행할때는 이렇게 작성해주세요

 

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

const hostname = "호스트명";
const port = 포트번호;

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

const httpsOptions = {
  key: fs.readFileSync("키파일경로"),
  cert: fs.readFileSync("인증서파일경로"),
};

app.prepare().then(() => {
  createServer(httpsOptions, async (req, res) => {
    try {
      const parsedUrl = parse(req.url, true);
      await handle(req, res, parsedUrl);
    } catch (err) {
      console.error("Error occurred handling", req.url, err);
      res.statusCode = 500;
      res.end("internal server error");
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on https://${hostname}:${port}`);
  });
});

 

로컬개발시 사용할 인증서를 만드는 방법도 알고 싶으시다면 아래 링크를 참조하세요

https://trend21c.tistory.com/2267

 

로컬환경에서 사용할 개발용 SSL 인증서 만들기

아래 가이드는 Mac을 기준으로 작성되어있습니다 로컬환경에서 개발을 할때 ssl 인증서가 필요한 경우가 있습니다 로컬환경에서 사용할 개발용 인증서를 만들기 위해 brew를 통해 mkcert를 설치합

trend21c.tistory.com

 

 

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함