Auth token management with Node.js Observer pattern

  1. You request the auth token
  2. Auth token received.
  3. Send request with auth token
  4. Received the desired response.
// serviceHandler output
{“newToken”:”def”}
No need for new request
No need for new request
No need for new request
No need for new request
No need for new request
No need for new request
No need for new request
No need for new request
// Token generator output
I am handling token: abc
// serviceHandler.js{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
{"newToken":"def"}
// tokenGenerator
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
I am handling token: abc
  1. If we have an invalid token, update a variable to represent that we are in the middle of getting new token.
  2. Make an actual request for the new token.
  3. Once the request is completed successfully, unset the variable to show that no request for auth is in progress.
  4. Send an event that new token is available so that other listeners can take appropriate action.
// betterServiceHandler
{"newToken":"def"}
// tokenGenerator
I am handling token: abc

--

--

--

Senior Staff Engineer @freshworks. Ex-McKinsey/Microsoft/Slideshare/SAP, Tech Enthusiast, Passionate about India. Opinions are mine

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhinav Dhasmana

Abhinav Dhasmana

Senior Staff Engineer @freshworks. Ex-McKinsey/Microsoft/Slideshare/SAP, Tech Enthusiast, Passionate about India. Opinions are mine

More from Medium

Introduction of NodeJS, KoaJS, and Restful services

Run MongoDB for development

Queue Using Dart

[React] Routing to an Error Page with axios interceptors