Netlify Functions - Best Practice for handling refresh tokens?

Hello there,

Instagram recently changed their public API to become a little bit more restrictive.

What I’d like to do is retrieve posts from an account that I own via a client side trigger, while at the same time, protecting my Instagram refresh token by not storing it in browser local storage.

My initial thought is to create a Netlify Function that does the following:

  1. Retrieve my client secret from a server-side environment variable, accessed only by the Netlify Function

  2. When the client (Gatsby App) loads the page, the Netlify function is called.

  3. Upon first run of the Netlify Function, retrieve a Long-Lived Access Token from the Instagram Basic Display API

  4. Store the refresh token somewhere server-side (is this even possible?)

  5. Use the access token to retrieve a user profile, and consequently the last 10 media items.

  6. Subsequent hits to the Netlify function’s endpoint should check to see if the token needs refreshing, before making the call to retrieve the user profile data.

So the question is, is it possible to retrieve a refresh token, and store it somewhere that is accessible by the Netlify Function only?

Failing that, the Long Lived Token actually lasts for 60 days. Theoretically, we could generate a token and store it as a server-side environment variable. If we use that method, is there an API endpoint that can be run to update environmental variables? E.g. I would set up a scheduled task that refreshes and updates the token every 59 days.

Any advice would be appreciated. Thanks in advance.

Hey @ardiewen,
This post discusses a few options:

They boil down to:

  1. use a function hooked up to a Fauna DB database to persist the token
  2. see if a custom Build Plugin would work for this use case- this method hasn’t been tried/tested before

Let us know if that helps you get started or if we can answer any other questions!

Yes, we ended up using a Netlify (lambda) proxy function calling a Dynamo DB at AWS to persist and amend the issued token for subsequent API calls. Site has been up and working well: Home | Four Hands Art Studio

I do think Netlify adding something similar to Cloud Flare workers kv storage would be very useful.

Thanks @jen @JpMaxMan, this is a solid approach!

1 Like

hey @JpMaxMan - if you head over to #features and do a solid write-up of what benefits you’d expect from implementing something akin to Cloud Flare workers, we can get some eyes on it and think on it some more. Any detail on why this might be beneficial to customers is helpful!

Glad I found this post. I’m looking to do the exact same thing, Instagram’s Basic Display API, token keys, 59 day refresh and all.

1 Like