Middleware redirect not working as intended
Unanswered
Kuchi posted this in #help-forum
KuchiOP
if (provinceCookie) {
const originalPath = req.url.split("?")[0]; // Extract pathname and exclude query parameters
console.log("originalPath", originalPath); // https://localhost:3000/AB
if (provinceCookie === "AB") {
const redirectedPath = `/AB${originalPath}`;
return NextResponse.redirect(redirectedPath);
}
if (provinceCookie === "BC") {
// Updated regular expression to match "/AB" or "/AB/" at the start of the pathname
const regex = /\/AB\/?/;
console.log("regex.test(originalPath)", regex.test(originalPath)); // this should now be true for "/AB/somePage" and "/AB/"
if (regex.test(originalPath)) {
const redirectedPath = originalPath.replace(/\/AB\/?/, "/"); // Replace "/AB/" or "/AB" with "/"
return NextResponse.redirect(redirectedPath);
}
}
}so the routes I'm trying to redirect to are localhost:3000/ if provinceCookie is set to BC
and localhost:3000/AB if provinceCookie is set to AB.
Also want to preserve route paths after so if its localhost:3000/somePage, and user switches to the Alberta location, setting the provinceCookie to AB it would be localhost:3000/AB/somePage
and /AB/ would be removed if the user selects British Columbia and sets the provinceCookie to BC