0

I’m facing an OAuth2 token persistence issue in a Node.js backend.

Scenario

I have a Node.js backend that integrates with APIs using OAuth2.

I wrote a token manager that:

Stores the access token + expiry time in a variable.

Refreshes the token only after expiry.

This setup works perfectly in local development.

const axios = require("axios");
class TokenManager {
 constructor() {
 this.accessToken = null;
 this.tokenExpiryTime = null; // timestamp
 }
 async getAccessToken() {
 // If token exists and is still valid
 if (this.accessToken && Date.now() < this.tokenExpiryTime) {
 return this.accessToken;
 }
 // Otherwise refresh
 const response = await axios.post("https://auth.example.com/oauth/v2/token", {
 client_id: process.env.CLIENT_ID,
 client_secret: process.env.CLIENT_SECRET,
 refresh_token: process.env.REFRESH_TOKEN,
 grant_type: "refresh_token",
 });
 this.accessToken = response.data.access_token;
 this.tokenExpiryTime = Date.now() + response.data.expires_in * 1000;
 return this.accessToken;
 }
}
module.exports = new TokenManager();

What’s the recommended way to manage OAuth2 tokens in a distributed environment (e.g., multiple containers behind a load balancer)?

Any real-world patterns, best practices, or architecture tips would be appreciated.

Problem in Production

After Dockerizing and deploying this app on EC2 (or any stateless infra), the behavior changes:

The token gets fetched/refreshed on every API call.

It never persists as expected.

That I couldn’t answer properly

Why does this happen in production/cloud but not locally?

How should token persistence be managed so that tokens are reused until expiry—even across restarts, scaling, and load balancing?

What I Tried

Keeping the token in memory inside the service class (works locally, fails in distributed environments).

Not sure how to persist across multiple containers/instances.

Question

Why does the token not persist after Docker deployment?

Marc Le Bihan
3,6016 gold badges35 silver badges74 bronze badges
asked Sep 7, 2025 at 1:32

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.