Discover how websites keep you logged in smoothly without asking for your password every time!
Session-based vs token-based auth in Node.js - When to Use Which
Imagine building a website where users log in, and you have to remember who they are on every page they visit.
You try to do this by checking their username and password on every request manually.
Manually checking login details on every request is slow and risky.
You might forget to check sometimes, or users get logged out unexpectedly.
It's hard to keep track of who is logged in and protect their data safely.
Session-based and token-based authentication help automatically remember users safely.
Sessions store user info on the server, while tokens let users prove who they are without extra server checks.
if (req.body.username === 'user' && req.body.password === 'pass') { /* allow access */ } else { /* deny */ }
app.use(session({ secret: 'secret', resave: false, saveUninitialized: true })); // or use JWT tokens for stateless authThese methods let users stay logged in securely and make your app faster and easier to manage.
When you log into your favorite shopping site, session or token auth remembers you so you don't have to enter your password on every page.
Manual login checks are slow and error-prone.
Session-based auth stores user info on the server.
Token-based auth lets users prove identity without server storage.
Practice
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 AQuick Check:
Session-based auth = server stores data + cookie link [OK]
- Thinking tokens are stored on the server in session auth
- Confusing session ID with user credentials
- Assuming session data is stored on the client
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 DQuick Check:
Use res.cookie() to set session cookies [OK]
- 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
const jwt = require('jsonwebtoken');
const token = req.headers.authorization?.split(' ')[1];
try {
const user = jwt.verify(token, 'secretKey');
res.send(`User ID: ${user.id}`);
} catch {
res.status(401).send('Unauthorized');
}Solution
Step 1: Extract token from Authorization header
The code splits the 'Authorization' header to get the token part after 'Bearer'.Step 2: Verify token and extract user info
jwt.verify checks the token with 'secretKey' and returns the decoded user object if valid.Final Answer:
User ID: [user's id from token] -> Option CQuick Check:
Valid token returns decoded user info [OK]
- Assuming token is printed directly without decoding
- Confusing token verification failure with syntax error
- Ignoring optional chaining and possible undefined token
function auth(req, res, next) {
if (!req.session.user) {
res.status(401).send('Not logged in');
}
next();
}Solution
Step 1: Analyze control flow after sending response
After res.status(401).send(), the function continues and calls next(), allowing unauthorized access.Step 2: Fix by adding return to stop execution
Adding return before res.status stops the function, preventing next() from running when unauthorized.Final Answer:
Missing return after sending 401 response causes next() to run anyway. -> Option BQuick Check:
Return after response to stop middleware [OK]
- Calling next() before checking session
- Confusing req.session.user with req.user
- Using res.sendStatus instead of res.status().send()
Solution
Step 1: Consider multi-device and scalability needs
Supporting multiple devices means the server should not rely on storing session state for each device.Step 2: Choose token-based auth for statelessness
Token-based auth uses signed tokens stored client-side, allowing stateless servers and easy scaling.Final Answer:
Token-based auth, because tokens are stateless and work well across devices. -> Option AQuick Check:
Stateless tokens = scalable multi-device auth [OK]
- Thinking sessions sync automatically across devices
- Believing token auth requires server session storage
- Choosing session auth for scalability
Ready to prove it?
Pass the test and this pattern moves unknown
