问题
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"
回答1:
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
来源:https://stackoverflow.com/questions/50416138/nextjs-set-dynamic-environment-variables-at-the-start-of-the-application