Handling API keys in a Proxy Redirect

I’d like to proxy to an external API, where parts of the API URL are read from Environment Variables. Specifically for adding an API key.

So sort of like they do in this example:

/api/*  https://api.example.com/:splat  200

But I’d like to inject API credentials that are read from an environment variable, to keep them secret.

/api/*  https://${USER}:${PASSWORD}@https://api.mysearch.com/:splat  200

Or, perhaps passing it in as an Header:

[[redirects]]
  from = "/search"
  to = "https://api.mysearch.com"
  status = 200
  force = true
  headers = {Authentication = ${API_KEY}}

Any advice?

H Jason,

First off, environment variables are only available in very specific contexts:

  • at build time,
  • to the shell

So, you have to make sure they get interpolated wherever you intend them to be expanded, by your build command. This article talks about that in more depth: [Common Issue] Using environment variables on Netlify correctly

This section of our docs shows a specific example addressing your use case: https://www.netlify.com/docs/netlify-toml-reference/#calling-environment-variables

Let me know how that works for you!

1 Like

@JasonStoltz this is actually a good use case for doing the proxying in a lambda function. An example of this in https://github.com/netlify/code-examples/tree/master/function_examples/token-hider . Also, any environment variables you save in the Netlify UI will have be available to your Netlify lambda functions.

1 Like

@futuregerald Thanks! That’s what I ended up implementing, that example is super helpful.

1 Like

lamba seems like overkill - plus, unless you take care to restrict access to the lamba, you’ve now published a public api that uses your api keys.

here is a simple one liner, stuff it in an npm script, or whatever build tool you use

echo "/api/*  https://${USER}:${PASSWORD}@https://api.mysearch.com/:splat  200" > _redirects

just make sure that _redirects ends up in the correct place.

1 Like