1

I'm writing a NodeJS app that runs on a server and queries a remote API on a schedule. This API requires authentication, and gives me a token that is valid for a number of hours.

What's the best way to store and reuse this token, and only reauthenticate when it expires?

This is the first Node app that I've written, so I'm not sure exactly how to ask the question. Is there a common library that would handle this for me?

If not, and I have to write my own module, what's an acceptable way to store the credential? Should I be using a global variable, a state store like Redux, or am I way off the mark?

Sean McGrath
  • 80
  • 1
  • 10
  • You can store your token (as a normal variable) in the module and refresh it when a subsequent HTTP request fails, then re-run the HTTP request; or do something a little more elegant like this: https://stackoverflow.com/questions/51646853/automating-access-token-refreshing-via-interceptors-in-axios – Charlie Schliesser Dec 03 '19 at 03:14
  • Do you need to keep this token if the server restarts? If so, you'll need a way to persist it to disk. Otherwise, some variable somewhere. – Brad Dec 03 '19 at 03:25
  • No, keeping the token isn't critical. I like @CharlieSchliesser idea of not tracking the expiry time, and just refreshing the token if a request fails. – Sean McGrath Dec 03 '19 at 03:28

1 Answers1

3

Well, it really depends upon the context of the code. If there's only one of these tokens for your server, then you just save it in a module-level Javascript variable and you can use it from there.

If there are multiple tokens, each associated with some other request coming into your server, then you need to find some way to associate the correct token with the correct request. There are lots of ways to do that, but what method is most appropriate depends upon what you're trying to associate each token with.

For one or a few tokens, there is no reason to put these in some data store. A Javascript variable is just fine. The only reason I could think of to use an actual data store would be if you need these tokens to persist a server restart. In that case, you could just read and write JSON to a single file that you could then read in when the server restarts.

If not, and I have to write my own module, what's an acceptable way to store the credential? Should I be using a global variable?

No. Not a global variable. A module level variable could make sense.

a state store like Redux

I don't see any reason to go with something like that.

jfriend00
  • 683,504
  • 96
  • 985
  • 979