5

The Problem

I am trying to pass an environment variable to the front end to display a map from MapBox.

My Attempts

  1. I have place the API Key into the root of my directory:
//.env.local
MAPBOX_KEY="abc123"
  1. In the front-end, client side, I am trying to load that ENV to render a map:
// components/MapBox.js
export default function MapBox(){
  const MAPBOX_TOKEN = process.env.MAPBOX_KEY

  return (
    <MapGL mapboxApiAccessToken={MAPBOX_TOKEN} />
  )
}

The above code does not seem to recgonize the API KEY.

  1. When I console.log(process.env.MAPBOX_KEY) in this component, I can see the API Key in the terminal while i'm running yarn dev

Is there a way to load this env to the front end?

Note: I am using the react-map-gl package built on top of MapBox

Tyler Morales
  • 1,440
  • 2
  • 19
  • 56

3 Answers3

8

You need to prefix it with NEXT_PUBLIC_

Only variables with that prefix will be exposed in the frontend

For example NEXT_PUBLIC_HEY will be visible for the frontend but both for the backend.

MAPBOX_KEY="abc123"
NEXT_PUBLIC_HEY="FRONT"

https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

n1md7
  • 2,854
  • 1
  • 12
  • 27
  • Does this mean that the variable is still unexposed to the browser meaning that people can't steal it? – Tyler Morales Jan 22 '22 at 00:06
  • Everything prefixed with `NEXT_PUBLIC_` will be exposed. There is no `process.env` for the frontend. What the framework does is that it looks for all env variables during the build(because the build is os level operation, it knows what env variables are) prefixed with `NEXT_PUBLIC_` creates custom `process.env` in frontend and injects values one by one. So, the values are in your source code, whoever has access to it can see all, it is served from the browser which means everyone can access it. – n1md7 Jan 22 '22 at 00:14
2

You have to prefix your ENV with NEXT_PUBLIC_ in .env.local

//.env.local
NEXT_PUBLIC_MAPBOX_KEY="abc123"

In your component, reference it like this:

// MapBox.js
export default function MapBox(){
  const MAPBOX_TOKEN = process.env.NEXT_PUBLIC_MAPBOX_KEY

  return (
    <MapGL mapboxApiAccessToken={MAPBOX_TOKEN} />
  )
}

Tyler Morales
  • 1,440
  • 2
  • 19
  • 56
  • 1
    Here's the [doc link](https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser) for reference – David784 Jan 21 '22 at 23:58
2
// Normal Env
   VERY_SECRET
// PUBLIC ENV
   NEXT_PUBLIC_NOT_SO_SECRET

Add NEXT_PUBLIC_ PREFIX