I would like to redirect users in my middleware. However, Next.js middleware behaves inconsistently. If I place the middleware in /pages/_middleware.ts the redirect will work. If I place it in /pages/api/_middleware.ts the redirect will not work.
// /pages/_middleware.ts
export function middleware() {
return NextResponse.redirect(
`http://example.com`
);
}
// /pages/api/_middleware.ts
export function middleware() {
return NextResponse.redirect(
`http://example.com`
);
}
Update:
I did a test on a fresh project for /api. The user will be redirected if they direst navigate to the route /api/hello. However, when the request is made via code redirect will fail. I would like to add a redirect guard at the api level but this doesn't seem possible with _middleware.
fetch(
`/api/hello`,
{
credentials: 'same-origin',
method: 'POST',
}
);