Environment Variables Not Getting Passed to NextJS 12 API Routes

Hi all,

I’m considering moving from Heroku to Netlify for my NextJS 12 app. I have a few NextJS API routes in my app, one of which depends on an API key/secret that I store as an environment variable (ESV_API_KEY).

App URL: https://staging.faithdashboard.com/
API Route (that should work): https://staging.faithdashboard.com/api/widgets/bible-verse?q=ps23.1
Relevant Code: faith-dashboard/bible-verse.ts at main · caleb531/faith-dashboard · GitHub

Now here’s the problem:

  1. Locally, my environment variable is stored in a gitignore’d .env.local file so it’s not committed publicly.
  2. On Heroku, I can set this environment variable in the dyno settings, and it gets passed through to my API route without any additional configuration.
  3. But on Netlify, my API route is showing the environment variable (ESV_API_KEY) as undefined, even though I’ve defined it in the Netlify Deploy Settings (screenshot below). And I have made sure to redeploy after setting the env variable, but still no luck. You can see the behavior if you visit the API route URL above

Now, I have read [Support Guide] Using environment variables on Netlify correctly, but it’s very framework-agnostic, and I’m not sure what the minimal steps are I need to take for my NextJS app specifically.

Thanks in advance,
Caleb

Hey @caleb531,

From the timestamps in our database, I can see that the variable was added after the latest deploy. Could you try to deploy again?

@hrishikesh I just ran another deploy via “Trigger deploy” > “Clear cache and deploy site”. The deploy completed successfully but my API endpoint still says the API key is missing.

@hrishikesh BTW, I decided to switch my primary site domain from staging.faithdashboard.com to netlify.faithdashboard.com while I’m still testing, so please use the latter instead for the URLs / configuration I’ve provided.

App URL: https://netlify.faithdashboard.com/
API Route (that should work): https://netlify.faithdashboard.com/api/widgets/bible-verse?q=ps23.1
Relevant Code: https://github.com/caleb531/faith-dashboard/blob/netlify/pages/api/widgets/bible-verse.ts

Another thing to note, you’ve published and locked a deploy: Netlify App. So your deploy never gets published.

1 Like

@hrishikesh That was it! I wasn’t aware that disabling auto-publishing would also lock the deploy configuration.

This is now resolved—my API route is now returning a 200 response, thus fixing that broken functionality in the app. Thank you for the assistance!

1 Like