Middleware redirection issue
Unanswered
Cape lion posted this in #help-forum
Cape lionOP
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
console.log(request.nextUrl.pathname);
let response = NextResponse.next({
request,
});
...
const selectedPlan = request.cookies.get("selectedPlan");
console.log("Selected Plan:", selectedPlan ? selectedPlan.value : "Not set");
if (selectedPlan) {
const url = request.nextUrl.clone();
if (request.nextUrl.hostname === "subdomain.example.com") {
url.hostname = "subdomain.example.com";
} else {
url.hostname = "localhost";
url.port = "3001";
}
url.pathname = selectedPlan.value;
response = NextResponse.redirect(url);
response.cookies.delete("selectedPlan");
return response;
}
return response;
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
Why does the redirection inside
if (selectedPLan) {...}
work when running locally but I get redirected too many times
when accessing it via. a real domain? It seems like the cookie is deleted successfully locally but not when running via. the real domain.
How I set the cookie on
localhost:3000
or example.com
"use server";
import { cookies } from "next/headers";
const createPricingCookie = (planName: string) => {
cookies().set("selectedPlan", planName, {
maxAge: 3600,
path: "/",
domain:
process.env.NODE_ENV === "production" ? "example.com" : "localhost",
sameSite: "strict",
});
};
export default createPricingCookie;