Middleware plays a crucial role in intercepting every request. Typically, you wouldn't want it to return JSON, as it's not an API endpoint. Avoid using res
with the NextApiResponse
type, which is unsuitable for middleware.
Instead, consider returning the request or redirecting it elsewhere if validation fails. Here's an example from Next.js Docs:
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { return NextResponse.redirect(new URL('/home', request.url)) }
Remember that middleware is not a standard serverless function and operates at lightning speed. Keep your code concise within it.
Returning a response with a body in middleware is possible:
return NextResponse.json( { success: false, message: 'authentication failed' }, { status: 401 } )
Refer to Next.js Docs for details: https://nextjs.org/docs/app/building-your-application/routing/middleware#producing-a-response