Next.js supports environment variables out of the box and thankfully they’re very easy to use.
If you’re unfamiliar with environment variables it’s likely you haven’t built applications that are run in multiple environments. In the most simplest example, two environments your application will run in is development (when you’re writing code) and production (when you deploy it to a server).
It’s not necessary for all cases, but in many cases there will be times you want to use a different API URL or secret key. For example, during development you may want to use the development API URL which is
development-api.domain.com instead of the live API URL which is
Another example is when you’re integrating with Stripe. During development and testing, you want to use the test API keys so that you don’t make real payments.
Simple! In the root of your Next.js application create a
.env file. Inside this file, declare all environment variables you need like this:
NEXT_PUBLIC_API_URL = "https://development-api.domain.com" STRIPE_KEY = "*************"
Then, in your code you can reference these variables by using
For example, making a GET request to the API using axios might look something like this:
Glad you asked! It’s important to remember there are two parts to a Next.js application. One is the React application built using React components and displayed to the user (client). The other half of the Next.js application is anything that is run on the server.
getServerSideProps()methods declared on your pages
getStaticProps()declared on your pages
These three features always execute on the server and therefore have access to the Node.js process. Since this data is never directly sent to the client, it is safe to use sensitive values such as Stripe keys.
On the other hand, data sent to the client can easily be fiddled with and therefore it is dangerous to send sensitive values to the client.
For this reason, Next.js does not allow any environment variables to be accessed by client code unless it is prefixed with
If you have environment variables that your React components need access to, you must prefix them with
NEXT_PUBLIC_. If you have variables that will only be used on the server-side, you do not need to prefix them like the
STRIPE_KEY example above.
.envfile to source control
Best practise here is to create a
.env.example file that has all the environment variabes needed. When deploying to a server, or working with other developers the
.env.example file can be used as a template to fill out all the environment variables required to run the app.
.env usually contains sensitive data such as secret keys and tokens. For this reason it is recommended that you do not include it in source control. Consider adding the
.env file to your
Here are some tips you can try if your environment variables aren’t working for you:
.envfile require the Next.js development server to be restarted