Home > Software engineering >  How do I obfuscate API calls from Gatsby?
How do I obfuscate API calls from Gatsby?

Time:03-08

I am developing an application in Gatsby that allows users to submit their information through a form. The form then submits that information to a private API via fetch. The problem is that this call exposes the API key to the browser, thus allowing anyone to use it for any other API functions.

How do I obfuscate the API call so that it does not expose the API key to the browser?

I imagine it would require me to write a server-side wrapper, but how do you do that with Gatsby?

CodePudding user response:

These responses aren't really grasping the problem. I can't keep the API key on the server side if the submit action needs to send the API key to the remote API. The only way I could do that is if I created a server-side wrapper that handled the API call. How do I do that with Gatsby?

Given that scenario I think you have (at least) two options:

  • Use serverless functions to proxy the call without having to host a server (where those environment variables would be stored). Depending on your hosting platform you can use Netlify functions (for Netlify hosting), Gatsby functions (for Gatsby Cloud hosting), AWS Lambda (for Amazon-related hosting), Google Cloud Functions, etc
  • Proxy the API calls through a backend-for-frontend, like an Express server, and add the secrets to your Express server

Both approaches rely on the fact that the serverless function/Express server will be used as middleware of those requests, hiding your secrets from the browser.

  • Related