• Blog
  • Documentation
  • Courses
  • Changelog
  • AI Starters
  • UI Kit
  • FAQ
  • Supamode
    New
  • Pricing

Launch your next SaaS in record time with Makerkit, a React SaaS Boilerplate for Next.js and Supabase.

Makerkit is a product of Makerkit Pte Ltd (registered in the Republic of Singapore)Company Registration No: 202407149CFor support or inquiries, please contact us

About
  • FAQ
  • Contact
  • Verify your Discord
  • Consultation
  • Open Source
  • Become an Affiliate
Product
  • Documentation
  • Blog
  • Changelog
  • UI Blocks
  • Figma UI Kit
  • AI SaaS Starters
License
  • Activate License
  • Upgrade License
  • Invite Member
Legal
  • Terms of License
    • Supabase Clients
    • Server Actions
    • Route Handlers
    • Server Components
    • React Query
    • CSRF Protection
    • Captcha Protection

CSRF Protection for your API Routes

Learn how to protect your API routes against CSRF attacks.

How to protect your API routes against CSRF attacks

Learn how to protect your API routes against CSRF attacks.

1

CSRF Protection

2

Passing the CSRF Token to API Routes

CSRF Protection

By default, all POST, PUT, PATCH and DELETE requests to your API routes are protected against CSRF attacks. This means that you need to send a CSRF token with your requests, otherwise they will be rejected.

There are two exceptions to this rule:

  1. Server Actions: When using Server Actions, protection is built-in and you don't need to worry about it.
  2. API Routes under /api: When the route is under the api path. In this case, the CSRF protection is disabled, since we use this prefix for webhooks or external services that need to access your API.

Passing the CSRF Token to API Routes

When using requests against API Route Handlers, you need to pass the CSRF token with your requests, otherwise the middleware will reject them.

To retrieve the CSRF token, you can use the useGetCsrfToken function from @kit/shared/hooks:

tsx
'use client';
function MyComponent() {
const csrfToken = useGetCsrfToken();
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('/my-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
body: JSON.stringify({ message: 'Hello, world!' }),
});
};
// your component code
}
On this page
  1. CSRF Protection
    1. Passing the CSRF Token to API Routes