Nextjs middleware being ignored

Hey, this is driving me crazy, using next, why I'm not being redirected to "/pending" by the middleware when pushed to "/dashboard" from a different (login) route using useRouter push login.tsx route
function goToDashboard(){
router.push('/dashboard');
}
return <button onClick={goToDashboard}>go</button>
function goToDashboard(){
router.push('/dashboard');
}
return <button onClick={goToDashboard}>go</button>
root middlware middleware.ts
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const { pathname } = req.nextUrl
const status = "pending"
const user = true
if (pathname.startsWith("/dashboard")) {
if (!user) {
return redirect("/login", req);
}
if (status === "pending") {
return redirect("/pending", req);
}
}
return res
}

export const config = {
matcher: [
"/dashboard",
"/login",
"/pending",
],
};
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const { pathname } = req.nextUrl
const status = "pending"
const user = true
if (pathname.startsWith("/dashboard")) {
if (!user) {
return redirect("/login", req);
}
if (status === "pending") {
return redirect("/pending", req);
}
}
return res
}

export const config = {
matcher: [
"/dashboard",
"/login",
"/pending",
],
};
3 Replies
teos
teos16mo ago
Where does redirect(url, req) comes from ? I believe you should return NextResponse.redirect(url) instead
werz0xff
werz0xffOP16mo ago
it is custom function
function redirect(url: string, req: NextRequest) {
return NextResponse.redirect(new URL(url, req.url));
}
function redirect(url: string, req: NextRequest) {
return NextResponse.redirect(new URL(url, req.url));
}
i think its a prefetch thing, because if I do a full refresh on the dashboard route it works fine
teos
teos16mo ago
Yeah, your example works fine on my end. Maybe try adding some logs to make sure the url is what you expect, and that redirect() is actually called. I don't see anything wrong with the code...
Want results from more Discord servers?
Add your server