Skip to content

Instantly share code, notes, and snippets.

@hos
Last active October 8, 2024 08:56
Show Gist options
  • Save hos/9ac10156c6b63f7374032b1b16500d50 to your computer and use it in GitHub Desktop.
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.
import { unstable_noStore as noStore } from 'next/cache'
export default function getEnv(name: string) {
noStore()
return process.env[name]
}
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>
)
}
@ritingliudd01
Copy link

Thanks a million 🙏

@ritingliudd01
Copy link

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

@hos
Copy link
Author

hos commented Aug 10, 2024

@ritingliudd01 Very useful, thank you 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment