New Title: Protecting API Keys: Hidden Methods in Client-Side JavaScript
P粉521748211
P粉521748211 2023-08-24 10:22:46
0
2
642
<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粉521748211
P粉521748211

reply all(2)
P粉872182023

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

P粉245276769

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template