All Articles

How Do I Obscure API Keys On The Client?

Jack Herrington
Jack Herrington
August 2nd, 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, it will end up showing clear as day in the Network tab of the Inspector as soon as you make a call on the client.

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.

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.

Share this article with your friends

Subscribe for Free Tips, Tutorials, and Special Discounts

We're in this together!

We respect your privacy. Unsubscribe at any time.

Jack Herrington

Written by Jack Herrington

Jack Herrington is a Full Stack Principal Engineer who orchestrated the rollout of React/NextJS at Walmart Labs and Nike. He is also the "Blue Collar Coder" on YouTube where he posts weekly videos on advanced use of React and NextJS as well as other frontend technologies trends. His YouTube channel hosts an entire free courses on React and TypeScript. He has written seven books including most recently No-BS TypeScript which is a companion book to the YouTube course.