next.js

NextJS middleware does not seem to be triggered


I have the middleware.js file within /myproject/pages/middleware.js:

export function middleware(request) {
  console.log(1)
  return NextResponse.redirect(new URL('/', request.url))
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: ['/test'],
}

Now what I expect is when i go to the page /test then it should redirect me to /. However nothing happens and I see my standard 404 page.

Any ideas why?

NextJs version: 12.2.2


Solution

  • Latest versions of NextJS requires the user to have a single middleware file on the same level as the pages folder.

    Instead of {root}/pages/middleware.js, try {root}/middleware.js
    and if you have a src folder try {root}/src/middleware.js.