ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Developer

CSRF Prevention

Prevent Cross-Site Request Forgery with token-based protection, SameSite cookies, and Origin checks.

2 snippets Intermediate
CSRFtokenSameSiteOrigin headerdouble submit

What you'll learn

  • CSRF token (double-submit cookie)
  • Origin / Referer validation

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. Review the code comments for important security notes and caveats.
Code Snippets

Copy-paste code snippets

2 ready-to-use snippets for csrf prevention. Click copy and paste into your project.

CSRF token (double-submit cookie)
                // Generate CSRF token
function generateCSRFToken() {
  return crypto.randomUUID();
}

// Set as cookie (not HttpOnly — JS needs to read it)
res.cookie('csrf-token', token, {
  secure: true,
  sameSite: 'strict',
  path: '/',
});

// Client sends token in header
fetch('/api/action', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': getCookie('csrf-token'),
  },
  body: JSON.stringify(data),
});

// Server compares cookie token vs header token
              
Origin / Referer validation
                function validateOrigin(req) {
  const origin = req.headers.origin;
  const referer = req.headers.referer;
  const allowed = ['https://example.com'];

  if (origin && !allowed.includes(origin))
    return false;

  if (!origin && referer) {
    const refOrigin = new URL(referer).origin;
    if (!allowed.includes(refOrigin))
      return false;
  }

  // Reject if neither present
  if (!origin && !referer)
    return false;

  return true;
}
              
100% Free · No signup · No cost

Generate something unguessable right now

148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site