search

Home  >  Q&A  >  body text

New Title: Protecting API Keys: Hidden Methods in Client-Side JavaScript

<p>Right now I'm writing a client-side JavaScript application that makes requests to the USPS Price Calculator API. In order to make this request, I need to provide my API user ID in the requested XML. The tag looks like this: <code><RateV4Request USERID="ThisIsWhereMyUserIdGoes"></code>. My question is: Is there a way to provide my user ID in JavaScript while still hiding it from the user seeing the client file. Currently my only solution is to create a PHP file on my server that contains the user ID and then use an AJAX request in client JavaScript to store it in a global variable. The code is as follows: </p> <pre class="brush:php;toolbar:false;">var userID; $.get("/secrets.php", function( data ) { userID = data; });</pre> <p>Is this approach sufficient to prevent my API user ID from being seen by users of my application? Is there any other way to do this? </p>
P粉521748211P粉521748211457 days ago619

reply all(2)I'll reply

  • P粉872182023

    P粉8721820232023-08-25 09:30:52

    If you're reading this page in 2020 and don't want to develop server-side code for whatever reason (saving hosting costs, etc.), serverless functions may be the solution.

    This also calls third-party APIs from the server side, but you don't have to develop a full server-side API proxy.

    Netlify has relevant documentation. I guess other providers like AWS Lambda, Google Cloud Function also offer similar functionality, but not sure.

    https://github.com/netlify/code-examples/tree/master/function_examples/token-hider

    advantage No server management required

    shortcoming Vendor lock-in

    reply
    0
  • P粉245276769

    P粉2452767692023-08-25 00:22:43

    In short: No, you cannot protect your API keys in client applications.

    This article details some details

    Two options:

    • Make the API call on the server side and provide the information to the client from there
    • Require clients to use their own API key

    reply
    0
  • Cancelreply