Next.js Discord

Discord Forum

Wildcard subdomain in nextjs shows 404 sometimes.

Unanswered
American Water Spaniel posted this in #help-forum
Open in Discord
American Water SpanielOP
I'm building a multi-tenant portfolio app with subdomain routing on Next.js + Vercel.

Setup:

- ".accifio.xyz" added to Vercel project
- Namecheap has Nameservers pointing to Vercel DNS
- Next.js middleware rewrites
"hello.accifio.xyz" → "/instances/hello"

Problem: Intermittent 403s on subdomains and main domain.

Sometimes works, sometimes doesn't — even the same subdomain works on refresh sometimes and fails other times.

Key observations:

- When 403 occurs, no logs appear in Vercel.

Here is "proxy.ts"

import { NextRequest, NextResponse } from "next/server";

export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;

if (!pathname.startsWith("/dashboard")) {
const domainName = request.headers.get("host");
if (!domainName) {
return NextResponse.next();
}

const subdomain = domainName
// remove after adding domain
.replace("accifio", "")
.replace("vercel", "")
.replace("app", "")
.replace("localhost:3000", "")
.replace("xyz", "")
.replace("www", "")
.replaceAll(".", "");

console.log("SUBDOMAIN", subdomain);

if (
subdomain &&
(pathname.startsWith("/login") || pathname.startsWith("/signup"))
) {
return NextResponse.error();
}

if (subdomain) {
return NextResponse.rewrite(
new URL(/instances/${subdomain}, request.url)
);
}
}

return NextResponse.next();
}

export const config = {
matcher: ["/((?!_next|favicon.ico|api).
)"],
};

Please help me out with this. Thanks in advance.

0 Replies