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
Latest versions of NextJS requires user to have a single middleware on the root folder.
Instead of {root}/pages/_middleware.js
, try {root}/middleware.js
For next 13.0.2 / 13.0.1 if you are using appDir: true ( experimental )
if you want to hit middleware:
put middleware.ts in root project: ( as the same hierarchy as "app" folder, not inside app folder... )
make sure tsconfig has include: [..., "middleware.ts"]
make empty "pages" folder. ( based on issue )
will hit every request:
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest ) { console.log('lol:,!') } export const config = { matcher: '/', }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.