Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Securityintermediate

CSRF Protection

Share

Add CSRF protection to forms and APIs

Works with OpenClaude

You 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-session or equivalent to confirm session library is installed

Steps

  1. Install CSRF middleware package: npm install csurf express-session cookie-parser (or framework equivalent)
  2. Configure session middleware before CSRF middleware in your app initialization order
  3. Add cookie-parser middleware to parse cookies and extract CSRF tokens
  4. Initialize csurf middleware with cookieParser() as the secret store
  5. Generate and inject CSRF tokens into form templates using req.csrfToken()
  6. Add hidden input field with token name _csrf to every form
  7. For API endpoints, accept tokens from X-CSRF-Token header or form body field
  8. 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

Quick Info

CategorySecurity
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
securitycsrfprotection

Install command:

curl -o ~/.claude/skills/csrf-protection.md https://claude-skills-hub.vercel.app/skills/security/csrf-protection.md

Related Security Skills

Other Claude Code skills in the same category — free to download.

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.