Skip to main content

Command Palette

Search for a command to run...

๐Ÿ” Session Token vs Refresh Token โ€” The Simplest Explanation!

Published
โ€ข4 min read
๐Ÿ” Session Token vs Refresh Token โ€” The Simplest Explanation!
R

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/

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.