Quick tip: .env in next.js
Fredrik BergqvistUsing environment variables is a great way to store environment-specific values and secrets that should not be in the git repo.
Let's say you have an API which runs on localhost locally but a different host in production.
On the server
Locally you need to add an .env.local
-file in your project root containing a variable for the API host name, let's call it API_HOST
and point it to localhost port 8080.
# .env.local in project root
API_HOST=http://localhost:8080
You would then need to add the environment variable to your production env as well. This will look different depending on your hosting provider, but on Google Cloud Run it looks like this:
On the client
To expose your environment values to the client, you need to add them to your
next.config.js
In most cases keeping using the variable on the server is enough, but in some cases you might need to access the environment variable on the client as well and in those cases you need to add the variable to your next.config
.
// next.config.js
module.exports = {
env: {
API_HOST: process.env.API_HOST
}
}