A refresh token helps keep a user logged in without asking for their password again. It lets the app get a new access token when the old one expires.
Refresh token concept in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
POST /token
Headers: Authorization: Bearer <refresh_token>
Response: { accessToken: <new_access_token> }The refresh token is usually sent securely in the request body or headers.
The server verifies the refresh token before issuing a new access token.
Examples
Express
app.post('/token', (req, res) => { const refreshToken = req.body.token; if (!refreshToken) return res.sendStatus(401); // Verify refresh token and issue new access token });
Express
const jwt = require('jsonwebtoken'); jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => { if (err) return res.sendStatus(403); const accessToken = jwt.sign({ name: user.name }, ACCESS_TOKEN_SECRET, { expiresIn: '15m' }); res.json({ accessToken }); });
Sample Program
This Express app shows a simple login route that issues access and refresh tokens. The /token route accepts a refresh token and returns a new access token if the refresh token is valid and stored.
Express
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); app.use(express.json()); const ACCESS_TOKEN_SECRET = 'access-secret-example'; const REFRESH_TOKEN_SECRET = 'refresh-secret-example'; let refreshTokens = []; app.post('/login', (req, res) => { // In real app, validate user credentials here const user = { name: req.body.name }; const accessToken = jwt.sign(user, ACCESS_TOKEN_SECRET, { expiresIn: '15m' }); const refreshToken = jwt.sign(user, REFRESH_TOKEN_SECRET); refreshTokens.push(refreshToken); res.json({ accessToken, refreshToken }); }); app.post('/token', (req, res) => { const refreshToken = req.body.token; if (!refreshToken) return res.sendStatus(401); if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403); jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => { if (err) return res.sendStatus(403); const accessToken = jwt.sign({ name: user.name }, ACCESS_TOKEN_SECRET, { expiresIn: '15m' }); res.json({ accessToken }); }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Important Notes
Always store refresh tokens securely, for example in an HttpOnly cookie.
Refresh tokens should be long-lived but revocable if needed.
Access tokens are short-lived to reduce risk if stolen.
Summary
Refresh tokens let apps get new access tokens without asking users to log in again.
They improve security by keeping access tokens short-lived.
Use refresh tokens carefully and store them securely.
Practice
1. What is the main purpose of a
refresh token in an Express app using authentication?easy
Solution
Step 1: Understand the role of refresh tokens
Refresh tokens allow the app to request new access tokens without user interaction.Step 2: Compare options with refresh token purpose
Only To get a new access token without asking the user to log in again correctly describes this purpose; others describe unrelated functions.Final Answer:
To get a new access token without asking the user to log in again -> Option DQuick Check:
Refresh token purpose = get new access token without login [OK]
Hint: Refresh tokens renew access tokens silently [OK]
Common Mistakes:
- Confusing refresh token with access token
- Thinking refresh token stores passwords
- Assuming refresh token logs out users
2. Which of the following is the correct way to send a refresh token in an Express response header?
easy
Solution
Step 1: Recall Express method to set headers
Express usesres.setHeader(name, value)to set response headers.Step 2: Match correct syntax for refresh token header
res.setHeader('refresh-token', token); uses correct method and header name; others are invalid or use wrong header.Final Answer:
res.setHeader('refresh-token', token); -> Option AQuick Check:
Set header with res.setHeader(name, value) [OK]
Hint: Use res.setHeader to send custom headers [OK]
Common Mistakes:
- Using non-existent res.sendRefreshToken method
- Assigning token directly to res property
- Using wrong header like 'Authorization' for refresh token
3. Given this Express route snippet, what will be the output if the refresh token is valid?
app.post('/token', (req, res) => {
const refreshToken = req.body.token;
if (!refreshToken) return res.status(401).send('No token');
if (refreshToken !== 'validtoken') return res.status(403).send('Invalid token');
res.json({ accessToken: 'newAccessToken123' });
});medium
Solution
Step 1: Check token presence and validity
IfrefreshTokenis missing, returns 401; if invalid, returns 403.Step 2: For valid token, send new access token JSON
When token equals 'validtoken', response sends JSON with new access token.Final Answer:
JSON response with new access token -> Option CQuick Check:
Valid token returns new access token JSON [OK]
Hint: Valid token returns JSON with new access token [OK]
Common Mistakes:
- Confusing status codes for missing vs invalid token
- Expecting empty response instead of JSON
- Ignoring token validation logic
4. Identify the bug in this Express refresh token handler:
app.post('/refresh', (req, res) => {
const token = req.body.refreshToken;
if (!token) res.status(401).send('Missing token');
if (token !== 'secret') res.status(403).send('Forbidden');
res.json({ accessToken: 'newToken' });
});medium
Solution
Step 1: Check response flow after status calls
Withoutreturn, code continues after sending response, causing errors.Step 2: Confirm need for return to stop execution
Addingreturnafterres.status(...).send(...)prevents multiple responses.Final Answer:
Missing return statements after res.status calls causing multiple responses -> Option AQuick Check:
Return after res.status to stop code [OK]
Hint: Always return after sending response to avoid errors [OK]
Common Mistakes:
- Not returning after res.status sends response
- Assuming res.json is wrong here
- Thinking property name is incorrect
5. You want to implement refresh token rotation in Express to improve security. Which approach correctly applies this concept?
hard
Solution
Step 1: Understand refresh token rotation
Rotation means issuing a new refresh token each time the old one is used and invalidating the old token.Step 2: Evaluate options for security best practice
Issue a new refresh token on each use and invalidate the old one matches rotation concept; others either reduce security or misuse storage.Final Answer:
Issue a new refresh token on each use and invalidate the old one -> Option BQuick Check:
Refresh token rotation = new token each use [OK]
Hint: Rotate refresh tokens by replacing old with new each use [OK]
Common Mistakes:
- Reusing same refresh token indefinitely
- Not invalidating old refresh tokens
- Storing tokens insecurely on client side
