I am trying to pass an environment variable to the front end to display a map from MapBox.
//.env.local
MAPBOX_KEY="abc123"
// 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.
yarn devIs 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
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"
// Normal Env
VERY_SECRET
// PUBLIC ENV
NEXT_PUBLIC_NOT_SO_SECRET
Add NEXT_PUBLIC_ PREFIX
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} />
)
}