Created
March 29, 2024 02:54
-
-
Save itsjavi/1665a58263bf42760791cae164e0b2af to your computer and use it in GitHub Desktop.
CSRF protection guard function for API routes in Next.js App Router, with Lucia Auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { verifyRequestOrigin } from 'lucia' | |
import { NextResponse } from 'next/server' | |
type RouteHandler = (request: Request) => NextResponse | Response | |
// Wrap your Next.js Route Handler with this middleware to protect against CSRF attacks | |
// NOTE: this won't protect against CSRF attacks on Server Actions and Server Components, | |
// so it's better to configure this in middleware.ts | |
export function csrfGuard(guardedFn: RouteHandler): RouteHandler { | |
return (request: Request, ...context) => { | |
const isServerComponentRequest = request.headers.get('Accept') === 'text/x-component' | |
if (['GET', 'HEAD', 'OPTIONS'].includes(request.method) && !isServerComponentRequest) { | |
return guardedFn(request, ...context) | |
} | |
// Only allow non-readOnly requests from the same origin | |
const originHeader = request.headers.get('Origin') | |
const hostHeader = request.headers.get('Host') || request.headers.get('X-Forwarded-Host') | |
if (!originHeader || !hostHeader || !verifyRequestOrigin(originHeader, [hostHeader])) { | |
return new NextResponse(null, { | |
status: 403, | |
}) | |
} | |
return guardedFn(request, ...context) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment