'Runtime configs in nextjs
I'm trying to setup my nextjs app to use runtime configurations. Basically, I have an endpoint url that needs to be available trough docker env vars. I configured following these docs but it isn't working. My app still using default values from .env file. Could anyone help to understand what I missed or did wrong? Thanks!
docs: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration https://nextjs.org/docs/advanced-features/custom-app
steps: 1- added to my next.config.js
publicRuntimeConfig: {
NEXT_PUBLIC_BACKEND_HOST: process.env.NEXT_PUBLIC_BACKEND_HOST,
},
2- retrieved config in my pages
const { publicRuntimeConfig } = getConfig()
const baseURL = publicRuntimeConfig.NEXT_PUBLIC_BACKEND_HOST
3- created a custom app to setup getInitialProps
Runtime configuration won't be available to any page (or component in a page) without getInitialProps.
import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
return { ...appProps }
}
export default MyApp
Solution 1:[1]
Everything seems fine in your code, tested in a fresh project and everything worked correctly. Therefore I think the issue is that you don't actually have NEXT_PUBLIC_BACKEND_HOST
env var set when you're running next start
. Btw, you don't need to use the NEXT_PUBLIC
prefix in this kind of usage. If you want build time args you can use NEXT_PUBLIC_
prefix to have the var be available both client and server side by just using process.env.NEXT_PUBLIC_
anywhere. Note that in that case the value will be inlined at build time, so the env var needs to be present during build.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |