Skip to main content
Kit provides automatic CSRF (Cross-Site Request Forgery) protection for all state-changing requests. This prevents malicious websites from executing actions on behalf of authenticated users.

Overview

CSRF protection in Kit:
  • Automatically validates all POST, PUT, PATCH, and DELETE requests
  • Generates per-session tokens for maximum security
  • Integrates with Inertia.js via meta tag and axios interceptor
  • Uses constant-time comparison to prevent timing attacks

How It Works

  1. When a session is created, Kit generates a cryptographically secure CSRF token
  2. This token is embedded in the HTML via a <meta> tag
  3. The frontend automatically includes the token in request headers
  4. Kit validates the token on every state-changing request
  5. Invalid tokens result in a 419 “Page Expired” response

Frontend Integration

Automatic Setup

Kit projects are pre-configured with CSRF protection. The generated main.tsx sets up axios to automatically include the CSRF token:

Inertia Forms

When using Inertia’s useForm hook, CSRF tokens are automatically included:

Manual Requests

For manual fetch or axios requests, include the token from the meta tag:

Backend Configuration

CSRF middleware is automatically registered in bootstrap.rs:

Excluding Routes

Some routes may need to bypass CSRF protection (e.g., webhook endpoints). You can exclude specific routes:

CSRF Helper Functions

Kit provides helper functions for working with CSRF tokens:

Error Handling

When CSRF validation fails, Kit returns a 419 status code with a “CSRF token mismatch” message. You can customize this behavior:

Security Considerations

Kit’s CSRF implementation follows security best practices:
  • Per-session tokens: Each session has its own unique CSRF token
  • Secure generation: Tokens are generated using cryptographically secure random bytes
  • Constant-time comparison: Token validation uses constant-time comparison to prevent timing attacks
  • Token regeneration: Tokens are regenerated on logout to prevent session fixation
  • SameSite cookies: Combined with SameSite=Lax cookies for defense in depth

Testing

When writing tests, you’ll need to include CSRF tokens. Kit’s testing utilities handle this automatically:

Inertia-Specific Behavior

When using Inertia.js, CSRF handling has some special considerations:
  • The CSRF token is injected into the HTML page via a <meta> tag
  • Inertia automatically reads this token and includes it in XHR requests
  • For 419 responses, Inertia can be configured to handle the redirect: