검색
검색
공개 노트 검색
회원가입로그인

윈도우 10에서 nextjs localhost https 적용하기

next로 개발하다보면 모바일에서 테스트해야 할 때가 온다. 이때 https가 필요해서 세팅을 하게 되었다. 서버와 프론트 둘 다 세팅이 필요하다.

서버 세팅하기

먼저 mkcert로 인증서를 만들자. 로컬 환경에서 쉽게 인증서를 만들 수 있게 해준다.

윈도우 10에는 chocolatey가 기본적으로 설치되어 있다. choco로 mkcert를 인스톨해준다.

@ cmd 관리자 권한 창

choco install mkcert

그 후 mkcert 세팅을 해준다. 이렇게 하면 시스템의 trust store 에 자동으로 등록해 준다.

mkcert -install

이 후 mkcert에 사용할 도메인을 등록해 준다. 나는 localhost와 내 ip를 등록했다.

mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1

여기서 loalhost.pem 과 localhost-key.pem 과 같은 퍼블릭키와 개인키 한 쌍이 나온다.


이걸 서버 디렉토리에 복사해 준다. 로컬에서만 쓸것이므로 gitignore에 추가해 주는 것을 잊지 말자.


그 다음 서버의 app.js에 다음과 같이 추가해 주면 된다.

const https = require("https");  
const http = require("http");  
  
...  
  
const HTTP_PORT = 8000;  
const HTTPS_PORT = 9000;  
  
const options = {  
  key: fs.readFileSync("localhost-key.pem", "utf8"),  
  cert: fs.readFileSync("localhost.pem", "utf8"),  
};  
  
http.createServer(app).listen(HTTP_PORT);  
  
https.createServer(options, app).listen(HTTPS_PORT, () => {  
  console.log("Node server is wating for port " + app.get("port"));  
});  

readFileSync의 경로는 절대 경로다.
이제 9000 포트로 접속해 보면 잘 나올 것이다. https://localhost:9000

프론트

next에도 https를 세팅해 줘야 한다. https끼리만 통신이 되기 때문이다.
먼저 두 키 파일을 넥스트의 루트 경로에 복사해준다.
그 다음 프론트의 루트 경로에 server.js를 만들어 준다.

@server.js

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("localhost-key.pem"),  
  cert: fs.readFileSync("localhost.pem"),  
};  
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("Server started on https://localhost:3000");  
  });  
});  

그 다음 package.json에 scripts의 dev를 다음과 같이 변경해 준다.

  "scripts": {  
    "dev": "cross-env NODE_EXTRA_CA_CERTS=\"C:\\Users\\UserName\\AppData\\Local\\mkcert\\rootCA.pem\" node server",  
    ...  
  },  

여기서 CA_CERTS는 rootCA로 mkcert를 설치할 때 같이 설치된다. 이 파일은 네트워크 중간에 끼어들 수 있는 권한이 있으므로 외부에 노출이 되면 안된다. 이 중간 지점의 인증서 경로가 있어야지 인증서 chain이 만들어 진다.

경로가 어디있는지 확인해 보려면 cmd창에서 다음과 같이 입력해 보면 된다.


mkcert -CAROOT

cross-env는 윈도우에서 node 환경 변수를 주입할 수 있는 패키지이다. 설치되지 않았다면 설치해 주자.


yarn add cross-env


또는

npm install --save-dev cross-env  

이제 yarn dev를 실행해 주자. 인증서 chain을 만들지 않아도 넥스트 서버가 동작하기는 하는데 실제 요청을 보내면


error: unable to verify the first certificate

이런 에러를 뱉는다.

그냥 모바일에서 만든걸 확인하려고 했던건데 세팅하는데 꼬박 하루가 걸렸다. 다음 사람이나 내일의 나를 위해 남겨 두자.

여담으로 모바일에서 접속해서 보려고 하는데 https까지 적용한 이유는 나는 http only 쿠키를 세팅하는데 ip를 사용하면 (같은 네트워크 환경에서 접속하려면 ip로 접속해야 한다.) https가 없으면 쿠키 세팅에 실패한다 ㅠㅠ

공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기
조회수 : 1167
heart
T
페이지 기반 대답
AI Chat