JWT Access Tokens
JWT Access Tokens: free step-by-step lesson with examples, common mistakes, and interview tips — part of MERN Stack Tutorial on Toolliyo Academy.
On this page
MERN Stack Tutorial · Lesson 42 of 100
JWT Access Tokens
Setup & React ✓ → API Mongo Auth → Wire & Harden → Ship & Projects
API Mongo Auth · 2 — Backend · ~6 min · Authentication
What is this?
After login, the API signs a JWT with a secret and returns it. Clients send Authorization: Bearer
Why should you care?
MernVerse needs identity without storing server sessions for every request (stateless APIs).
See it live — copy this example
Run examples in your MernVerse client/ (Vite React) or server/ (Express) folders. Keep secrets in .env.
import jwt from 'jsonwebtoken';
const token = jwt.sign(
{ sub: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// middleware
const payload = jwt.verify(header.slice(7), process.env.JWT_SECRET);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Keep JWT_SECRET long and private.
- Put only non-sensitive claims in the payload.
- Verify on every protected route.
Practice next
- Install jsonwebtoken.
- Sign on login success.
- Verify in auth middleware.
- Add role to claims.
- Return token in JSON { token }.
Remember
Sign after auth. Bearer scheme. Short expiry + refresh later.
Login token
SPA must call /api/notes securely.
Outcome: Protected route accepts a valid JWT.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!