Skip to content

Environment variables

Environment variables are pieces of data that are available to your whole project. They are exposed to your project at build-time, so if you add/change an environment variable, do not forget to restart your dev server / redeploy your site.

In your local filesystem, environment variables should live in a .env file that is never uploaded to the repository. Even if the repository is private, it is a very bad practice to upload keys to the repo and they should only live in your local system.

All developers working in a project must have a .env file that they use but each of them must update this file locally.

You will need to declare these variables in your deployment environment to be able to access them. In Netlify, go to your project > Project Configuration > Environment Variables and you should see a screen like this:

environment variables in Netlify

You will see the available environment variables and have the option to create new ones. You can upload your env file directly or create each variable on its own. When creating a variable, you will see a screen like this:

create environment variables in Netlify

If you want to use different keys for different branches, you can do it by choosing the option ‘Different value for each deploy context’ in the ‘Values’ section.

create branch-specific environment variables in Netlify

Here you can either give a value for all branches (so all branch deployments will use this value and your main branch will use the Production value) or give specific values to specific branches by using the options at the bottom.

This is useful when you need to use one database for your production environment and a different one for your stage branch, for instance.

There are two ways of accessing your variables, depending on where you are working from.

If you access a variable from your client-side, it will be exposed to the browser. Keep this in mind when working with sensible keys, as they should never be accessed from client-side files.

Your client-side variables need to be prefixed by PUBLIC_ (in Astro) and VITE_ (in Vite projects) and can be accessed using import.meta.env.PUBLIC_KEY_NAME.

Variables that are not correctly prefixed will be ignored by import.meta.env.

These can be non-sensitive information such as public keys, environment info…

Here is where you should access your private keys. You can do this from server-side files by using process.env.KEY_NAME. These will never be exposed to the browser.