环境变量不适用于NextJS上的Mapbox令牌 [英] Environment variable not working with Mapbox token on NextJS
问题描述
我有一个Mapbox映射,我正在尝试将环境变量传递给使用NextJS 9.4中内置的 .env.local
集成.根据Next docs,我使用的是 .env.local
文件,为了将env变量公开给浏览器,我给它加了 NEXT_PUBLIC _
前缀.但是,此设置不会传递访问令牌.当我直接传递令牌时,它确实起作用,因此我知道这是 .env.local
文件未传递该特定env变量的某种问题,即使它与其他令牌也一样.
I have a Mapbox map which I am trying to pass an environment variable in to using the built-in .env.local
integration in NextJS 9.4. As per the Next docs, I am using a .env.local
file and in order to expose the env variable to the browser, I am prefixing it with NEXT_PUBLIC_
. However, the access token is not being passed through with this setup. When I pass the token in directly, it does work, so I know this is some sort of problem with the .env.local
file not passing that particular env variable, even though it does with other tokens.
.env.local:
.env.local:
NEXT_PUBLIC_MAPBOX_TOKEN=my_mapbox_access_token
OTHER_API_TOKEN=my_other_api_token
map.js:
// Works
mapboxgl.accessToken = "my_mapbox_access_token";
// Doesn't work
mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN;
other.js:
// Also works
class OtherAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = "https://rest.otherapi.com/";
}
willSendRequest(request) {
request.headers.set(
"X-Application-Key",
process.env.OTHER_API_TOKEN
);
}...
因此,Mapbox令牌在直接传递时有效,而环境变量在与其他API一起使用时有效,但是由于某些原因,env变量不适用于Mapbox API.我尝试了是否使用 NEXT_PUBLIC _
前缀.我在做什么错了?
So the Mapbox token works when it is passed directly, and the environment variables work when used with other APIs, but for some reason the env variables are not working with the Mapbox API. I've tried with and without the NEXT_PUBLIC_
prefix. What am I doing wrong?
推荐答案
可能是
您正在使用 dotenv
请在GitHub上查看此讨论: https://github.com/vercel/next.js/discussions/12754
Please see this discussion on GitHub: https://github.com/vercel/next.js/discussions/12754
这篇关于环境变量不适用于NextJS上的Mapbox令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!