DEV Community

Cover image for Using HTTPS in Next.js local Development
sinchang
sinchang

Posted on

Using HTTPS in Next.js local Development

Sometimes we need to use HTTPS in local development, but it doesn't support by the Next.js team officially. One of the solutions I figured out that is using the custom server, and you can find the example here.

Today, I want to share another solution is using Docker Compose to meet the same purpose.

Step1: Dockerize your Next.js App

Create file Dockerfile.dev with the below content.

FROM node:14.17.6-alpine as dev
RUN mkdir /app
WORKDIR /app
COPY package*.json ./
COPY yarn.lock ./
RUN yarn
EXPOSE 3000
CMD ["yarn" , "dev"]
Enter fullscreen mode Exit fullscreen mode

Step2: Generate development certificates using mkcert

You can follow the mkcert's document to making locally-trusted development certificates for your local domain like example.com. Generated cert files should be under the certs folder.

Step3: Update the local machine host

I recommend using the app SwitchHosts to organize hosts.

image

Step4: Create Docker Compose file

Create file docker-compose.yml with the below content.

version: '3.8'

services:
  nextjs:
    ports:
      - '3000:3000'
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - ./:/app
      - nextjs-dev-node_modules:/app/node_modules
      - nextjs-dev-next:/app/.next
    environment:
      - VIRTUAL_HOST=example.com
      - VIRTUAL_PORT=3000
    restart: always

  nginx-proxy:
    image: jwilder/nginx-proxy
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./certs:/etc/nginx/certs
    ports:
      - '80:80'
      - '443:443'
    depends_on:
      - nextjs
    restart: always

volumes:
  nextjs-dev-node_modules:
  nextjs-dev-next:
Enter fullscreen mode Exit fullscreen mode

Step5: Run Docker Compose

Just use the command docker-compose up --build, then you can see the web app content on https://example.com.

Discussion (0)