Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Created March 29, 2024 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsjavi/1665a58263bf42760791cae164e0b2af to your computer and use it in GitHub Desktop.
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
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