Save a token after authentication with external API's?

Is there any way to save a token without using an external origin?

Most API’s we connect with login with authentication and return a time-limited token we use for the rest of the requests, doing a new authentication on every request would not be appreciated - is there any way we can save these token for each subsequent request without using external services to store the token?

Because, if we can’t then using Amazon Lambda might be cheaper and faster because they don’t add any additional cost when accessing S3 internally.

Hi! Yes, you have a few options:

  1. You can cache the API token response. By passing cf: {cacheTtl: 600} for example to the Authentication fetch request, it’s possible to have us cache it. That way each subsequent request within the same data center would not make another request for that amount of time.
  2. You can store the token in global memory. Your Worker doesn’t get spawned for each request, it’s allowed to continue running between them. If you keep the token in global memory it will only be downloaded once per edge machine.

Thanks for the quick reply!

  1. I just tested this, works as advertised :wink: I also saw that custom keys where possible, but only on the enterprise plan.

  2. Um, how do i use global memory? I tried searching but nothing came up, is it part of the web api?

It’s actually simpler than you’d think to use global memory. Just declare a variable outside your request handler!

1 Like

Nevermind: Tutorials don’t load at all in Firefox :frowning:

It seems that globals are unreliable for anything uniquely generated on the worker.

On the example you posted above, I get very random numbers when doing requests from the same client.

Is there any way to keep a guaranteed value for a specific amount of time?

I’m basically looking to keep track of anonymous sessions for a specific amount of time or at least 1 hour.