Handling sensitive client-side API keys in Next.js

How to avoid exposing API keys to the browser

TL;DR

Create an API handler which will call the external API with the sensitive API key, then call that handler from the client-side.

The problem

Here’s an example of how…


This content originally appeared on DEV Community and was authored by Carlo Gino Catapang

How to avoid exposing API keys to the browser

TL;DR

Create an API handler which will call the external API with the sensitive API key, then call that handler from the client-side.

The problem

Here's an example of how to call an API with a required API key.

const API_URL= 'https://www.test.com/api'
const API_KEY = 'some-secret-key'

useEffect(() => {
  fetch(`${API_URL}/hello?apiKey=${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.

const API_URL = proccess.env.NEXT_PUBLIC_EXTERNAL_API_HOST
const API_KEY = proccess.env.NEXT_PUBLIC_API_KEY;

useEffect(() => {
  fetch(`${API_URL}/hello?apiKey=${API_KEY}`)
  // ...
}, [])

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.

Solution

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

  1. Remove the NEXT_PUBLIC in the variable name(e.g. NEXT_PUBLIC_API_KEY to API_KEY)
  2. Create a handler named hello.js under pages/api.
  3. Move the API call to the handler with the updated environment variable.
export default async function handler(req, res) {
  const data = await fetch(
    `https://www.test.com/api/hello?apiKey=${process.env.API_KEY}`,
  ).then(response => response.json());

  res.json(data); // Send the response
}

The handler above is accessible via localhost:3000/api/hello in a local environment or https://www.ourhost.com/api/hello in production.

But since we are pointing to the same host, we use window.location.origin to avoid hardcoding the path or creating unnecessary environment variables.

useEffect(() => {
  fetch(`${window.location.origin}/api/hello`)
  // ...
}, [])

The API key should not be visible in the browser as the external API call executes from the server.

Conclusion

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.


This content originally appeared on DEV Community and was authored by Carlo Gino Catapang


Print Share Comment Cite Upload Translate Updates
APA

Carlo Gino Catapang | Sciencx (2021-11-20T12:14:38+00:00) Handling sensitive client-side API keys in Next.js. Retrieved from https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/

MLA
" » Handling sensitive client-side API keys in Next.js." Carlo Gino Catapang | Sciencx - Saturday November 20, 2021, https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/
HARVARD
Carlo Gino Catapang | Sciencx Saturday November 20, 2021 » Handling sensitive client-side API keys in Next.js., viewed ,<https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/>
VANCOUVER
Carlo Gino Catapang | Sciencx - » Handling sensitive client-side API keys in Next.js. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/
CHICAGO
" » Handling sensitive client-side API keys in Next.js." Carlo Gino Catapang | Sciencx - Accessed . https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/
IEEE
" » Handling sensitive client-side API keys in Next.js." Carlo Gino Catapang | Sciencx [Online]. Available: https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/. [Accessed: ]
rf:citation
» Handling sensitive client-side API keys in Next.js | Carlo Gino Catapang | Sciencx | https://www.scien.cx/2021/11/20/handling-sensitive-client-side-api-keys-in-next-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.