Home
Support Forums

How to set and update environment variables from within serverless functions?

I need to create and persist OAuth access tokens and refresh tokens somehow, so I can use them in my serverless functions.

I was thinking of storing them as environment variables and then updating them from within the serverless function when they expire.

But so far I can’t see how to update environment variables programmatically from within a serverless function. It only seems possible to do that using the UI.

Also, I’m not entirely sure if the new programmatically set environment variable would be usable because I think they get injected at build time, not runtime.

Do you have any suggestions on how to tackle this problem?

Hi @Abba,

To start off, I think this is a better use case for an external database than Netlify Functions. However, you can update environment variables using Functions by using Netlify API. You can use updateSite (build_settings.env) to do what you’re trying to.

And yes, I do believe they get injected during build time, but you can try to see if it works.