In real-world Node.js apps, authentication is usually handled using two tokens together: an access token and a refresh token. This approach improves both security and user experience.
Access Token (Short-lived)
An access token is a JWT used to access protected APIs.
Key points
- Sent with every request (Authorization header)
- Contains user data (like userId, role)
- Short expiry (e.g., 15–60 minutes)
- If leaked → limited damage due to short life
Example
const accessToken = jwt.sign(
{ userId: user._id },
"accessSecret",
{ expiresIn: "15m" }
);
Refresh Token (Long-lived)
A refresh token is used to generate a new access token when it expires.
Key points
- Not sent with every request
- Stored securely (preferably httpOnly cookie or DB)
- Long expiry (e.g., 7 days)
- Used only for token renewal
Example
const refreshToken = jwt.sign(
{ userId: user._id },
"refreshSecret",
{ expiresIn: "7d" }
);
How They Work Together
Flow:
- User logs in
- Server sends:
- Access Token (short-lived)
- Refresh Token (long-lived)
- Client uses access token for API calls
- When access token expires:
- Client calls
/refreshAPI with refresh token - Server verifies refresh token
- New access token is issued
- Client calls
Example Refresh API
app.post("/refresh", (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (!refreshToken) return res.sendStatus(401);
jwt.verify(refreshToken, "refreshSecret", (err, user) => {
if (err) return res.sendStatus(403);
const newAccessToken = jwt.sign(
{ userId: user.userId },
"accessSecret",
{ expiresIn: "15m" }
);
res.json({ accessToken: newAccessToken });
});
});
Why Not Use Only One Token?
If you use only a long-lived token:
- Higher security risk if token is stolen
- Hard to control sessions
Using access + refresh tokens:
- Keeps access tokens short-lived → safer
- Allows seamless login without asking user to re-login
Best Practices
- Store refresh token in httpOnly cookie
- Save refresh tokens in DB (to revoke if needed)
- Rotate refresh tokens (issue new one each time)
- Keep access token in memory (not localStorage if possible)
- Always validate tokens on backend
Simple Interview Explanation
- Access token → used to access APIs, short expiry
- Refresh token → used to get new access token, long expiry
Key Takeaway
Access tokens handle secure API access, while refresh tokens ensure smooth user sessions without frequent logins. Together, they provide a balance between security and usability in Node.js applications.