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

Rajon DeyRajon Dey
4 min read

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:

StepAction
πŸ” 1Login (generate access + refresh tokens)
πŸ”„ 2Refresh token (get new access token)
πŸ”“ 3Logout (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
}

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

B. API Request Flow

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

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

D. Logout Flow

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

πŸ› οΈ 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-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

CompanyAuth SystemNotes
FacebookSession cookie-based (internal), tokens for APIsUses long-lived refresh system
GoogleOAuth2 + OpenID + JWTAccess & Refresh tokens, stored securely
DiscordAccess token + refresh token flowLike OAuth2 spec
SpotifyStrict refresh token rotation, OAuth2Modern best practices
NetflixShort-lived access token, secure refresh handlingHigh 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

FeatureSession Token (Access)Refresh Token
PurposeAccess APIsGet new access tokens
LifespanShort (15m–1h)Long (days–weeks)
Sent with requestsβœ… Yes❌ No
Risk if stolenHigh (frequently exposed)Low (stored securely)
StorageMemory/localStorage/cookieHTTP-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.

0
Subscribe to my newsletter

Read articles from Rajon Dey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rajon Dey
Rajon Dey

I'm a Software Developer, my passion is crafting smart, meaningful, and professional websites that enhance the online presence of individuals and businesses, making the web a more engaging, effective, and better platform. Get the data - https://developer-data.beehiiv.com/