Refresh Tokens — Complete Guide
Refresh Tokens — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 52 of 100
Refresh Tokens
Stack ✓ → Projects
Projects · 2 — Apps · ~6 min · MEAN — Authentication & Security
What is this?
Refresh tokens are long-lived credentials stored securely (httpOnly cookie) used to obtain new access JWTs without re-login in MeanVerse apps.
Why should you care?
Short access tokens limit damage; refresh flow keeps UX smooth for 8-hour banking shifts.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
router.post('/auth/refresh', async (req, res) => {
const token = req.cookies.refreshToken;
if (!token) return res.status(401).end();
const stored = await RefreshToken.findOne({ tokenHash: hash(token), revoked: false });
if (!stored || stored.expiresAt < new Date()) return res.status(401).end();
const accessToken = signAccessToken({ id: stored.userId, roles: stored.roles });
res.json({ accessToken });
});
res.cookie('refreshToken', rawToken, {
httpOnly: true, secure: true, sameSite: 'strict', maxAge: 7 * 864e5
});
What happened?
- Store hash of refresh token in MongoDB — leak of DB does not reveal usable tokens.
- httpOnly cookie blocks JavaScript theft via XSS.
Practice next
- Issue refresh token on login; store hash in RefreshToken collection.
- Keep access token in memory or sessionStorage only.
- Rotate refresh token on each use — invalidate old hash.
- Detect refresh token reuse and revoke all user sessions.
- Add device name column for session management UI.
Remember
Access JWT short; refresh token long. httpOnly cookie + server-side hash storage. Rotation reduces replay attack value.
Teller workstation
Access expires every 15m; teller stays logged in all day via refresh.
Outcome: Stolen access token useless after expiry; refresh revocable centrally.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!