If your API key is set in an .env file but your code logs undefined, the issue is almost always either where you are trying to access it or how it’s named.

Below is the quick fix.

my-api-key-is-coming-back-as-undefined-heres-how-to-fix-it

1. Environment Variables Don’t Automatically Work in the Browser

Most frameworks (like Next.js or Vite) do not expose server-side environment variables to the client by default.
This means if you’re doing something like:

console.log(process.env.API_KEY);

in React or client-side JavaScript, it will always return undefined.

The Fix

Rename your variable to include the public prefix your framework requires.

Next.js:

NEXT_PUBLIC_API_KEY=your_key_here

Then use it in the browser:

console.log(process.env.NEXT_PUBLIC_API_KEY);

Vite:

VITE_API_KEY=your_key_here
console.log(import.meta.env.VITE_API_KEY);

2. Restart Your Dev Server After Editing .env

Environment variables are loaded only when the server starts.

If you added a variable and didn’t restart, it won’t be picked up.

# Stop dev server
CTRL + C

# Restart it
npm run dev

3. Check That Your .env File Name Is Correct

Use the correct filename:

.env.local

or

.env

Make sure it’s in your project root, not inside /src.

4. Make Sure the Variable Name Matches Exactly

Environment variable names are case sensitive.

This:

NEXT_PUBLIC_API_KEY=abc123

must be referenced exactly like this:

process.env.NEXT_PUBLIC_API_KEY

Not:

process.env.next_public_api_key

Quick Recap

ProblemFix
Using env var in browser but variable is privateAdd NEXT_PUBLIC_ or VITE_ prefix
Value still undefinedRestart dev server
.env not loadingEnsure file is in project root
Variable still not foundCheck exact spelling and case

Final Working Example (Next.js)

.env.local:

NEXT_PUBLIC_API_KEY=abc123

Component:

export default function Home() {
  console.log("API KEY:", process.env.NEXT_PUBLIC_API_KEY);
  return <div>Check your console</div>;
}

✅ The key now appears.
❌ No more undefined.