Support Forums

process.env.API_KEY not working on next-on-netlify deployment

I have an an api call in my next.js app

In index.js there is a line: const api_key = process.env.API_KEY

My build command is “node -p ‘process.env’ && yarn build”

I can see the API_KEY in the build logs. But index.js apparently can’t access “process.env.API_KEY”.

The app crashes.

Please help!

@vinod-vms hey! thanks for letting us know :). is your API_KEY prefixed with NEXT_PUBLIC? see: https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

I had also read the Next.js docs.

Expose my API Key to the browser?

Like, a console.log would reveal it to anyone?

No. I don’t want to do that.

Pardon me if I’m getting it wrong.

I want to inject it during build-time only.

BTW, I use next-on-netlify for deployment.

Thank you.

hey @vinod-vms can you provide a repo that reproduces this issue? we’ll need that / more info to diagnose what’s going on. at the very least we’ll need to see your index.js. let us know!

Howdy :wave:t2:

Where are you defining your API key? The Netlify Toml or the Netlify Admin UI? The layout is a little non-uniform, but depending on where you define that those values, they may or may not be included in your Functions automatically.

This build plugin might help, and if nothing else, its README does a great job at explaining the various methods of getting ENV vars where you need them -


I have defined my API key in the Netlify Admin UI.

This is my repo: https://github.com/vinod-vms/world-news-app

In my local machine it just works fine. Next’s build command is able to take the API_KEY from the local .env file.


I edited my netlify.toml file:

package = “netlify-plugin-inline-functions-env”

I also added “netlify-plugin-inline-functions-env” as a devDependency in the package.json file.

Currently, build fails with this message:

Error: Failed to inline function files due to the following error:
10:49:13 AM: /opt/build/repo/out_functions/next_api_hello/next_api_hello.js: don’t know how to turn this value into a node
/opt/build/repo/out_functions/next_api_hello/next_api_hello.js: don’t know how to turn this value into a node

Please help.

Thank you.

Hey, I cloned your repo, removed the “netlify-plugin-inline-functions-env” package, and checked that the environment variables are available.
I created an API_KEY with the value of test123123123 and then ran the code.

While there was an error of data being undefined (Maybe u need to check the response payload from the api youre calling?

I was though, able to see that in the functions logs of netlify, as next-on-netlify runs everything through functions, that the environment variable was able to be accessed. You ofcourse cannot console log this variable to the browser etc unless you were to use PUBLIC etc as stated above. However, you should be able to use the variable inside your function :slight_smile:

In addition to the above, I have checked the newsapi you are calling.
You are calling
"https://newsapi.org/v2/top-headlines?" + “country=in&” + aKey;
however, they request that it be:
"https://newsapi.org/v2/top-headlines?" + “country=in&” + “apiKey=” + aKey;

that is probably why your data is undefined.

I have edited this all in my repo and have deployed it here: https://pedantic-haibt-214364.netlify.app/
You can see that the news articles come through!

Does this help? https://github.com/AaronPowell96/world-news-app

I have made a PR to make it easier for you here: https://github.com/vinod-vms/world-news-app/pull/1

Hi @AaronP

I have cloned your fork.

Made a .env file with my api key.

Ran ‘yarn install’ && ‘yarn dev’

It is not working here.

I am unable to correctly get the api response.

Error: Error serializing .errorCode returned from getServerSideProps in “/”.

Coming back to the code, you have suggested,

In addition to the above, I have checked the newsapi you are calling.
You are calling
"https://newsapi.org/v2/top-headlines?" + “country=in&” + aKey;
however, they request that it be:
"https://newsapi.org/v2/top-headlines?" + “country=in&” + “apiKey=” + aKey;

that is probably why your data is undefined.

But I have prefixed the “apiKey=” string before the actual api key in the Netlify UI.

I’m afraid, it is just a tautology.

I have also allowed your request to view by build logs.

Kind of you if you would explain.

Thank you.

Hi Vinod, I would need a link to said Netlify Build logs. My repo builds fine and continues to work with the aKey just being set to the newsapi key they give you.

I had not got time to run the code locally, however, it does build for netlify.
I will try to give it a quick local review this evening, however I cannot guarantee anything quick thank you!!

I have had authorized you to view the build.

Let me restate the problem so as to make sure that we’re on the same page.

The app builds just fine. No problems whatsoever.

But there is this API call, and Next.js’s build process can’t access the secret API_KEY which is defined in the Netlify UI.

If you hard code the value, then the news comes through.

That is what I’m currently doing.

For me, there is a workaround, that is to have a private repo and hard code the API key in there.

This is a public repo, and I can’t no way use this for production.

For me, the problem is with the next-on-netlify plugin.

Do the engineers have any docs for this?

How shall I inject the secret key that is defined in the Netlify UI during build time?

Currently the app builds and the site goes live.

But when we navigate to the browser, the api response is undefined, because aKey or API_KEY or whatever you name it, is just not there.

Thank you.

1 Like

Next generates static pages, and the next-on-netlify plugin uses functions.

Clone my repo, set the API_KEY in the UI to JUST the api key not “apiKey=xzxzc” as you said before.
You cannot console log the environment variable but it is built into the api call so that you will be authorised when it is called on page load. As you can see from https://pedantic-haibt-214364.netlify.app/ I did not hardcode the value either.

Because its injected at build time you wont see the api call in the network tab (maybe) as it will just be the javascript running, I am replying without looking at the code just recalling from memory. :slight_smile:

For me to view your builds on netlify youd need to give me a link to them, it would also be helpful if you linked your published site

This is the link:

And the preview:

{“errorType”:“Runtime.UnhandledPromiseRejection”,“errorMessage”:“TypeError: Cannot read property ‘map’ of undefined”,“trace”:[“Runtime.UnhandledPromiseRejection: TypeError: Cannot read property ‘map’ of undefined”," at process. (/var/runtime/index.js:35:15)"," at process.emit (events.js:314:20)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}


I fixed this in the code I sent. If you change you code to be (data || []) etc. I did also make a pull request with the code at the time.

Change the code to (data || []) ?

If there is data, let it be data; otherwise an empty array.

How would this solve the problem?

This is a NOT a problem with my code.

This is a problem on how to correctly use environment variables on Netlify.

There is an earlier thread:

But since I am specifically using next-on-netlify for deployment, I opened the issue.

Any help on this would be highly appreciated.


Did you try to clone my repo and set your API_KEY in the ui? I have successfully done what you are trying to achieve. Accessing the Environment variable at BUILD time so that api requests can be successfully made.

I understand your issue and am trying to state that I cloned your repo, tested its workings, and submitted a PR for you.

Lets say for whatever reason your data doesn’t come back then undefined.map will cause the error youre getting, there is no harm in fixing that so see where you get to next?
Lets get it working on netlifies build and dig deeper into the local environment after?

I was going to fork your repo again just to check any changes you had made since opening the issue but that would most likely override my current PR and I wanted you to still be able to access it :slight_smile:

To clarify, you are trying to access your environment variable at BUILD time in netlify, setting the API_KEY in the UI and that will be built into your generated site so that it can pull data from the third party. You will not be able to console log the variables or use them at run-time so therefore if you try to run it locally at this current time, the variable will be undefined.

Your error posted above clearly states Cannot read property ‘map’ of undefined”,. Changing both uses of data to fallback to an empty array when undefined will at least let you see the next issue if there is one. I know it is not related to accessing your variable.

I cloned your repo.

I made a .env file in the root.

I have stated early, I get this error.

Error: Error serializing .errorCode returned from getServerSideProps in “/”.

Why did you need an env file? Lets attempt to get your code built in netlify first. Did you:

  1. clone the repo,
  2. create a netlify site with your API_KEY environment variable set.
  3. deploy your changes so that it triggers a build with the newly set variable?

I am off to bed in as second but will try to wait if you are willing to attempt this :slight_smile:

EDIT: I just checked as I am getting off now, from my repo I added a .env at the root directory with
API_KEY="abcMYKEYHEREASDasdada" and then ran yarn dev and everything seemed to run fine locally too!

I hope this manages to help you as I think we are in different timezones :slight_smile: One last suggestion, which would also be included in the above steps is that somehow someway maybe your current site setup has other issues to creating the site again with this new configuration will have better luck. Goodluck! Ill check back when I can tomorrow for you.

I have pushed your code to the master branch.

Hopefully, you can see the build.

I’ll revert to an older version if it is not working.