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?