Bug using middleware.ts for a multi-tenant app
Answered
Himalayan posted this in #help-forum
HimalayanOP
I am looking for a solution to a problem I have since yesterday, I have to debug this middleware used to transform incoming request with a subdomain (like tenant.masterdomain.com) into an app router compatible route (masterdomain.com/tenant) but it just gives me 308 errors for some reasons and trying different middleware doesn't solve the problem, here it is :
I also attached a picture of the current app router routes, anyone has an idea of what's going wrong ?
export default async function middleware(req: NextRequest, res: NextResponse) {
const { nextUrl: url } = req;
const hostname = req.headers.get("host")!;
console.log("hostname : ", hostname);
const searchParams = url.searchParams.toString();
const path = `${url.pathname}${searchParams ? `?${searchParams}` : ""}`;
console.log("path : ", path);
const subdomain = extractSubdomain(hostname);
console.log("subdomain : ", subdomain);
console.log("req url : ", req.url);
const urlDomain = new URL(`${subdomain}${path}`, req.url);
console.log("urlDomain : ", urlDomain.href);
console.log("urlDomain + reqUrl : ", urlDomain.href, req.url);
if (urlDomain.href === req.url) {
return NextResponse.next(); // Prevent unnecessary rewrite
}
return NextResponse.rewrite(urlDomain);
}I also attached a picture of the current app router routes, anyone has an idea of what's going wrong ?
Answered by Himalayan
Solution : the app router was badly configured and needed to get rid of the underscore before subdomain to get the result I expected
1 Reply
HimalayanOP
Solution : the app router was badly configured and needed to get rid of the underscore before subdomain to get the result I expected
Answer