Vercel next.js environment variable not working
Asked Answered
S

5

9

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

Sternberg answered 20/12, 2020 at 18:10 Comment(0)
D
8

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

Declarative answered 16/1, 2021 at 5:48 Comment(2)
yarn now secret add - you sure about this? I get Command "now" not found.Bretbretagne
@Bretbretagne Truuuuee, this was applicable at the time of writing in 2021. now has changed to vercel, and the command has changed as well; to: vercel secrets add [secret-name] [secret-value] as documented here: vercel.com/docs/cli/secrets Ideally the documentation stays current-ish; the idea you're going to google on is "adding nextjs secrets via CLI"Declarative
J
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).

Jaimie answered 21/2, 2023 at 12:45 Comment(0)
A
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.

Absolution answered 6/4, 2023 at 22:6 Comment(0)
L
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.

Layout answered 27/5, 2023 at 22:37 Comment(0)
J
0

In my case I just had to redeploy the application and it worked.

Jointer answered 7/4 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.