How to properly set environment variables in Next.js app deployed to Vercel?

Simply creating a .env.local (or .env) file with your environment variables should be enough to be picked by Next.js on the server. There’s no need to add anything to your next.config.js.

# .env.local

CLIENT_URL=vxcxsfddfdgd
MAILING_SERVICE_CLIENT_ID=1245785165455ghdgfhasbddahhhhhhhhm
MAILING_SERVICE_CLIENT_SECRET=Rdfvcnsf4263543624362536
MAILING_SERVICE_REFRESH_TOKEN=000000
[email protected]

However, if you need to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_.

NEXT_PUBLIC_CLIENT_URL=vxcxsfddfdgd

This will be available on the browser using:

process.env.NEXT_PUBLIC_CLIENT_URL

For more details about environment variables in Next.js refer to https://nextjs.org/docs/basic-features/environment-variables.


The same principle applies to environment variables you create in Vercel (or any other hosting service), adding the prefix will make them available to the browser.

You can add environment variables in Vercel through the Environment Variables page of your Project Settings, that match the variables in your .env.local.

For more details about environment variables in Vercel refer to https://vercel.com/docs/concepts/projects/environment-variables.

Leave a Comment