Csurf

To install csurf in your Node.js project, you can use npm. Run the following command:

npm install csurf

Now that you have csurf installed, you can use it in your Express.js application. Here's an example of how to set it up

const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

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

// Middleware
app.use(cookieParser()); // Parse cookies
app.use(bodyParser.urlencoded({ extended: false })); // Parse form data

// Initialize csurf middleware
const csrfProtection = csrf({ cookie: true });

// Generate a csrf token and attach it to the response locals
app.use((req, res, next) => {
  res.locals.csrfToken = req.csrfToken();
  next();
});

// Routes
app.get('/', (req, res) => {
  res.send('CSRF Example');
});

app.get('/form', csrfProtection, (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

app.post('/process', csrfProtection, (req, res) => {
  res.send('CSRF Token Verified');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Last updated