How to protect an API Key when using JavaScript?

Viewed 34420

So, I'm developing a small application just for my own use and perhaps an open source project on Git. I'm using an API from Envato Marketplaces, and as you all know there are some operations that don't require any keys, but in the same time there are some that do require.

I first made a nice API wrapper for the Envato API in PHP, but then I decided to experiment a little bit with JavaScript, so I'm developing the same wrapper with JavaScript. So far I have no problems with the public operations, but I now have to use the API Key.

My question would be if there's a way to protect the API Key in JavaScript. I cannot just put it there in plain text as it can then be used by others who see the code. So would there be an implementation where the API remains secret ? Maybe grabbing it from a JSON text file with XHR ?

3 Answers

My solution right now is to write a little wrapper in rust, and throw it in the /cgi-bin and make calls to that. That should keep the api-key, api creds and session data separate from the client.

The session context is a bit lost concept. However, if your Async request calls your server where your active session can be tracked then before the server makes an API call then the server can add a mapped API key for that request while sending the request to the service provider. The service provider can validate the domain from where the request is received and this will be a more effective way to protect API key and request spoofing.

Related