Session-based vs Token-based Authentication in Node.js
📖 Scenario: You are building a simple Node.js server that handles user login. You want to understand how session-based and token-based authentication work by creating basic examples of each.
🎯 Goal: Build two simple authentication setups in Node.js: one using session-based authentication with express-session, and one using token-based authentication with JSON Web Tokens (jsonwebtoken).
📋 What You'll Learn
Create a user object with fixed username and password
Set up session configuration using express-session
Implement login route that creates a session on success
Set up token secret variable for JWT
Implement login route that returns a JWT token on success
Add middleware to protect a route using session or token
💡 Why This Matters
🌍 Real World
Web applications often need to authenticate users securely. Session-based auth stores login info on the server, while token-based auth uses tokens that clients keep. Understanding both helps build secure apps.
💼 Career
Many backend developer roles require knowledge of authentication methods. Knowing how to implement and protect routes with sessions and tokens is essential for building secure APIs and web apps.
Progress0 / 4 steps
1
Create a user object with fixed credentials
Create a constant called user with an object containing username set to 'user1' and password set to 'pass123'.
Node.js
Hint
Use const user = { username: 'user1', password: 'pass123' }; to create the user object.
2
Set up session configuration with express-session
Add these lines: import express and express-session, create an app using express(), and configure app to use express-session with a secret 'mysecret', resave set to false, and saveUninitialized set to true.
Node.js
Hint
Use require to import modules and app.use(session({...})) to configure sessions.
3
Implement login route that creates a session on success
Add a POST route /login that reads username and password from req.body. If they match the user object, set req.session.user to user.username and send 'Logged in'. Otherwise, send 'Invalid credentials'. Use express.json() middleware.
Node.js
Hint
Use app.post with express.json() to read JSON body and set session on success.
4
Set up token secret and implement token-based login route
Add jsonwebtoken import, create a constant tokenSecret with value 'tokensecret'. Add a POST route /token-login that reads username and password from req.body. If they match user, create a JWT token signed with tokenSecret containing { username } and send it as JSON { token }. Otherwise, send { error: 'Invalid credentials' }. Also add middleware authenticateToken that checks the token from Authorization header and calls next() if valid, else sends 401. Add a protected GET route /protected that uses authenticateToken and sends 'Protected content'.
Node.js
Hint
Use jsonwebtoken to create and verify tokens. Extract token from Authorization header. Protect routes with middleware.
Practice
(1/5)
1. Which of the following best describes session-based authentication in Node.js?
easy
A. User data is stored on the server and linked to the client via cookies.
B. User credentials are sent with every request without storing data on the server.
C. A signed token is stored on the server and sent to the client.
D. Authentication is done only once without any session or token.
Solution
Step 1: Understand session-based auth storage
Session-based authentication stores user info on the server side, typically in memory or a database.
Step 2: Identify how client links to session
The client receives a cookie that holds a session ID to link requests to the stored session data.
Final Answer:
User data is stored on the server and linked to the client via cookies. -> Option A
Quick Check:
Session-based auth = server stores data + cookie link [OK]
Hint: Session auth stores data server-side, linked by cookies [OK]
Common Mistakes:
Thinking tokens are stored on the server in session auth
Confusing session ID with user credentials
Assuming session data is stored on the client
2. Which code snippet correctly sets a cookie for session-based authentication in Express.js?
easy
A. res.session('abc123');
B. res.setHeader('Authorization', 'Bearer abc123');
C. res.sendToken('abc123');
D. res.cookie('sessionId', 'abc123', { httpOnly: true });
Solution
Step 1: Identify Express.js method to set cookies
Express uses res.cookie() to set cookies on the client with options like httpOnly for security.
Step 2: Match correct syntax for session cookie
res.cookie('sessionId', 'abc123', { httpOnly: true }) correctly sets a cookie named 'sessionId'.
Final Answer:
res.cookie('sessionId', 'abc123', { httpOnly: true }); -> Option D
Quick Check:
Use res.cookie() to set session cookies [OK]
Hint: Use res.cookie() to set cookies in Express [OK]
Common Mistakes:
Using res.setHeader for cookies instead of Authorization header
Assuming res.sendToken is a valid Express method
Trying to set session with res.session which doesn't exist
3. Given this token-based auth code snippet, what will be the output if the token is valid?