7

I'm using google maps in a Next.js project and everything's working locally. The google maps secret key is being stored in next.config.js which I access in the code through process.env.NEXT_PUBLIC_GOOGLEMAPS

When I deployed the project to Vercel, I didn't include next.js.config for security reasons. So I added the key under Settings -> Environment Variables enter image description here

However, the environment variable is not working in production. When I console log process.env.NEXT_PUBLIC_GOOGLEMAPS, I get undefined

What could be causing this issue and how can I fix it? Thanks

Allen Wu
  • 165
  • 1
  • 2
  • 10

4 Answers4

7

This is how I got my setup to work...

  1. I have an env.local file for local dev key. Add .env.local.* to .gitignore This file has my key/value pair like so:

1 NEXT_PUBLIC_G_KEY=AFLkefjlkwblahblahblah

  1. I have a next.config.js file that has this key as well in an env space:

env: { NEXT_PUBLIC_G_KEY: process.env.NEXT_PUBLIC_G_KEY } (process.env works out of the box according to the docs)

  1. I deploy to vercel so I create a secret with the actual value of the key...:

$> yarn now secret add MyAppName_PRoD_G_KEY AFLkefjlkwblahblahblah

  1. i go to my app in vercel > settings > environment variables and create a new one in the UI, mapped to the secret i just made in the command line.

vercel environment variable mapped to secret

K.H. B
  • 363
  • 2
  • 9
0

For me it worked only by adding them through the vercel interface (I had some interference because of the next.config.js file, however as soon as I added that to .gitignore everything worked).

Dragos
  • 46
  • 1
  • 6
0

If you have restricted the IP addresses that can access your Google Maps API, most probably Vercel IP is denied access by Google. Maybe your .env variable is working but the problem is Google Maps IP address restriction.

johnnn
  • 71
  • 1
  • 4
0

I have faced the same problem. Turned out that Vercel exposes only variables that start with NEXT_PUBLIC. E.g. NEXT_PUBLIC_PRODUCTION_BE_API. Hope this helps.