MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
5.1Input Validation & Data Sanitization with Joi or Zod5.2User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies5.3Password Hashing with Bcrypt & Role-Based Access Control (RBAC)5.4Security Hardening: Helmet, CORS, Express Rate Limiting & HPP5.5Production Configuration, Environment Variables & PM2 Process Manager
HomeTutorialsNode.js & Express.jsUser Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies
Password Hashing with Bcrypt & Role-Based Access Control (RBAC)

User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Stateless authentication using JSON Web Tokens (JWT) is the modern standard for securing REST APIs and distributed microservices. When paired with HTTP-Only Cookies, JWTs protect client applications against Cross-Site Scripting (XSS) credential theft.


1. Anatomy of a JSON Web Token

A JWT consists of three base64url-encoded parts separated by periods (.):

1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0ZjEiLCJyb2xlIjoiYWRtaW4ifQ.uS7Z-K...
2[ HEADER ].[ PAYLOAD ].[ SIGNATURE ]
  1. 1
    Header: Algorithm and token type ({"alg": "HS256", "typ": "JWT"}).
  2. 2
    Payload: Claims and user identifiers ({"id": "usr_123", "role": "admin", "exp": 1718000000}). Never store sensitive data like plaintext passwords or credit cards in the payload!
  3. 3
    Signature: Cryptographic hash of (base64Header + "." + base64Payload) generated using a secret key or private RSA key.

2. Signing and Verifying JWTs

1import jwt from 'jsonwebtoken';
2 
3const JWT_SECRET = process.env.JWT_SECRET || 'super-secure-production-secret-key';
4const JWT_EXPIRES_IN = '1d';
5 
6// Generate token upon login
7export function generateToken(payload) {
8 return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
9}
10 
11// Verify token in authentication middleware
12export function verifyToken(token) {
13 return jwt.verify(token, JWT_SECRET);
14}

3. Why HTTP-Only Cookies Beat LocalStorage

Storing JWT tokens in browser localStorage exposes them to complete theft via malicious JavaScript injected through Cross-Site Scripting (XSS).

Instead, transmit the token in an HTTP-Only, Secure, SameSite Cookie:

1export function sendAuthTokenCookie(res, token) {
2 const cookieOptions = {
3 httpOnly: true, // Prevents client-side JS from accessing document.cookie (XSS Defense)
4 secure: process.env.NODE_ENV === 'production', // Transmitted ONLY over HTTPS
5 sameSite: 'strict', // Mitigates Cross-Site Request Forgery (CSRF)
6 maxAge: 24 * 60 * 60 * 1000 // 1 day
7 };
8 
9 res.cookie('token', token, cookieOptions);
10}

4. Authentication Guard Middleware

1import jwt from 'jsonwebtoken';
2 
3export const protectRoute = (req, res, next) => {
4 // Check Authorization header OR cookie
5 let token;
6 if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
7 token = req.headers.authorization.split(' ')[1];
8 } else if (req.cookies && req.cookies.token) {
9 token = req.cookies.token;
10 }
11 
12 if (!token) {
13 return res.status(401).json({ error: 'You are not logged in. Please provide a valid token.' });
14 }
15 
16 try {
17 const decoded = jwt.verify(token, process.env.JWT_SECRET);
18 req.user = decoded; // Attach user payload to request object
19 next();
20 } catch (err) {
21 return res.status(401).json({ error: 'Token is invalid or has expired.' });
22 }
23};

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Why is storing JWT authentication tokens in browser localStorage dangerous?
Question 2
What security property does the httpOnly: true cookie flag enforce?
Question 3
Which part of a JSON Web Token verifies that the token payload has not been tampered with in transit?
Question 4
What happens when jwt.verify() encounters a token whose expiration timestamp (exp) is in the past?
Question 5
Why should sensitive information like user passwords never be stored inside a JWT payload?

Next Lesson

Password Hashing with Bcrypt & Role-Based Access Control (RBAC)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Input Validation & Data Sanitization with Joi or ZodPassword Hashing with Bcrypt & Role-Based Access Control (RBAC)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext