Confusion on middleware redirect function
Unanswered
Dogue Brasileiro posted this in #help-forum
Dogue BrasileiroOP
I am using the platforms middleware code in my next app
This is my code:
This is my code:
if (hostname == `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
const session = req.cookies.get('user_token');
if (!session && path !== "/login" && path !== "/signup") {
return NextResponse.redirect(new URL("/login", req.url));
} else if (session && (path == "/login" || path == "/signup")) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.rewrite(
new URL(`/app${path === "/" ? "" : path}`, req.url),
);
}
// special case for `vercel.pub` domain
if (hostname === "vercel.pub") {
return NextResponse.redirect(
"https://vercel.com/blog/platforms-starter-kit",
);
}
// rewrite root application to `/home` folder
if (
hostname === "localhost:3000" ||
hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
) {
return NextResponse.rewrite(
new URL(`/home${path === "/" ? "" : path}`, req.url),
);
}
// rewrite everything else to `/[domain]/[slug] dynamic route
return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));7 Replies
Dogue BrasileiroOP
I load the page http://app.localhost:3000/signup in the browser. It hit this line in the middleware since session is not null. The redirect url is http://localhost:3000/dashboard
but it is redirecting to http://app.localhost:3000/dashboard regardless in the browser. why?
but it is redirecting to http://app.localhost:3000/dashboard regardless in the browser. why?
Dogue BrasileiroOP
so no one knows how this works?
Lapland Longspur
Hey, in one place you have “return NextResponse.rewrite(
new URL(
);†could it be that ?
You have “/appâ€. Could that be it ?
new URL(
/app${path === "/" ? "" : path}, req.url),);†could it be that ?
You have “/appâ€. Could that be it ?
@Lapland Longspur Hey, in one place you have “return NextResponse.rewrite(
new URL(`/app${path === "/" ? "" : path}`, req.url),
);†could it be that ?
You have “/appâ€. Could that be it ?
Dogue BrasileiroOP
no its like when i navigate to
http://app.localhost:3000/dashboard, i am getting the req.url as http://localhost:3000/dashboard inside the middlewarePeterbald
Hi when you load the page /signup, there are already session. So it must be redirect to /dashboard.
It is right thing. You wrote the code like this.
It is right thing. You wrote the code like this.
Please consider the highlighted conditional statement