Skip to content

Instantly share code, notes, and snippets.

@nsdevaraj
Created August 5, 2024 14:13
Show Gist options
  • Save nsdevaraj/b8e0c26cbcaa1d56906e04f9945f8125 to your computer and use it in GitHub Desktop.
Save nsdevaraj/b8e0c26cbcaa1d56906e04f9945f8125 to your computer and use it in GitHub Desktop.
Prevention of Cross-Site Request Forgery (CSRF) Attacks
import express from 'express';
import csrf from 'csurf';
import cookieParser from 'cookie-parser';
const app = express();
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use((req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next();
});
app.post('/submit-form', (req, res) => {
// The CSRF token is automatically validated by the csurf middleware
// If validation fails, it will throw an error
// Process the form submission
res.send('Form submitted successfully');
});
// Error handler
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('CSRF token validation failed');
} else {
next(err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment