Add CSRF protection to forms and APIs
✓Works with OpenClaudeYou are a security engineer implementing CSRF (Cross-Site Request Forgery) protection. The user wants to add CSRF tokens to forms and validate them on the server side for both traditional forms and APIs.
What to check first
- Verify your web framework has CSRF middleware available (Express, Django, Rails, etc.)
- Check if you're using session management or stateless JWT auth (affects token strategy)
- Run
npm list express-sessionor equivalent to confirm session library is installed
Steps
- Install CSRF middleware package:
npm install csurf express-session cookie-parser(or framework equivalent) - Configure session middleware before CSRF middleware in your app initialization order
- Add
cookie-parsermiddleware to parse cookies and extract CSRF tokens - Initialize
csurfmiddleware withcookieParser()as the secret store - Generate and inject CSRF tokens into form templates using
req.csrfToken() - Add hidden input field with token name
_csrfto every form - For API endpoints, accept tokens from
X-CSRF-Tokenheader or form body field - Validate tokens automatically on unsafe HTTP methods (POST, PUT, DELETE, PATCH)
Code
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const app = express();
// Middleware order matters: parser → session → cookieParser → csrf
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: true, httpOnly: true, sameSite: 'strict' }
}));
app.use(cookieParser());
// CSRF protection middleware
const csrfProtection = csrf({ cookie: false });
// GET route: generate and send token
app.get('/form', csrfProtection, (req, res) => {
res.send(`
<form action="/submit" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<input type="email" name="email" required>
<button type="submit">Submit</button>
</form>
`);
});
// POST route: validate token automatically
app.post('/submit', csrfProtection, (req, res) => {
res.json({ message: 'Form submitted securely', email: req.body.email });
});
// API endpoint: accept token from header
app.post('/api/data', csrfProtection, (req, res) => {
res.json({ success: true, data: req.body });
});
// Error handler for CSRF failures
app.use((err, req, res, next) => {
if
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Security Skills
Other Claude Code skills in the same category — free to download.
Dependency Audit
Audit dependencies for known vulnerabilities
Secret Scanner
Scan codebase for leaked secrets and credentials
CSP Generator
Generate Content Security Policy headers
Input Sanitizer
Add input sanitization to prevent injection attacks
Auth Middleware
Create authentication middleware
RBAC Setup
Implement role-based access control
Security Headers
Configure security headers (HSTS, X-Frame-Options, etc.)
Encryption Helper
Set up encryption for sensitive data at rest
Want a Security skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.