next.js 环境变量未定义(Next.js 10.0.5) [英] next.js environment variables are undefined (Next.js 10.0.5)

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

问题描述

我正在使用 Next.js 编写一个网站,并尝试添加 google 跟踪代码管理器.
我按照 Next.js Github 示例的教程进行操作,但由于某些原因,我无法访问我的环境变量.
它说我的变量是未定义的.
我在我的项目文件夹中创建了一个 .env.local 文件(与组件、node_modules、页面等处于同一级别)
在这个文件中,我创建了一个这样的变量(测试目的):

I am coding a website with Next.js and I tried to add google Tag Manager.
I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables.
It says my variable is undefined.
I created a file .env.local on my project folder (at the same level as components, node_modules, pages, etc)
In this file I created a variable like this (test purpose) :

NEXT_PUBLIC_DB_HOST=localhost

在我的索引页面上,我尝试了以下代码:

And on my index page I tried this code :

console.log("test ", process.env.NEXT_PUBLIC_DB_HOST);

但在我的控制台中,我得到一个未定义的测试".
我试图将我的变量放入 .env 文件中,但没有成功.
我做错了什么?

But in my console I get a "test undefined".
I tried to put my variable into an .env file instead, without success.
What I am doing wrong ?

推荐答案

这个环境只适用于服务器端.要在客户端访问此环境,您需要在 next.config.js 中声明

This envs just works in Server Side. To access this envs in Client Side, you need declare in the next.config.js

这边:

module.exports = {
  reactStrictMode: true,
  env: {
    BASE_URL: process.env.BASE_URL,
  }
}

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

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