Reputation: 21
In our implementation process we created a single building and went through the different stages (integration, staging and production). In each of the environments, we have variable environmental differences.
The problem is that when we started the server it only referred to the environment variables on the server, but in the client the process.env file is empty.
stack: "next": "5.0.0" "babel-plugin-inline-dotenv": "1.1.1",
for load .env file is used "inline-dotenv"
Upvotes: 2
Views: 13119
Reputation: 511
To read runtime environment variables, we recommend using getServerSideProps or incrementally adopting the App Router.
This is the recommended technique by Next.js docs for Build Once Deploy Anywhere.
Upvotes: 0
Reputation: 271
I struggled a lot with this, because I can not afford building docker images for each environment like qa, stage, production and so on. So, I created the following npm package. Please check, maybe it will save many hours of life for someone: next-config-env-variables-patch
Upvotes: 2
Reputation: 146
You can use publicRuntimeConfig
in your next.config.js file.
Example:
// next.config.js
module.exports = {
serverRuntimeConfig: { // Will only be available on the server side
mySecret: 'secret'
},
publicRuntimeConfig: { // Will be available on both server and client
staticFolder: '/static',
mySecret: process.env.MY_SECRET // Pass through env variables
}
}
note that the value of publicRuntimeConfig.mySecret
is now getting fetched from the environment variables.
So now you can read that value by importin next/config
Example:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.mySecret);
source: next.js docs
Upvotes: 7