Next.js Discord

Discord Forum

Issues with NEXT_PUBLIC_VERCEL_ENV

Answered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Orinoco CrocodileOP
I have a NextJS project hosted on Vercel. In one of the client side React components I console.log process.env.NEXT_PUBLIC_VERCEL_ENV and always get undefined (on dev / preview).

From my understanding NEXT_PUBLIC_VERCEL_ENV shouldn't have to be set in .env.local but automatically be available? (as per: https://vercel.com/docs/projects/environment-variables/system-environment-variables).

My Framework Preset is set to Next.js. I have "Automatically expose System Environment Variables" checked in Project Settings > Environment Variables.

Anyone got an idea why?
Answered by Orinoco Crocodile
It actually works 🎊

For anyone else reading this: console.log(process.env.NEXT_PUBLIC_VERCEL_ENV) will be undefined locally but resolve to "preview" in preview and "production" in production.

This does make sense after reading ☝️
View full answer

6 Replies

from what I understand it is available only in the build step
Orinoco CrocodileOP
What does that entail?

VERCEL_ENV is available (privately) in node
NEXT_PUBLIC_VERCEL_ENV is available (publicly) in JS, but only during build time?

What use case is there even for using it? The build step is automatic, isn't it?
I simply want an environment variable that defines what environment I'm in. NODE_ENV doesn't cut it, because it's not aware of Vercel's own "preview" -environment.

And while setting these manually per-environment in Project Settings > Environment Variables might work, I'm under the impression that I should be able to extract them from process.env without any extra work.

Furthermore this works for my Svelte app (also hosted on Vercel). Mabye that's because Svelte IS being built every time before visible on the frontend?
I'm guessing my use-case is very normal, so I'm curious on how ya'll get a hold on the value of VERCEL_ENV in client side code
Orinoco CrocodileOP
I just saw this section in the docs. That explains why it wouldn't work on dev. But it is also undefined in a preview deploy 🤔
Orinoco CrocodileOP
It actually works 🎊

For anyone else reading this: console.log(process.env.NEXT_PUBLIC_VERCEL_ENV) will be undefined locally but resolve to "preview" in preview and "production" in production.

This does make sense after reading ☝️
Answer