Can next.js rewrites be configured with environment variables?

Currently, I am in the process of developing my application with a next.js frontend and express.js backend. During development, I simply run the relevant dev servers in the terminal. However, now I am looking to deploy my app using Docker for production. In this setup, I want the IP of my API to be the name of the container instead of localhost. Additionally, I wish to use different ports for development and production.

During the development phase, I hardcoded rewrites in my code like so:

const nextConfig = {
  reactStrictMode: true,
  async rewrites() {
    return [
      {
        source: "/api/:path*",
        destination: `http://localhost:5000/api/:path*`,
      },
      {
        source: "/auth/:path*",
        destination: `http://localhost:5000/auth/:path*`,
      },
    ];
  },
};

module.exports = nextConfig;

This setup worked well during development. But as I transitioned towards production, I wanted the destination URL to be based on environment variables. For instance, in the dev environment, the destination for /api would be http://localhost:5000/api, while in production it should be http://api:5100/api (referring to the api Docker container).

Unfortunately, after some troubleshooting, I discovered that using environment variables in the next.config.js is not supported, as detailed in this GitHub issue: https://github.com/vercel/next.js/issues/21888.

Given this limitation, I am seeking advice on alternative methods to achieve environment-dependent rewrites since direct usage of environment variables is not feasible. Any suggestions or insights would be greatly appreciated.

Answer №1

Take a look and see if you can crack this case using middleware. Unlike next.config.js, middleware is able to access runtime environment variables.

// middleware.ts

import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: ["/api/:path*", "/auth/:path*"],
};

export function customMiddleware(request: NextRequest) {
  return NextResponse.rewrite(
    new URL(
      `${process.env.API_HOST}${request.nextUrl.pathname}${request.nextUrl.search}`
    ),
    { request }
  );
}

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

JavaScript alert causing disruption to Ajax requests

Currently, I am utilizing JQuery Ajax to retrieve a script from the server. $.ajax({ url: src, type: "GET", dataType: "script", timeout: transaction_timeout }).done(function(){}) .fail(function() { alert("Error in server");}) .always(funct ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Angular 4: Triggering a function by clicking a link with specific parameters

I am relatively new to working with Angular 4. I have an anchor tag that, when clicked, should redirect me to a link where I also need to pass parameters. I'm unsure if my current approach is correct or not. Above all, I really need guidance on how to ...

Unable to add an event while looping through a NodeList in JavaScript

Seeking assistance in iterating a NodeList object using javascript, and implementing a click event for each item : document.addEventListener("DOMContentLoaded", async () => { try { posts.map(post => { container.innerHTML += out ...

Building multiple files in React allows developers to divide their code

Can a React/Redux application be split into modules during webpack build? For example, having a set of components for users and another set for invoices. I want webpack to generate users.js and invoices.js that can be imported into index.html. If I make ch ...

What is the specific operation of this function?

Could someone clarify how this function operates? I have a grasp on the ternary operator, which checks if the flag is true and if not, then it uses the second value. However, I am unsure why flag is initially a Boolean and how it toggles between true and ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Adding a disabled internal Style node to the HTML5 DOM: A simple guide

According to this, the style tag can be turned off using the disabled attribute. I attempted the following: <head> <style>body { color: black; }</style> <style disabled>body {color: red; }</style> </head> <bo ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...

Order JSON object based on designated Array

I'm looking to organize a JSON object in a specific order, Here is the current object structure: { "you": 100, "me": 75, "foo": 116, "bar": 15 } I would like to rearrange this object in the following sequence ['me', 'foo', &apos ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Making an ajax request to update the value of a specific key in an object

I am currently working with a firebase database that contains multiple collections. Using the code provided, I have managed to successfully retrieve an array that consists of all attractions with an area_id that matches the area_id of e.target. However, t ...

Manipulating strings in Discord.js

if(msg.content.includes("[mid]")) { let str = msg.content let pokeID = str.substring( str.indexOf("[mid]") + 5, str.lastIndexOf("[/mid") //get the unique-code for a pokemon ); msg.channel.send ...

Update nested child object in React without changing the original state

Exploring the realms of react and redux, I stumbled upon an intriguing challenge - an object nested within an array of child objects, complete with their own arrays. const initialState = { sum: 0, denomGroups: [ { coins: [ ...

Switch out a character with its corresponding position in the alphabet

Starting out, this task seemed simple to me. However, every time I attempt to run the code on codewars, I keep getting an empty array. I'm reaching out in hopes that you can help me pinpoint the issue. function alphabetPosition(text) { text.split ...

Using destructuring repeatedly for a single object property

At times, I engage in nested destructuring, where I go more than one level deep. It can be risky, but I always make sure the property exists to avoid encountering an error of undefined. Recently, I came across this scenario: const { match: { ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...