Yes, exactly! Once you set environment variables in your Vercel project settings, you can access them in your code using process.env.VARIABLE_NAME.
Here's how it works:
Server-side (Server Components, API Routes, Server Actions):
// Access any environment variable directly
const apiKey = process.env.DATABASE_URL
const secret = process.env.API_SECRETClient-side (Client Components, browser code):
// MUST be prefixed with NEXT_PUBLIC_
const publicKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYKey points:
process.env.VARIABLE_NAME in server contexts (Server Components, API routes, Server Actions)NEXT_PUBLIC_ to be accessible in the browser. This is a security feature to prevent accidentally exposing secrets.process.env is automatically available in Next.js.env.local file, but in Vercel's production/preview environments, the dashboard values are used automaticallySo yes, you just use the name directly with process.env.YOUR_VARIABLE_NAME and Vercel handles the rest!
Almost! It depends on where this code runs:
✅ Works in server-side contexts:
app/api/*/route.ts)// ✅ Server Component or Server Action
const response = await fetch(
process.env.API_URL, // Works!
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}
)❌ Does NOT work in client components:
If this code is in a Client Component (has "use client" at the top), you need to prefix it:
// ❌ Client Component - won't work
const response = await fetch(
process.env.API_URL, // This will be undefined!
// ...
)
// ✅ Client Component - correct way
const response = await fetch(
process.env.NEXT_PUBLIC_API_URL, // Must have NEXT_PUBLIC_ prefix
// ...
)Best practice: Keep API calls with sensitive environment variables in Server Actions or API Routes, not in client components. This keeps your secrets secure on the server.