1

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:

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
        );
    }...

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?

FRMR
  • 289
  • 3
  • 27

1 Answers1

1

Possibly this

You are using dotenv

Please see this discussion on GitHub: https://github.com/vercel/next.js/discussions/12754

Roar S.
  • 8,103
  • 1
  • 15
  • 37