Support Forums

Update env vars from Netlify Function

Hello Everyone,

First off, thanks to team Netlify and other contributors for all your time and energy spent writing and debugging the platform that exists today.

TLDR; Given that refreshing an access token in a netlify function does not update Netlify dashboard env vars, where are access tokens to be stored safely with minimal function calls?

The function starts by checking whether an access token is passed the half way mark toward expiration. If the access token is close to expiring it sends the existing access token to the API to refresh, and the new access token, along with a timestamp for when it expires, is returned.

The new access token successfully saves to process.env.access_token and the new access token becomes available for the next function call. The problem is that the function reverts back to the previous environment variable values after redeployment.

It appears that on deployment of the function it builds using the environment variables available at the time and creates a process.env for the function itself which is disconnected from the Netlify dashboard’s process.env.

So I thought I could read/write the .env file of the function and learned that the environment is read only. Whoops.

The goal is to keep access tokens out of the repository, but it may be the only choice in the event that the function isn’t updated before the original access token expires. That way the repo always contains an up-to-date access token in the event that a new build / redeploy occurs.

An alternative is to use a function call to get/put the access token to a non-expiring-access-token database.


Hello @willcdotca, welcome to the Netlify Forums!

Yes, you’ll need to redeploy your function (along with your site) so that your function can be updated with the new api token.

There’s two steps you could do to update the token on a function if you want to do things programmatically:

  1. Update the env var using the following endpoint: https://open-api.netlify.com/#operation/updateSite
  2. Trigger a new deploy by invoking a build hook set up as described here: https://docs.netlify.com/configure-builds/build-hooks/

Let me know if that helps.