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
CSRF Protection in Express
📖 Scenario: You are building a simple Express web server that serves a form to submit user data. To keep your app safe from Cross-Site Request Forgery (CSRF) attacks, you want to add CSRF protection.CSRF attacks happen when a malicious site tricks a user's browser into submitting unwanted requests to your server. Using a CSRF token helps your server verify that the form submission is genuine.
🎯 Goal: Build an Express server that uses the csurf middleware to protect a form from CSRF attacks. The form should include a hidden CSRF token field, and the server should validate this token on form submission.
📋 What You'll Learn
Create an Express app with the express and csurf packages
Set up cookie parsing with cookie-parser
Add the csurf middleware configured to use cookies
Serve a simple HTML form that includes the CSRF token as a hidden input
Handle the form POST request and verify the CSRF token
💡 Why This Matters
🌍 Real World
CSRF protection is essential for web apps that accept form submissions to prevent attackers from tricking users into submitting unwanted requests.
💼 Career
Understanding and implementing CSRF protection is a key skill for backend developers working with Express or similar web frameworks to build secure applications.
Progress0 / 4 steps
1
Set up Express app with cookie-parser
Create an Express app by importing express and cookie-parser. Then create an app instance with express() and use cookieParser() as middleware.
Express
Hint
Use require('express') and require('cookie-parser'). Then call express() to create the app and add cookieParser() as middleware.
2
Add csurf middleware with cookie option
Import csurf and add it as middleware to the app using app.use(). Configure csurf with the option { cookie: true }.
Express
Hint
Import csurf and add it with app.use(csurf({ cookie: true })) to enable CSRF protection using cookies.
3
Serve a form with CSRF token included
Add a GET route at '/' that sends an HTML form. The form must include a hidden input named _csrf with the value from req.csrfToken(). Use res.send() to send the HTML string.
Express
Hint
Use app.get('/', (req, res) => { ... }) and send a form with a hidden input named _csrf set to req.csrfToken().
4
Handle POST request and verify CSRF token
Add middleware to parse URL-encoded form data with express.urlencoded({ extended: false }). Then add a POST route at '/process' that sends a success message. The CSRF token will be verified automatically by the csurf middleware.
Express
Hint
Add express.urlencoded({ extended: false }) middleware to parse form data. Then add a POST route at /process that sends a success message.
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
Step 1: Understand CSRF meaning
CSRF stands for Cross-Site Request Forgery, which tricks users into submitting unwanted actions.
Step 2: Identify CSRF protection goal
Protection stops other sites from sending commands on behalf of a user without permission.
Final Answer:
To prevent unauthorized commands from being sent from other websites -> Option A
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
Step 1: Understand csurf error handling
If the CSRF token is missing or invalid, csurf middleware triggers an error with status 403 Forbidden.
Step 2: Check route behavior
The route handler is not called; instead, Express sends a 403 error response.
Final Answer:
The server throws a 403 Forbidden error -> Option C
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
Step 1: Check form token inclusion
CSRF protection requires the token to be sent with the form, usually as a hidden input field.
Step 2: Evaluate other options
While cookie-parser is needed if using cookies, the most common cause is missing token in the form.
Final Answer:
You forgot to include the CSRF token in the form as a hidden input -> Option D
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?