DEV Community

Cover image for Stop building backends just to hide API keys
Tossesdev
Tossesdev

Posted on

Stop building backends just to hide API keys

We all know how inconvenient it is to spin up a backend just to hide an API key, but obviously that inconvenience is a lot more appealing than waking up to a $20k bill because someone found your key on GitHub or in DevTools while you were sleeping. So, I put some thought into what protections having a dedicated backend for your key actually gets you, and it narrowed down to a handful of things:

  • Rate limiting - Stop your key from getting spammed
  • CORS - Stop people from putting your key into their own apps
  • Authentication (Firebase, auth0, Clerk, etc) - Require sign in for hitting the API
  • Endpoint allow listing - Stop people from accessing endpoints they shouldn't be

And for most projects, the implementation is nearly identical app to app. So why not make a drop in replacement to hardcoding keys, that's compatible with any API... I did.

Introducing Bounce

Bounce is an API proxy that lets you set up a config and swap your API base URL for a Bounce URL... and that's it. It handles all of the security mentioned above, and injects your key into the query before sending it to the upstream. Then responds exactly the same as the upstream API would (streamed responses work as well). Without needing code.

The replacement is just:

Instead of calling the API directly (exposing your key):

fetch("https://api.tosses.dev/v1/credentials", { method: "POST",
 body: { key: "SECRET_KEY", expiry_ttl: 1800 } 
});
Enter fullscreen mode Exit fullscreen mode

Route through Bounce to auto-inject your secret key:

const BOUNCE_KEY = "your_key_here";
const BOUNCE_URL = `https://fetch.tosses.dev/${BOUNCE_KEY}/v1/credentials`;

fetch(BOUNCE_URL, { method: "POST", 
body: { expiry_ttl: 1800 } // No 'key' needed
}); 
Enter fullscreen mode Exit fullscreen mode

Try it out here! I'd appreciate any feedback!

Top comments (0)