Setting up a NextJS development server in a docker environment with networking

Currently, my development environment consists of a NextJS app running in a docker-compose setup under the name frontend.

The backend is powered by an expressjs app known as backend.

In my NextJS app, there's an environment variable that specifies the backend endpoint, which can be either http://backend:3000 or http://localhost:3000. However, setting different endpoints causes issues with client-side versus server-side querying in NextJS.

Is there a way to access the backend from both my host machine and the frontend container using the same URL?

Edited for clarity

version: "3.9"
services:
    frontend:
        image: node:18.14.2
        ports:
            - "8000:8000"
        volumes:
            - ./Frontend:/app
            #      - /app/node_modules/
            - /app/.next/
        environment:
            - NEXT_PUBLIC_BACKEND_BASE_URI=http://backend:3000
            - NEXT_PUBLIC_CMS_URL=http://cms:1337
        working_dir: /app
        command: sh -c "npm install --silent && npm run dev"
    frontend-graphql:
        image: node:18.14.2
        volumes:
            - ./Frontend:/app
            # - /app/node_modules/
            - /app/.next/
        environment:
            - NEXT_PUBLIC_BACKEND_BASE_URI=http://backend:3000
            - NEXT_PUBLIC_CMS_URL=http://cms:1337
        working_dir: /app
        command: sh -c "npm install --silent && npm run dev"
    backend:
        image: node:18.14.2
        ports:
            - "3000:3000"
        working_dir: /app
        volumes:
            - ./Backend:/app
        #      - /app/node_modules/
        command: sh -c "npm install && npm install -g ts-node && npm run dev"
    cms:
        image: node:18.14.2
        ports:
            - "1337:1337"
        working_dir: /app
        volumes:
            - ./CMS:/app
            - /app/node_modules/
        command: sh -c "npm install && npm install --platform=linux --arch=arm64v8 sharp && npm run dev"

Answer №1

In my experience, one of the most effective solutions I have come across involves a workaround using the host.docker.internal hostname.

It's worth noting that while host.docker.internal can be accessed directly within a docker container, with Next.js needing to access the backend server from "outside" the container (in the browser), I found it necessary to map

127.0.0.1 to host.docker.internal 

within the /etc/hosts file (this method has been tested on both Mac and Windows).

This setup permits client-side requests to reach , enabling the use of the same hostname for both client-side and server-side queries.

Answer №2

I came across a helpful resource on setting up server and public runtime configurations here. While there are concerns about deprecation, it is still possible to configure server runtime settings.

  1. Update the next.config.js file:
const nextConfig = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    apiUrl: process.env.NEXT_SERVER_API_URL || 'http://dockerbackend:8000'
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    apiUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
  }
}
  1. Modify the @/config/index.ts file:
import getConfig from 'next/config';

const config = getConfig();

let apiUrl = process.env.NEXT_PUBLIC_API_URL;
if (config) {
  apiUrl = config?.serverRuntimeConfig?.apiUrl
}

export {
  apiUrl
}
  1. Include the config file in your code wherever you need to access the API URL:
import { apiUrl } from '@/config'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access attributes of an unknown object (referencing 'Person')

I'm currently facing an issue when trying to POST data from my Next.js project to my MySQL database. Here is my frontend code: import React from 'react' import { useReducer, useEffect, useState } from 'react' import Axios from &ap ...

The progress bars in the Docker console are not showing up as expected

I'm attempting to incorporate one of npm's terminal progress bars to visually represent the progress of a lengthy process. When I execute it using the standard "node index.js" command, everything works smoothly. However, when running it from a ba ...

What could be causing the sanity cli to encounter an error during installation?

I'm facing an issue while attempting to execute the following commands: npm install -g @sanity/cli >> sanity init --coupon javascriptmastery2022 and this error message is displayed: sanity : File C:\Users\...\AppData\Roaming ...

Setting up Node.js 10 and npm on an Alpine Linux system

I am currently using Alpine to construct my Rails application and I am encountering complications with some of its dependencies. At this moment, here is my Dockerfile configuration: FROM ruby:2.5.1-alpine ENV BUNDLER_VERSION=2.0.2 RUN apk add --update - ...

Upon deployment, Dokku mistakenly categorizes my Node.js application as a Go app

After creating a Procfile with the following contents: web: node web.js I updated my package.json file as follows: { "name": "app-express", "version": "0.0.1", "private": true, "description": "web panel", "main": "web.js", "scrip ...

The nvm is functioning properly within the bash shell, however, it is not working within the

RUN curl --silent -o- https://raw.githubusercontent.com/creationix/nvm/v0.39.1/install.sh | bash - && \ . $HOME/.nvm/nvm.sh && \ nvm ls && \ chmod -R 777 /bin/ && \ nvm install ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

What are the steps to eliminate the package-lock.json warning while constructing a Node application image using Docker?

Exploring Docker to develop a compact Node.js application image, I aim to eliminate the warning provided below: npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Error message: "CORS issue arises in NextJS custom server following execution of 'npm run build'"

Everything was running smoothly until I needed to implement a production build with Server Side Rendering. Unable to utilize "next export," I ran into issues after executing "npm run build." Authentication failures led me to discover that the backend serve ...

Encountering a type error while trying to use Docker with npm install

Recently, I downloaded the latest Ubuntu docker image and equipped it with node, npm, among other necessary tools. While attempting to perform an npm install on my project, I keep encountering a recurring error. For demonstration purposes, I will only disp ...

Avoid the issue of having duplicate user ids by implementing a locked thread feature within Next.js

My database setup involves using MongoDB to store user data, with the user id incrementing each time a new user registers (e.g. 1, 2, 3, 4, etc). To generate the user id, I have the following code snippet. The collection where user data is stored is named ...

Ordering data in GraphQL by its unique identifier

After downloading a simple tutorial code, I found myself struggling to figure out how to sort by ID in GraphQL while playing around with it. Here is the query.js file: import React from "react"; import { useQuery } from "@apollo/react-hooks"; const Quer ...

The node-libxml-xsd library encounters an error stating "file not recognized: File format not recognized" while attempting a node-gyp rebuild, potentially causing issues with the xmljs.node file

Encountering an issue when attempting to create a Docker container for a Meteor app, node-gyp rebuild encounters failure while compiling node-libxml-xsd. The error reads: <command-line>:0:0: note: this is the location of the previous definition SO ...

Issue with handling a Promise Rejection error in a React/Next.js project while working with the openAI API

Currently, I am in the midst of working on a React/Next.js project where I have come across an error regarding Unhandled Promise Rejection within my code. Resolving this issue has proven to be quite challenging. Here are the specifics of the problem: Erro ...

Encountering a Mongoose Server Selection Error ECONNREFUSED while using a docker-compose file

My goal is to set up a sleek dockerized Mongo Express React Node stack. While Mongoose connects smoothly to my dockerized mongo when using node, it runs into issues inside docker. back.js : const express = require('express'); const app = expres ...

In order to link a package using npm, the package name must contain a specified name field

Hi there, currently I am grappling with the task of creating a docker image. A small section of my docker file is causing some trouble, and I suspect it's related to the nodejs package. The softlink in question looks like this: ls -la "/usr/bin/npm" ...

There was an error trying to read properties of undefined, specifically the 'prototype', in a code using Next.Js and Express

While attempting to incorporate express into my next.js project, I encountered errors when trying to initialize express: const express = require('express'); The errors that appeared were: Module not found: Can't resolve 'async_hooks ...

Securing your Next.js App with Express JWT Authentication

After setting up a /api/login endpoint to handle user login functionality, I created a login.js page to send form data to the login API. The login API authenticates user credentials stored in the database, generates a token, and saves it to a cookie. awai ...

Having trouble locating the services package.json file while executing docker-compose

While constructing a docker-compose.yml file within my workspace, I encountered an issue when attempting to run docker-compose. The error message I received was ENOENT: no such file or directory, open '/entity-service/package.json'. Interestingly ...

How to efficiently initialize a Next.js app with Phusion Passenger while triggering the production build using a specific file?

In most cases, a Next.js application is launched by using the command npm run start after compiling it with npm run build. I am unable to start it using a command because my web server stack (Phusion Passenger) requires a specific startup script. https:// ...