Next.js Discord

Discord Forum

Next.js dynamic alias with process.env not working at runtime

Unanswered
Pteromalid wasp posted this in #help-forum
Open in Discord
Pteromalid waspOP
Hi everyone,

I'm trying to create a dynamic path alias in Next.js using a process.env variable (NEXT_PUBLIC_CLIENT). The goal is to have @branding point to different folders depending on the environment, e.g., communityapp by default or legion if set in .env.

However, it always falls back to the default value (communityapp) and only seems to change if I manually update my tsconfig.json. The runtime never picks up the environment variable.

Here’s my setup:

next.config.ts

import type { NextConfig } from "next";
import path from "path";

const client = process.env.NEXT_PUBLIC_CLIENT || "communityapp";

const nextConfig: NextConfig = {
  devIndicators: false,
  webpack: (config) => {
    config.resolve.alias["@branding"] = path.resolve(__dirname, `src/branding/${client}`);
    return config;
  },
  turbopack: {
    resolveAlias: {
      "@branding": path.resolve(__dirname, `src/branding/${client}`),
    }
  }
};

export default nextConfig;



tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@branding/*": ["src/branding/communityapp/*"]
    }
  }
}



page.tsx

"use client";

import React from "react";
import Image from "next/image";

import config from "@branding/config.json";
import "@branding/brand.css";
import logo from "@branding/assets/icon.png";

export default function LoginPage() {
  return (
    <div>
      <Image src={logo} alt="logo" />
      <h1>{config.companyName}</h1>
    </div>
  );
}



What I've tried:

* Updating next.config.ts alias for both webpack and Turbopack.
* Restarting the dev server after changing .env.
* Importing images dynamically with require().

Problem:
At runtime, @branding always resolves to communityapp, even though NEXT_PUBLIC_CLIENT=legion is set in .env.

Does anyone know how to make @branding truly dynamic based on an environment variable at runtime in Next.js 15+?

Thanks in advance!

1 Reply

Giant panda
The path aliases in tsconfig.json are used by the TypeScript compiler and not by Next.js at runtime. When you run next dev, the next.config.js file is loaded and the aliases for webpack and turbopack is set. These aliases are used by Next.js's bundler. However, tsconfig.json needs to be updated for the TypeScript compiler to recognize the new path, otherwise it will continue to point to the old location.
To fix this you need to create a script that update the tsconfig.json file before running next dev.