javascript|June 03, 2021|2 min read

Nextjs - How to Build Next.js Application on Docker and Pass API Url

TL;DR

Pass API URLs as build-time arguments in the Dockerfile using ARG and ENV since Next.js requires environment variables at build time, not runtime.

Nextjs - How to Build Next.js Application on Docker and Pass API Url

Introduction

In this post we will see:

  • How to prepare a docker image for your next.js application
  • Pass API url

Assumption Setup

We have:

  • An API backend to configure
  • Nextauth URL

Challenge

We have to pass URLs at build time, not run time. This is the point I struggled a lot with. So either you are building your Next.js build with docker or not, you need to pass variables at build time.

Code To receive URLs from Environment

First of all your code needs to use URLs from environment.

Whatever API you are calling, you need a base url. Your code needs to use url as below:

process.env.NEXT_PUBLIC_API_URL

# Example GET API

await axios.get(
  `${process.env.NEXT_PUBLIC_API_URL}/emails/count`
)

How to Pass URL from Environment

I have two variables to pass:

  • NEXT_PUBLIC_API_URL
  • NEXTAUTH_URL

From .env.local file

You can either place a file with name env.local and pass the values there.

NEXTAUTH_URL=YOUR_HOST:3000
NEXT_PUBLIC_API_URL=BACKEND_HOST:1337

# Do remember to use your host and port

Use next.config.js

Create a file named next.config.js at the root directory of your Next.js project.

module.exports = {
  env: {
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337',
    NEXTAUTH_URL: process.env.NEXTAUTH_URL || 'http://localhost:3000',
  },
}

Here, First I’m expecting these variables to come from environment. If not present in environment, I’m usin using the default one. So, those default one will be used during development.

Prepare Docker Image

Lets have a look at docker file:

# Install dependencies only when needed
FROM node:alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

# Rebuild the source code only when needed
FROM node:alpine AS builder

ARG NEXT_PUBLIC_API_URL
ARG NEXTAUTH_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV NEXTAUTH_URL=$NEXTAUTH_URL

WORKDIR /app
COPY . .
COPY --from=deps /app/node_modules ./node_modules
RUN npm run build && npm install --production --ignore-scripts --prefer-offline

# Production image, copy all the files and run next
FROM node:alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

USER nextjs

EXPOSE 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
ENV NEXT_TELEMETRY_DISABLED 1

CMD ["npm", "start"]

Here, I’m passing those environment variables here as:

ARG NEXT_PUBLIC_API_URL
ARG NEXTAUTH_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV NEXTAUTH_URL=$NEXTAUTH_URL

Build Docker Image

docker build 
  --build-arg NEXT_PUBLIC_API_URL=<YOUR_PUBLIC_HOST> 
  --BUILD-ARG NEXTAUTH_URL=<YOUR_API_BACKEND>
  -t <IMAGE_NAME_YOU_WANT> .

Deployment

I will post about Nginx Load Balancer and docker-compose in next post soon.

Related Posts

Nextjs - How to Redirect to Another Page and Pass State

Nextjs - How to Redirect to Another Page and Pass State

Introduction We have a page, for example a . And, upon submission we would want…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

Introduction In this post, we will use in Next.js with strapi. And, we will…

Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth

Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth

Introduction Next-auth is a fantastic library for abstracting handling of…

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

Introduction In this post, we will integrate Next.js with Strapi fully. And we…

How to Use Signin Signout Buttons in Next.js bootstrap project with Next-auth

How to Use Signin Signout Buttons in Next.js bootstrap project with Next-auth

Introduction In our last post, we have seen a full example of Next.js with…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…