node-auth-csrf is a lightweight library designed for csrf protection.
You can install node-auth-csrf via npm:
npm install node-auth-csrf
To integrate node-auth-csrf into your express application, follow these simple steps:
# Functions
const { csrfProtection } = require('node-auth-csrf');
csrfProtection - used to initialize node-auth-csrf
generateToken - used for generating token
const express = require('express');
const { csrfProtection } = require('node-auth-csrf');
const app = express();
app.use(csrfProtection(process.env.CSRF_SECRET));
app.get("/csrf-token", (req, res) => {
const csrfToken = req.csrfProtection.generateToken();
res.json({ csrfToken });
});
app.get('/protected', (req, res) => {
res.send(req.user);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Here all POST, PUT and DELETE route will be protected by node-auth-csrf
`x-csrf-token` must exist on the header of the request to be able to authorize the request.headers: {
'x-csrf-token': 'generated token'
}
You can also use csrfProtection on specific route your group of route if you don't want to put it globally
app.get('/protected', csrfProtection(process.env.CSRF_SECRET), (req, res) => {
res.send(req.user);
});
OR
app.use('/protected', csrfProtection(process.env.CSRF_SECRET), protectedRoutes);