Notification texts go here Contact Us Buy Now!

Middleware is not called in Next.js Project

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

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.