Bird
Raised Fist0
Expressframework~15 mins

Refresh token concept in Express - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Refresh token concept
What is it?
A refresh token is a special code given to a user after they log in. It lets the user get a new access token without logging in again when the old one expires. This helps keep the user logged in smoothly and securely. Refresh tokens are usually long-lived and stored safely.
Why it matters
Without refresh tokens, users would have to log in again every time their access token expires, which can be annoying and disrupt the experience. Refresh tokens allow apps to keep users logged in longer without asking for passwords repeatedly, improving security and convenience. They also help servers control access better by limiting how long access tokens last.
Where it fits
Before learning about refresh tokens, you should understand how access tokens and authentication work in web apps. After this, you can learn about token storage, security best practices, and implementing token rotation for better protection.
Mental Model
Core Idea
A refresh token is like a special key that lets you get a new temporary key without re-entering your password.
Think of it like...
Imagine you have a hotel room key card that expires every day (access token). The hotel gives you a master card (refresh token) that lets you get a new room key card without going to the front desk each time.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   User logs   │──────▶│  Server issues │──────▶│ Access Token  │
│    in once    │       │ Access + Refresh│       │ (short-lived) │
└───────────────┘       │    Tokens      │       └───────────────┘
                        └───────────────┘               │
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Access Token  │
                                               │   expires     │
                                               └───────────────┘
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Use Refresh   │
                                               │ Token to get │
                                               │ new Access   │
                                               │ Token       │
                                               └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Access Tokens
🤔
Concept: Access tokens are short-lived codes that prove a user is logged in.
When a user logs in, the server gives them an access token. This token is like a temporary pass that lets the user access protected parts of the app. It usually lasts a short time, like 15 minutes to an hour.
Result
Users can access protected resources without re-entering credentials during the token's lifetime.
Knowing access tokens are temporary helps understand why we need a way to renew them without bothering the user.
2
FoundationWhy Tokens Expire Quickly
🤔
Concept: Short expiration limits risk if a token is stolen.
If an access token lasts too long, someone who steals it can misuse it for a long time. By making tokens expire quickly, the app reduces this risk. But this means users need a way to get new tokens without logging in again.
Result
Access tokens expire fast, improving security but requiring token renewal.
Understanding the trade-off between security and user convenience sets the stage for refresh tokens.
3
IntermediateIntroducing Refresh Tokens
🤔Before reading on: do you think refresh tokens are used to access resources directly or to get new access tokens? Commit to your answer.
Concept: Refresh tokens let users get new access tokens without logging in again.
Along with the access token, the server gives a refresh token. This token lasts longer and is only used to ask the server for a new access token when the old one expires. The refresh token is never sent to access protected data directly.
Result
Users stay logged in longer without re-entering credentials, improving experience and security.
Knowing refresh tokens only request new access tokens clarifies their role and limits exposure.
4
IntermediateStoring Refresh Tokens Securely
🤔Before reading on: do you think storing refresh tokens in browser localStorage is safe or risky? Commit to your answer.
Concept: Refresh tokens must be stored securely to prevent theft.
Because refresh tokens last longer, if stolen, they can be misused. Storing them in secure, httpOnly cookies helps protect them from JavaScript attacks. Avoid storing refresh tokens in places accessible by scripts, like localStorage.
Result
Refresh tokens are less likely to be stolen, reducing security risks.
Understanding secure storage prevents common security mistakes that expose refresh tokens.
5
IntermediateUsing Refresh Tokens in Express Apps
🤔
Concept: Express apps handle refresh tokens by verifying and issuing new access tokens.
When the client sends a refresh token to the server, Express verifies it. If valid, the server creates a new access token and sends it back. This process keeps the user logged in without asking for credentials again.
Result
Users get seamless access token renewal in Express apps.
Knowing the server-side flow helps build secure and user-friendly authentication.
6
AdvancedRefresh Token Rotation and Revocation
🤔Before reading on: do you think refresh tokens should be reused or replaced after each use? Commit to your answer.
Concept: Replacing refresh tokens after each use improves security.
Refresh token rotation means issuing a new refresh token every time the old one is used. This limits damage if a token is stolen. Also, servers keep track of valid refresh tokens to revoke them if needed, like when a user logs out.
Result
Better protection against stolen refresh tokens and easier logout handling.
Understanding rotation and revocation is key to building robust, secure authentication systems.
7
ExpertHandling Refresh Token Attacks and Edge Cases
🤔Before reading on: do you think a stolen refresh token can be used indefinitely if not rotated? Commit to your answer.
Concept: Refresh tokens can be attacked, so apps must detect misuse and handle errors gracefully.
If a refresh token is stolen, attackers can try to use it. Rotation helps detect reuse of old tokens, signaling an attack. Apps should revoke all tokens and force re-login if misuse is detected. Also, handling expired or malformed tokens prevents crashes and security holes.
Result
Apps become resilient to token theft and maintain user security.
Knowing these advanced protections prevents serious security breaches in production.
Under the Hood
When a user logs in, the server creates two tokens: a short-lived access token and a long-lived refresh token. The access token is signed and contains user info to authorize requests. The refresh token is stored securely and used only to request new access tokens. The server verifies refresh tokens against a database or uses cryptographic checks. On refresh, the server may invalidate the old refresh token and issue a new one to prevent reuse.
Why designed this way?
This design balances security and usability. Short-lived access tokens reduce risk if stolen, while refresh tokens avoid forcing users to log in repeatedly. Rotation and revocation mechanisms address token theft risks. Alternatives like long-lived access tokens were rejected because they increase attack windows.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ User logs in  │──────▶│ Server creates │──────▶│ Access Token  │
│               │       │ Access + Refresh│       │ (short-lived) │
└───────────────┘       │ Tokens        │       └───────────────┘
                        └───────────────┘               │
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Access Token  │
                                               │ expires      │
                                               └───────────────┘
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Client sends  │
                                               │ Refresh Token │
                                               └───────────────┘
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Server checks │
                                               │ Refresh Token │
                                               └───────────────┘
                                                        │
                                                        ▼
                                               ┌───────────────┐
                                               │ Issues new    │
                                               │ Access Token  │
                                               └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do refresh tokens allow direct access to protected data? Commit yes or no.
Common Belief:Refresh tokens can be used like access tokens to get data directly.
Tap to reveal reality
Reality:Refresh tokens are only for getting new access tokens and cannot access protected resources directly.
Why it matters:Using refresh tokens directly would break security and expose sensitive data.
Quick: Is storing refresh tokens in localStorage safe? Commit yes or no.
Common Belief:It's safe to store refresh tokens in localStorage for easy access.
Tap to reveal reality
Reality:Storing refresh tokens in localStorage exposes them to JavaScript attacks like XSS, risking theft.
Why it matters:If stolen, attackers can get new access tokens and impersonate users.
Quick: Should refresh tokens be reused indefinitely? Commit yes or no.
Common Belief:You can reuse the same refresh token multiple times without risk.
Tap to reveal reality
Reality:Reusing refresh tokens without rotation increases risk if a token is stolen; rotation limits this risk.
Why it matters:Not rotating tokens can allow attackers to use stolen tokens indefinitely.
Quick: Do refresh tokens last forever? Commit yes or no.
Common Belief:Refresh tokens never expire and can be used forever.
Tap to reveal reality
Reality:Refresh tokens have expiration or can be revoked to limit misuse.
Why it matters:Infinite lifetime tokens increase security risks and make revoking access harder.
Expert Zone
1
Refresh token rotation requires careful synchronization to avoid race conditions where multiple tokens are accepted.
2
Some systems use stateless refresh tokens with cryptographic signatures, avoiding database lookups but requiring careful revocation strategies.
3
Implementing refresh token reuse detection can alert on token theft attempts and trigger security responses.
When NOT to use
Refresh tokens are not suitable for public clients like single-page apps without secure storage. In such cases, short-lived access tokens with silent re-authentication or PKCE flows are better alternatives.
Production Patterns
In production, refresh tokens are stored in httpOnly secure cookies, rotated on each use, and tracked in a database for revocation. Servers implement reuse detection and force logout on suspicious activity. This pattern balances security and user experience.
Connections
OAuth 2.0 Authorization Framework
Refresh tokens are a core part of OAuth 2.0 flows for delegated access.
Understanding refresh tokens helps grasp how OAuth manages long-term access securely.
Session Management in Web Applications
Refresh tokens serve a similar role to server-side sessions but in a stateless way.
Knowing refresh tokens clarifies modern stateless authentication compared to traditional sessions.
Cryptographic Key Rotation
Refresh token rotation parallels key rotation practices in cryptography to limit exposure.
Recognizing this connection highlights the importance of limiting token lifetime to reduce attack windows.
Common Pitfalls
#1Storing refresh tokens in localStorage exposing them to XSS attacks.
Wrong approach:localStorage.setItem('refreshToken', token);
Correct approach:Set refresh token in httpOnly, secure cookie from server response headers.
Root cause:Misunderstanding that localStorage is accessible by JavaScript and vulnerable to attacks.
#2Reusing the same refresh token without rotation.
Wrong approach:Client sends the same refresh token repeatedly without requesting a new one.
Correct approach:Server issues a new refresh token with each refresh request and invalidates the old one.
Root cause:Not realizing that rotation limits damage from stolen tokens.
#3Allowing refresh tokens to never expire.
Wrong approach:Issuing refresh tokens without expiration or revocation mechanisms.
Correct approach:Set expiration on refresh tokens and track them for revocation on logout or suspicious activity.
Root cause:Assuming refresh tokens are safe indefinitely without lifecycle management.
Key Takeaways
Refresh tokens let users get new access tokens without logging in again, improving user experience.
They must be stored securely, usually in httpOnly cookies, to prevent theft by malicious scripts.
Refresh token rotation and revocation are essential to protect against token theft and misuse.
Understanding refresh tokens bridges the gap between short-lived access tokens and long-term user sessions.
Proper implementation of refresh tokens is critical for secure and smooth authentication in modern web apps.

Practice

(1/5)
1. What is the main purpose of a refresh token in an Express app using authentication?
easy
A. To encrypt the access token
B. To store user passwords securely
C. To log out the user automatically after a timeout
D. To get a new access token without asking the user to log in again

Solution

  1. Step 1: Understand the role of refresh tokens

    Refresh tokens allow the app to request new access tokens without user interaction.
  2. 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.
  3. Final Answer:

    To get a new access token without asking the user to log in again -> Option D
  4. Quick 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
A. res.setHeader('refresh-token', token);
B. res.sendRefreshToken(token);
C. res.refreshToken = token;
D. res.header('Authorization', token);

Solution

  1. Step 1: Recall Express method to set headers

    Express uses res.setHeader(name, value) to set response headers.
  2. 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.
  3. Final Answer:

    res.setHeader('refresh-token', token); -> Option A
  4. Quick 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
A. Status 401 with message 'No token'
B. Status 403 with message 'Invalid token'
C. JSON response with new access token
D. Empty response with status 200

Solution

  1. Step 1: Check token presence and validity

    If refreshToken is missing, returns 401; if invalid, returns 403.
  2. Step 2: For valid token, send new access token JSON

    When token equals 'validtoken', response sends JSON with new access token.
  3. Final Answer:

    JSON response with new access token -> Option C
  4. Quick 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
A. Missing return statements after res.status calls causing multiple responses
B. Incorrect property name for token in request body
C. Using res.json instead of res.send
D. No bug, code works fine

Solution

  1. Step 1: Check response flow after status calls

    Without return, code continues after sending response, causing errors.
  2. Step 2: Confirm need for return to stop execution

    Adding return after res.status(...).send(...) prevents multiple responses.
  3. Final Answer:

    Missing return statements after res.status calls causing multiple responses -> Option A
  4. Quick 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
A. Keep the same refresh token forever to avoid user re-login
B. Issue a new refresh token on each use and invalidate the old one
C. Send refresh token only once during login and never again
D. Store refresh tokens in localStorage on the client side

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Issue a new refresh token on each use and invalidate the old one -> Option B
  4. Quick 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