0
0
Expressframework~5 mins

CSRF protection in Express

Choose your learning style9 modes available
Introduction

CSRF protection stops bad websites from tricking your site into doing things you don't want. It keeps your users safe.

When you have forms that change user data like passwords or emails.
When users can perform actions like posting comments or making purchases.
When you want to keep user sessions secure from outside attacks.
When your site uses cookies to remember users.
When you want to follow web security best practices.
Syntax
Express
import csrf from 'csurf';
import cookieParser from 'cookie-parser';

const csrfProtection = csrf({ cookie: true });

app.use(cookieParser());
app.use(csrfProtection);

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

app.post('/process', (req, res) => {
  res.send('Data is processed safely.');
});

The csurf middleware adds a secret token to each user's cookie.

You must include the token in your forms as a hidden input named _csrf.

Examples
This sets up CSRF protection using cookies to store the token.
Express
const csrfProtection = csrf({ cookie: true });
This applies the CSRF protection middleware to all routes.
Express
app.use(csrfProtection);
This adds the CSRF token to your form so the server can check it later.
Express
res.send(`<input type='hidden' name='_csrf' value='${req.csrfToken()}' />`);
Sample Program

This Express app uses the csurf middleware to protect a form from CSRF attacks. The token is stored in a cookie and added to the form as a hidden input. When the form is submitted, the server checks the token before processing.

Express
import express from 'express';
import csrf from 'csurf';
import cookieParser from 'cookie-parser';

const app = express();
const port = 3000;

app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));

const csrfProtection = csrf({ cookie: true });

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

app.post('/process', csrfProtection, (req, res) => {
  res.send('Data is processed safely.');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Always use cookie-parser before csurf if you use cookie-based tokens.

If the CSRF token is missing or wrong, the server will reject the request with an error.

Remember to include the CSRF token in every form that changes data.

Summary

CSRF protection stops unwanted actions from other sites.

Use the csurf middleware with cookies or sessions.

Include the CSRF token in your forms as a hidden field.