New Title: Protecting API Keys: Hidden Methods in Client-Side JavaScript
P粉521748211
2023-08-24 10:22:46
<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>
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
In short: No, you cannot protect your API keys in client applications.
This article details some details
Two options: