Last active
October 8, 2024 08:56
-
-
Save hos/9ac10156c6b63f7374032b1b16500d50 to your computer and use it in GitHub Desktop.
Workaround to use runtime variables in the next.js app (App Router), so you can change them after build.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { unstable_noStore as noStore } from 'next/cache' | |
export default function getEnv(name: string) { | |
noStore() | |
return process.env[name] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Script from 'next/script' | |
// Add this file to some Server Component, in my case I use this in `app/layout.tsx` | |
// Next.js, will inline all the process.env.SOMETHING variables into the code at build time. | |
// Which will force us to build the app for each environment we want to deploy to, with the | |
// only different being few environment variables. Instead, what we want is to get the environment | |
// dynamically from the runtime, so if we change them in the env and run the app again, it must | |
// use the new environment variables. To do this, we will inject the environment variables into | |
// the window object, so we can access them in the runtime. | |
// IMPORTANT: this can't be access with `process.env.SOMETHING`, as it will be replaced at build time, | |
// instead use the `getEnv` function from `env.tsx`. | |
const InjectRuntimePublicEnv = () => { | |
const env = Object.entries(process.env).reduce((all, [key, value]) => { | |
if (!key.startsWith('NEXT_PUBLIC_')) { | |
return all | |
} | |
all[key] = value | |
return all | |
}, {}) | |
return ( | |
<Script | |
id="inject-runtime-env" | |
strategy="beforeInteractive" | |
>{`window.process = ${JSON.stringify({ env }, null, 2)}`}</Script> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created a repo based on your codes. Also added context way to share env values across
./app/*
https://github.com/ritingliudd01/nextjs-14-get-runtime-env