~/javascript/nextjs-how-build-docker-with-api-url.md

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

2 min readJune 03, 2021by Gorav Singal#javascript#next-js
// 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.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

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…

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

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

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…

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 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

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…