I am using Nextjs 14 with the app router and I have some environment variables in my .env.local file:
NEXT_PUBLIC_API_URL=https://myapi.com
SECRET_KEY=mySecret
Inside my app, I need to access them:
// app/page.tsx
export default function Home() {
console.log(process.env.NEXT_PUBLIC_API_URL); // works
console.log(process.env.SECRET_KEY); // undefined
return <h1>Hello world</h1>
}
The problem is that the API works fine in the client component, but the secret key is always undefined, even in server components.
I already restarted the server and installed dotenv, but it doesn’t change anything. Now, my question is:
What is the correct way to access private environment variables in Nextjs 14 with the App Router?
Do I need to configure something special so that SECRET_KEY is available on the server side?
I appreciate your help.
I already restarted the server and installed dotenv, but it doesn’t change anything.
NEXT_PUBLIC_, you can use it even at client components. As for the ones without this prefix, server components can still access them. Can you elaborate, or maybe share your codebase if it's public? Also note that for server components, the console.log will be at the server terminal output, not in the browser.