环境变量不适用于 NextJS 上的 Mapbox 令牌 [英] Environment variable not working with Mapbox token on NextJS

查看:23
本文介绍了环境变量不适用于 NextJS 上的 Mapbox 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Mapbox 地图,我正在尝试将环境变量传递给使用 NextJS 9.4 中的内置 .env.local 集成.根据 Next 文档,我正在使用 .env.local 文件,并且为了向浏览器公开 env 变量,我在它前面加上了 NEXT_PUBLIC_.但是,此设置不会传递访问令牌.当我直接传递令牌时,它确实有效,所以我知道这是 .env.local 文件没有传递该特定环境变量的某种问题,即使它与其他令牌一起使用.

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;

其他.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 一起使用时有效,但由于某种原因,环境变量不适用于 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屋!

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