NextJS - Set dynamic environment variables at the start of the application

丶灬走出姿态 提交于 2020-02-02 13:22:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!