Save a token after authentication with external API's?


#1

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.


#2

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.

#3

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?


#4

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

https://cloudflareworkers.com/#179e7c3a2ab2c3ced734f1e016048ed3:https://tutorial.cloudflareworkers.com


#5

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