Bird
Raised Fist0
Node.jsframework~20 mins

Session-based vs token-based auth in Node.js - Practice Questions

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Auth Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is a key difference between session-based and token-based authentication?

Choose the option that best describes a fundamental difference between session-based and token-based authentication methods.

ASession-based auth stores user data on the server, while token-based auth stores user data on the client.
BSession-based auth requires the client to send a token with every request, token-based does not.
CToken-based auth stores session data on the server, session-based stores it in cookies.
DToken-based auth only works with cookies, session-based only with local storage.
Attempts:
2 left
💡 Hint

Think about where the user state is kept in each method.

❓ component_behavior
intermediate
2:00remaining
What happens when a token expires in token-based authentication?

In token-based authentication, what is the typical behavior when the token expires?

AThe server automatically renews the token without client action.
BThe session on the server is cleared but the token remains valid.
CThe client must re-authenticate to get a new token.
DThe token silently refreshes in the background without user notice.
Attempts:
2 left
💡 Hint

Consider who controls token renewal in token-based auth.

🔧 Debug
advanced
3:00remaining
Why does this session-based auth code fail to keep user logged in?

Examine the Node.js Express code below. Why does the user get logged out immediately after login?

Node.js
app.post('/login', (req, res) => {
  const user = authenticate(req.body.username, req.body.password);
  if (user) {
    req.session.user = user;
    res.redirect('/dashboard');
  } else {
    res.status(401).send('Login failed');
  }
});

app.get('/dashboard', (req, res) => {
  if (!req.session.user) {
    res.redirect('/login');
  } else {
    res.send(`Welcome ${req.session.user.name}`);
  }
});
AThe session cookie is set to expire immediately.
BThe authenticate function returns null causing session.user to be undefined.
CThe redirect after login clears the session data.
DThe session middleware is not configured or used in the app.
Attempts:
2 left
💡 Hint

Check if the app uses session middleware properly.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly verifies a JWT token in Node.js?

Choose the code snippet that correctly verifies a JWT token using the jsonwebtoken library.

Ajwt.verify(token, secret, (err, decoded) => { if (err) throw err; console.log(decoded); });
Bjwt.verify(token, (err, decoded) => { if (err) throw err; console.log(decoded); });
Cjwt.decode(token, secret, (err, decoded) => { if (err) throw err; console.log(decoded); });
Djwt.check(token, secret, (err, decoded) => { if (err) throw err; console.log(decoded); });
Attempts:
2 left
💡 Hint

Look for the correct method name and parameters for verifying a JWT.

❓ state_output
expert
2:30remaining
What is the output of this token-based auth middleware when token is missing?

Given the following Express middleware, what response does the server send if the request has no Authorization header?

Node.js
function authMiddleware(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    return res.status(401).json({ error: 'No token provided' });
  }
  const token = authHeader.split(' ')[1];
  jwt.verify(token, 'secret', (err, user) => {
    if (err) return res.status(403).json({ error: 'Invalid token' });
    req.user = user;
    next();
  });
}
AServer crashes with TypeError
B{"error":"No token provided"} with status 401
CNext middleware is called without error
D{"error":"Invalid token"} with status 403
Attempts:
2 left
💡 Hint

Check the condition when Authorization header is missing.

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

  1. Step 1: Understand session-based auth storage

    Session-based authentication stores user info on the server side, typically in memory or a database.
  2. 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.
  3. Final Answer:

    User data is stored on the server and linked to the client via cookies. -> Option A
  4. 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

  1. 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.
  2. Step 2: Match correct syntax for session cookie

    res.cookie('sessionId', 'abc123', { httpOnly: true }) correctly sets a cookie named 'sessionId'.
  3. Final Answer:

    res.cookie('sessionId', 'abc123', { httpOnly: true }); -> Option D
  4. 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?
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');
}
medium
A. SyntaxError
B. Unauthorized
C. User ID: [user's id from token]
D. Token string printed as is

Solution

  1. Step 1: Extract token from Authorization header

    The code splits the 'Authorization' header to get the token part after 'Bearer'.
  2. Step 2: Verify token and extract user info

    jwt.verify checks the token with 'secretKey' and returns the decoded user object if valid.
  3. Final Answer:

    User ID: [user's id from token] -> Option C
  4. Quick Check:

    Valid token returns decoded user info [OK]
Hint: Valid JWT returns decoded user info, else error [OK]
Common Mistakes:
  • Assuming token is printed directly without decoding
  • Confusing token verification failure with syntax error
  • Ignoring optional chaining and possible undefined token
4. Identify the bug in this session-based auth middleware code snippet:
function auth(req, res, next) {
  if (!req.session.user) {
    res.status(401).send('Not logged in');
  }
  next();
}
medium
A. req.session.user should be req.user instead.
B. Missing return after sending 401 response causes next() to run anyway.
C. next() should be called before checking session.
D. res.status should be res.sendStatus.

Solution

  1. Step 1: Analyze control flow after sending response

    After res.status(401).send(), the function continues and calls next(), allowing unauthorized access.
  2. Step 2: Fix by adding return to stop execution

    Adding return before res.status stops the function, preventing next() from running when unauthorized.
  3. Final Answer:

    Missing return after sending 401 response causes next() to run anyway. -> Option B
  4. Quick Check:

    Return after response to stop middleware [OK]
Hint: Add return after res.send to prevent next() running [OK]
Common Mistakes:
  • Calling next() before checking session
  • Confusing req.session.user with req.user
  • Using res.sendStatus instead of res.status().send()
5. You want to build a Node.js app that supports multiple devices per user and scales easily. Which authentication method is best and why?
hard
A. Token-based auth, because tokens are stateless and work well across devices.
B. Token-based auth, because it requires server to store session data.
C. Session-based auth, because cookies automatically sync across devices.
D. Session-based auth, because it stores user data on the server for security.

Solution

  1. Step 1: Consider multi-device and scalability needs

    Supporting multiple devices means the server should not rely on storing session state for each device.
  2. Step 2: Choose token-based auth for statelessness

    Token-based auth uses signed tokens stored client-side, allowing stateless servers and easy scaling.
  3. Final Answer:

    Token-based auth, because tokens are stateless and work well across devices. -> Option A
  4. Quick Check:

    Stateless tokens = scalable multi-device auth [OK]
Hint: Use token auth for scalable, multi-device apps [OK]
Common Mistakes:
  • Thinking sessions sync automatically across devices
  • Believing token auth requires server session storage
  • Choosing session auth for scalability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard