0

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.

3
  • I've tried to replicate your issue, but clean Next.js 14 App Router app works as expected - if you prefix the variable with 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. Commented Aug 24 at 18:36
  • Turns out the issue was that I was calling the wrong variable name. The variable was SECRET_KEY and y was trying to call it as SECRT_KEY. After fixing the variable name, everything worked as expected. Thanks for your help Commented Aug 25 at 13:31
  • Really appreciate the time with this question. Commented Aug 30 at 22:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.