javascriptjquery

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?


Solution

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

    This article goes into some more detail

    Two options