Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Hide an API Key in Client-Side Javascript

Right now I am writing a client-side javascript app that makes a request to the USPS Price Calculator API. In order to make this request, I need to provide my API User ID in the xml of the request. The tag looks like this: <RateV4Request USERID="ThisIsWhereMyUserIdGoes">. My question is this: is there any way I can provide my user ID to the javascript, while still hiding it from users who look at the client-side files. Right now, the only solution I have is to create a PHP file in my server that has the User ID, then using an AJAX request in the client-side javascript to store it in a global variable. It looks like this:

var userID;
$.get("/secrets.php", function( data ) { 
       userID = data;
});

Is this an adequate way of keeping my API User ID from being seen by the users of my app? What else could I do?

like image 485
Joshua E Avatar asked Jul 07 '16 04:07

Joshua E


People also ask

How should you hide your API key?

has suggested in a comment: if at some point you committed your API keys to your git repo, you should remove all traces of it. You can do this by using git rebase and removing the commit that added the keys.

Where are Javascript API keys stored?

env is a place where we can store any environmental variables we want to keep secret (such as an API key). These are variables that are specific to your environment and shouldn't be shared with others. . env is a common file extension for a configuration file used to set variables containing sensitive information.


1 Answers

In short: No, you can't secure your API key in a client-side app.

This article goes into some more detail

Two options

  • Make the API calls server-side and then serve information to the client from there
  • Require the client use their own API keys
like image 175
Jacob Mulquin Avatar answered Sep 28 '22 06:09

Jacob Mulquin