Bird
Raised Fist0
Expressframework~20 mins

CSRF protection in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
CSRF Protection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does CSRF token validation work in Express?
Consider an Express app using the csurf middleware. What happens when a POST request is sent without the CSRF token?
Express
const express = require('express');
const csurf = require('csurf');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());
app.use(csurf({ cookie: true }));

app.post('/submit', (req, res) => {
  res.send('Form submitted');
});
AThe server responds with a 403 Forbidden error because the CSRF token is missing or invalid.
BThe server logs the request but still processes it without blocking.
CThe server redirects the user to the login page automatically.
DThe server accepts the request and processes it normally without any error.
Attempts:
2 left
πŸ’‘ Hint
Think about what the csurf middleware does when the token is missing or wrong.
πŸ“ Syntax
intermediate
1:30remaining
Which code snippet correctly sets up CSRF protection with cookies in Express?
Choose the correct code to enable CSRF protection using the csurf middleware with cookie support.
Aapp.use(csurf({ cookie: false }));
Bapp.use(csurf({ session: true }));
Capp.use(csurf({ cookie: true }));
Dapp.use(csurf());
Attempts:
2 left
πŸ’‘ Hint
Look for the option that enables cookie-based CSRF tokens.
πŸ”§ Debug
advanced
2:30remaining
Why does the CSRF token validation fail in this Express app?
Given the code below, why does the server always respond with a 403 error on POST requests?
Express
const express = require('express');
const csurf = require('csurf');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());
app.use(csurf({ cookie: true }));

app.get('/form', (req, res) => {
  res.send(`<form method='POST' action='/submit'>
    <input type='hidden' name='_csrf' value='${req.csrfToken()}' />
    <button type='submit'>Submit</button>
  </form>`);
});

app.post('/submit', (req, res) => {
  res.send('Success');
});
AThe app is missing express.urlencoded middleware before csurf, so the body is not parsed and token is not found.
BThe cookieParser middleware is used after csurf, so cookies are not read correctly.
CThe CSRF token is not included in the form, so validation fails.
DThe csurf middleware is configured incorrectly; it should not use cookies.
Attempts:
2 left
πŸ’‘ Hint
Check the order of middleware and what csurf needs to read the token from the body.
🧠 Conceptual
advanced
1:30remaining
What is the main purpose of CSRF protection in web frameworks like Express?
Why do we add CSRF protection middleware in web applications?
ATo authenticate users by verifying their passwords.
BTo encrypt user data sent between client and server.
CTo speed up server response times by caching requests.
DTo prevent attackers from tricking users into submitting unwanted requests on their behalf.
Attempts:
2 left
πŸ’‘ Hint
Think about what CSRF attacks do to users and servers.
❓ state_output
expert
2:00remaining
What is the value of the CSRF token after this Express route runs?
Given the code below, what will be the output of the console.log statement?
Express
const express = require('express');
const csurf = require('csurf');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());
app.use(csurf({ cookie: true }));

app.get('/token', (req, res) => {
  const token = req.csrfToken();
  console.log(token);
  res.send('Token sent');
});
AAn empty string because no token is generated.
BA unique string token generated for the user session, e.g., 'XyZ123AbC'.
CAn error is thrown because cookieParser is missing.
DUndefined, because req.csrfToken() is not a function.
Attempts:
2 left
πŸ’‘ Hint
What does req.csrfToken() return when csurf middleware is used correctly?

Practice

(1/5)
1. What is the main purpose of CSRF protection in an Express app?
easy
A. To prevent unauthorized commands from being sent from other websites
B. To speed up the server response time
C. To encrypt user passwords
D. To log user activity on the server

Solution

  1. Step 1: Understand CSRF meaning

    CSRF stands for Cross-Site Request Forgery, which tricks users into submitting unwanted actions.
  2. Step 2: Identify CSRF protection goal

    Protection stops other sites from sending commands on behalf of a user without permission.
  3. Final Answer:

    To prevent unauthorized commands from being sent from other websites -> Option A
  4. Quick Check:

    CSRF protection = prevent unauthorized commands [OK]
Hint: CSRF stops fake requests from other sites [OK]
Common Mistakes:
  • Confusing CSRF with password encryption
  • Thinking it speeds up server
  • Believing it logs user activity
2. Which of the following is the correct way to add CSRF protection middleware in Express using the csurf package?
easy
A. app.use(csurf({ cookie: true }))
B. app.use(csrf())
C. app.use(csrfProtection())
D. app.use(csrf({ session: false }))

Solution

  1. Step 1: Recall csurf usage

    The csurf middleware is used as csurf({ cookie: true }) to enable cookie-based CSRF tokens.
  2. Step 2: Check options correctness

    Options B, C, and D use wrong function names or invalid options.
  3. Final Answer:

    app.use(csurf({ cookie: true })) -> Option A
  4. Quick Check:

    Correct csurf syntax = app.use(csurf({ cookie: true })) [OK]
Hint: Use csurf with correct function and options [OK]
Common Mistakes:
  • Using wrong function name like csrf()
  • Missing the cookie option
  • Passing invalid options
3. Given this Express route using csurf middleware, what will happen if the CSRF token is missing or invalid?
app.post('/submit', csurf({ cookie: true }), (req, res) => {
  res.send('Form submitted');
});
medium
A. The server redirects to the home page
B. The server responds with 'Form submitted' anyway
C. The server throws a 403 Forbidden error
D. The server crashes with an uncaught exception

Solution

  1. Step 1: Understand csurf error handling

    If the CSRF token is missing or invalid, csurf middleware triggers an error with status 403 Forbidden.
  2. Step 2: Check route behavior

    The route handler is not called; instead, Express sends a 403 error response.
  3. Final Answer:

    The server throws a 403 Forbidden error -> Option C
  4. Quick Check:

    Invalid CSRF token = 403 Forbidden error [OK]
Hint: Missing token causes 403 error, not success [OK]
Common Mistakes:
  • Assuming form submits anyway
  • Thinking server redirects automatically
  • Believing server crashes
4. You added csurf middleware but your form keeps failing CSRF validation. Which of these is the most likely cause?
medium
A. You did not install the cookie-parser package
B. You used app.use(express.json()) before csurf()
C. You set cookie: false in csurf options
D. You forgot to include the CSRF token in the form as a hidden input

Solution

  1. Step 1: Check form token inclusion

    CSRF protection requires the token to be sent with the form, usually as a hidden input field.
  2. Step 2: Evaluate other options

    While cookie-parser is needed if using cookies, the most common cause is missing token in the form.
  3. Final Answer:

    You forgot to include the CSRF token in the form as a hidden input -> Option D
  4. Quick Check:

    Missing token in form = validation fails [OK]
Hint: Always add CSRF token hidden input in forms [OK]
Common Mistakes:
  • Ignoring token in form fields
  • Misordering middleware without reason
  • Assuming cookie-parser always required
5. You want to protect an Express app using csurf with cookie-based tokens and render the token in a form. Which code snippet correctly sets up the middleware and passes the token to the template?
hard
A. app.use(csurf({ cookie: false })); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); });
B. app.use(csurf({ cookie: true })); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); });
C. app.use(csurf()); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken }); });
D. app.use(csurf({ cookie: true })); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken }); });

Solution

  1. Step 1: Setup csurf with cookie option

    Use csurf({ cookie: true }) to enable cookie-based CSRF tokens.
  2. Step 2: Call req.csrfToken() as a function

    To get the token string, call req.csrfToken(), not just reference the function.
  3. Step 3: Pass token to template

    Pass the token as csrfToken in the render call for the form to use.
  4. Final Answer:

    app.use(csurf({ cookie: true })); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); }); -> Option B
  5. Quick Check:

    Correct csurf setup + token call = app.use(csurf({ cookie: true })); app.get('/form', (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); }); [OK]
Hint: Call req.csrfToken() and enable cookie option [OK]
Common Mistakes:
  • Not calling req.csrfToken() as a function
  • Using cookie: false when cookies are needed
  • Passing function reference instead of token string