Handling sensitive client-side API keys in Next
How to protect your API keys from being leaked to the client-side
Saturday, November 20, 2021
How to avoid exposing API keys to the browser
Create an API handler which will call the external API with the sensitive API key, then call that handler from the client-side.
Here's an example of how to call an API with a required API key.
Of course, we don't want it to be hardcoded or committed to the repo; As a workaround, we can create an environment variable.
If you're wondering why variables start with
NEXT_PUBLIC_you can refer to this blog
Using the above example will surely help us not leak the API key in our codebase; however, it is still accessible to the client-side.
Go to the Network tab in the browser, and you'll see the API key in the request headers.
Keep in mind that client-side code needs to be treated as publicly accessible by anyone.
As mentioned in the
TL;DR section, we can prevent the exposure of API keys if the code is running on the server.
The good thing is that Next.js is not only a client-side framework but is also used to run server-side code, which means no need to create a new backend service for this use case.
Check this documentation to learn about creating an API in Next.js.
Here's the general steps
- Remove the
NEXT_PUBLICin the variable name(e.g.
- Create a handler named
- Move the API call to the handler with the updated environment variable.
The handler above is accessible via
localhost:3000/api/hello in a local environment or
https://www.ourhost.com/api/hello in production. OR simply via
The API key should not be visible in the browser as the external API call executes from the server.
This article might be anti-climactic as the solution is very similar to all other solutions we've seen so far. However, it is worth mentioning that in Next.js, forwarding an API call to the server is straightforward since Next.js can be both used in the frontend and backend.