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 i
If you are reading this page in 2020 and don’t want to develop server-side code for whatever reasons(saving hosting cost, etc), severless function might be the solution.
This also calls 3rd party API from the server-side, but you don’t have to develop a full-fledged server-side API proxy.
Netlify has documentation on this. I guess other providers like AWS lambda, Google cloud function offers similar things but not sure.
https://github.com/netlify/code-examples/tree/master/function_examples/token-hider
Pros No server management
Cons Vendor lock-in
Even with your PHP solution you can't hide your userId. It can be easily printed in browser console by accessing consle.log(userId);
. As far as I know anything that is available to client-side is vulnerable and can easily be decoded. Even if you obfuscate your api key it can still be decoded from clientside.
The right thing to do is to create a PHP wrapper around the API calls that require keys, and then call that wrapper from Javascript.
In short: No, you can't secure your API key in a client-side app.
This article goes into some more detail
Two options