Next.js Discord

Discord Forum

Runtime dynamic env variables, that need to be exposed to client

Answered
Knopper gall posted this in #help-forum
Open in Discord
Avatar
Knopper gallOP
I have a situation, where I'm building a nextjs frontend into a docker container, which needs to run on k8s, so the environment variables need to be overridable.
In this specific case, I have an API_URL env variable, which the browser also needs to know; which needs to be overridable.

I tried doing the following
const apiUrl = process.env.API_URL
console.warn({apiUrl})
if (!apiUrl) throw new Error("env variable API_URL missing")

export default function RootLayout({ children }: PropsWithChildren) {
  return (
    <html lang="en">
      <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
        <App apiUrl={apiUrl!}>
          {children}
        </App>
      </body>
    </html>
  )
}


"use client"
export type AppProps = PropsWithChildren & {
  apiUrl: string,
}

export default function App({ children, apiUrl }: AppProps) {
  const client = new ApolloClient({
    uri: apiUrl,
    cache: new InMemoryCache(),
    ssrMode: true,
  })
  console.warn("passed api url:", apiUrl)

  return (
    <ApolloProvider client={client}>
      {children}
    </ApolloProvider>
  )
}


But this is printing two different env variables, the server one is the one that i passed to docker run -e API_URL=http://test, and the client one is the one from my .env file (i cannot seem to build the project unless i add an .env file, it seems to run the code and gives errors when generating /_not_found)

So how would i approach this?
Answered by Asian black bear
View full answer

2 Replies

Avatar
Asian black bear
Answer
Avatar
Knopper gallOP
Great, that seems to do it