DEV Community

Cover image for πŸ” Session Token vs Refresh Token β€” The Simplest Explanation!
Rajon Dey
Rajon Dey

Posted on

πŸ” Session Token vs Refresh Token β€” The Simplest Explanation!

Modern web apps run on tokens. But which one does what? Let's break down Session Tokens and Refresh Tokens so clearly that you’ll never forget, and confidently implement them in any project.


Let’s go from concept to code and build your solid understanding with:

  1. πŸ”§ What to Build (Token System Essentials)
  2. πŸ“œ Functions You’ll Need
  3. πŸ” Algorithms/Flows
  4. πŸ› οΈ Tools & Libraries (with alternatives)
  5. πŸš€ Trendy/Best Practices
  6. 🏒 What Big Tech Uses

πŸ”§ 1. WHAT TO BUILD – Token Auth System in Any App

Any software (web, mobile, API-based) with token authentication will have 3 main parts:

Step Action
πŸ” 1 Login (generate access + refresh tokens)
πŸ”„ 2 Refresh token (get new access token)
πŸ”“ 3 Logout (invalidate refresh token)

πŸ“œ 2. REQUIRED FUNCTIONS (in pseudo + JS-style)

You typically need to write 5 core functions:

// 1. Login
function login(email, password) {
  // validate user
  // generate accessToken + refreshToken
  // store refreshToken securely (DB or cookie)
}

// 2. Generate Access Token
function generateAccessToken(user) {
  // return jwt.sign(user, secret, { expiresIn: '15m' })
}

// 3. Generate Refresh Token
function generateRefreshToken(user) {
  // return jwt.sign(user, refreshSecret, { expiresIn: '7d' })
}

// 4. Refresh Token Endpoint
function refresh(req) {
  // validate refreshToken
  // if valid => issue new accessToken
}

// 5. Logout
function logout(req) {
  // remove/invalidate refreshToken
}
Enter fullscreen mode Exit fullscreen mode

Add:

  • βœ… middleware to check access token on every API call
  • πŸ”„ Token rotation strategy

πŸ” 3. ALGORITHM FLOW (Pseudocode)

A. Login Flow

User submits email + password
↓
If valid:
  β†’ generate access token (15 mins)
  β†’ generate refresh token (7 days)
  β†’ send access in body, refresh in HTTP-only cookie
Enter fullscreen mode Exit fullscreen mode

B. API Request Flow

Frontend sends access token in headers
↓
Backend verifies token
↓
If valid β†’ grant access
If expired β†’ ask frontend to refresh token
Enter fullscreen mode Exit fullscreen mode

C. Token Refresh Flow

Frontend sends refresh token (cookie)
↓
Backend verifies it
↓
If valid β†’ issue new access token (maybe refresh token too)
↓
Frontend replaces old token and continues
Enter fullscreen mode Exit fullscreen mode

D. Logout Flow

User clicks logout
↓
Frontend deletes tokens (cookie/localStorage)
↓
Backend blacklists or deletes refresh token from DB
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ 4. TOOLS TO USE

πŸ”‘ Token Generator

  • jsonwebtoken (Node.js)
  • pyjwt (Python)
  • nimbus-jose-jwt (Java)

πŸ“¦ Session Store (Optional)

  • Redis (store refresh token or blacklist tokens)
  • In-memory (for demo)
  • Database (Mongo, Postgres)

πŸͺ Cookie Management

  • cookie-parser (Node)
  • HttpOnly + SameSite=Strict for refresh tokens

πŸ” Auth Libs (if you want ready-made)

  • NextAuth.js (Next.js)
  • Passport.js (Node)
  • Firebase Auth (Google, prebuilt solution)
  • Supabase Auth (Backendless)

⚑ 5. TRENDY BEST PRACTICES

βœ… Use short-lived access tokens (15m to 1h)

βœ… Use refresh tokens with rotation (and maybe detection of reuse)

βœ… Store refresh token in HTTP-only secure cookies, never in localStorage

βœ… Add a logout-all-devices or token revoke option

βœ… Use middleware/auth guard in APIs/routes

✨ Extra: Use a queue (e.g., Redis) to store a blacklist of used refresh tokens (detect hijacking)


🏒 6. BIG TECH STRATEGY

Company Auth System Notes
Facebook Session cookie-based (internal), tokens for APIs Uses long-lived refresh system
Google OAuth2 + OpenID + JWT Access & Refresh tokens, stored securely
Discord Access token + refresh token flow Like OAuth2 spec
Spotify Strict refresh token rotation, OAuth2 Modern best practices
Netflix Short-lived access token, secure refresh handling High emphasis on device-level auth

πŸ’¬ Even big companies don't keep users logged in forever. They refresh tokens in the background to make UX smooth.


βœ… What You Should Write (Almost Any Software Needs):

Backend

  • Login route
  • Token generation utilities
  • Token refresh route
  • Logout route
  • Auth middleware
  • Optional: Token storage in DB or Redis

Frontend

  • Store access token (memory/localStorage)
  • Auto-refresh tokens on expiration
  • Logout flow
  • Attach token to API headers

🧠 Side-by-Side Snapshot

Feature Session Token (Access) Refresh Token
Purpose Access APIs Get new access tokens
Lifespan Short (15m–1h) Long (days–weeks)
Sent with requests βœ… Yes ❌ No
Risk if stolen High (frequently exposed) Low (stored securely)
Storage Memory/localStorage/cookie HTTP-only cookie (preferred)
Rotation ❌ Optional βœ… Recommended

🎯 Quick Summary

Use access tokens for immediate API calls.

Use refresh tokens to silently renew access without asking the user to log in again.

Store refresh tokens securely. Rotate them. Invalidate them on logout.

Access token is your key to the house. Refresh token is your ability to get a new key if you lose the old one.

Top comments (0)