Right way to use API private key

I’m making a React project and using the Marvel API to get information about characters and comics. To use that API, Marvel provided an API key. My question is, how i can use this key without made it visible to the client side? Because it’s hardcoded on the JS file, so anyone can view the file and extract my key. Any ideas?

You can’t in a purely frontend solution. Ideally what you would do is create a server and you would make an API call to the server then then the server would make the API call to Marvel. Your key could be hidden in a .env file so no one would ever see it.

But in order for a front end to work, all of it gets loaded on the client, so you can’t hide it.

Some APIs allow you to limit what domains can all them - that might work. Another option is to store it as an encoded string and then decode it before using - this is not perfect because they can figure out that you’re decoding, but it does offer another level of obfuscation.

Other than that, I wouldn’t worry about it. Did it cost you any money? If not, I’d just go for it. You can always change it later if there is a problem.

2 Likes

Thanks, man. It was enlightening.
I’d think the better solution for that case is to limit the domains and use only my public key, cause the response time of Marvel’s API is terrible.
I’d liked the server solution, it’s going to be very useful in the future.

Yeah, you’ll get plenty of practice at the server solution when you get to the backend sections. I remember being where you were and wondering if there was a better way. A lot of my confusions got answered in the backend section - a lot of things made more sense.

2 Likes