Nextjs 环境变量始终未定义 [英] Nextjs env variable is always undefined

查看:23
本文介绍了Nextjs 环境变量始终未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目设置是这样的:

My project setup is like this:

project-ci (only docker)
  nextjs
  backend

Staging 和 Production 是相同的,所以我传入了 staging 的 docker-compose.yml 文件只有这个参数(两个环境都是先用这些命令构建的 npm run build然后 npm run start)

Staging and Production are the same so I pass in docker-compose.yml file of staging only this argument (both environments are built with these commands first npm run build and then npm run start)

args:
    NEXT_PUBLIC_URL: arbitrary_value

Dockerfile 的 nextjs 中放上这些命令

in Dockerfile of the nextjs put these commands

ARG NEXT_PUBLIC_URL
ENV NEXT_PUBLIC_URL=$NEXT_PUBLIC_URL

然后可以在 nextjs 中使用 process.env.NEXT_PUBLIC_URL 访问该变量.到目前为止,如果我尝试在 index.js 中使用 console.log(process.env.NEXT_PUBLIC_URL),则该值始终为 undefined.任何想法有什么问题,也检查了文档,但结果仍然是 undefined

so variable will then be accessible in nextjs with process.env.NEXT_PUBLIC_URL. So far if I try to console.log(process.env.NEXT_PUBLIC_URL) in index.js the value is always undefined. Any ideas what is wrong, also checked the docs but the result was still undefined

https://nextjs.org/docs/api-参考/next.config.js/runtime-configuration

https://nextjs.org/docs/api-参考/next.config.js/环境变量

推荐答案

您可以使用公共运行时配置属性访问 env 变量:

You can access env variables using public runtime config property:

next.config.js

next.config.js

module.exports = {
    publicRuntimeConfig: {
      NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
    }
};

然后:

import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.NEXT_PUBLIC_URL);

如果它不起作用,请确保在 docker 容器中创建 env 变量

If it doesn't work, make sure the env variables are created inside docker container

这篇关于Nextjs 环境变量始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆