How Do I Obscure API Keys On The Client?

Jack Herrington
2 min readAug 3, 2023

--

Question: How do I obscure API keys on the client?

Answer: So you have a super powerful key to a 3rd party API that allows you to read/write any data you want from any customer, and you don’t want that falling into anyone else’s hands. What do you do? Gotcha. First off, you never send that to the client, not in any way, not obscured, not encrypted, not anything. Because try as you might to hide it, the key will end up showing clear as day in the Network tab of the Inspector as soon as you make a call on the client.

React + NextJS Questions And Answers Banner

What you should do instead is create a proxy API endpoint on your NextJS server. NextJS has always had great support for making API routes. You can use a route handler to create a proxy endpoint that will take the request from the client, and then make the request to the 3rd party API on the server. This way, the client never sees the API key, and you can do whatever you want with the response before sending it back to the client.

This proxy API also doesn’t need to be a 1-to-1 proxy, you can create an abstraction layer that allows you to do things like caching, or rate limiting, or even just to make the API easier to use. For example, if you have a 3rd party API that requires you to make 3 separate calls to get the data you need, you can create a single endpoint that makes those 3 calls and returns the data in a single response. In addition this new API ensures that if you want to change out that 3rd party API layer later that you only have to change it in one place.

To be honest, learning how to make the calls from a NextJS route handler will teach you how to make the calls to the API during Server Side Rendering, which is probably what you want to do anyway. So learning this technique of building proxy APIs is a two-fer!

Before you do any of this, make sure that the API key is indeed dangerous to be on client. Not all API keys are meant to be kept secret. Some keys, like Firebase keys, are meant to be used on the client. If you’re not sure, check the documentation for the API you’re using.

Jack Herrington is currently working on a course on NextJS, subscribe to the newsletter to get updates as well as React and NextJS tips, tricks and tutorials.

--

--

Jack Herrington
Jack Herrington

Written by Jack Herrington

YouTuber and Principal Engineer. Full NextJS course at pronextjs.dev

No responses yet