I understand! You want to allow access to normal app routes like /login, /register etc. on the main domain, while still handling subdomain routing. Here's the refactored middleware:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Local tenant data cache or fallback
const TENANT_CACHE = new Map<string, any>();
// Define your main app routes that should be accessible on the root domain
const MAIN_APP_ROUTES = [
'/login',
'/register',
'/signup',
'/auth',
'/dashboard',
'/profile',
'/settings',
'/pricing',
'/about',
'/contact',
'/terms',
'/privacy',
'/help',
'/docs',
// Add more routes as needed
];
async function identifyTenant(request: NextRequest) {
const hostname = request.headers.get("host") || "";
const currentHost = hostname.split(":")[0];
const subdomain = currentHost.split(".")[0];
// Check cache first
if (TENANT_CACHE.has(subdomain)) {
return TENANT_CACHE.get(subdomain);
}
try {
// Try to fetch from external API first
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL || 'https://your-api-domain.com'}/api/tenant/info?subdomain=${subdomain}`,
{
headers: {
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(5000)
}
);
if (response.ok) {
const data = await response.json();
const tenant = data.data;
if (tenant) {
TENANT_CACHE.set(subdomain, tenant);
}
return tenant;
}
} catch (error) {
console.warn(`Failed to fetch tenant data for ${subdomain}:`, error);
}
// Fallback: Check against predefined tenant list
const KNOWN_TENANTS = [
{ subdomain: 'demo', name: 'Demo Tenant' },
{ subdomain: 'test', name: 'Test Tenant' },
// Add your known tenants here
];
const fallbackTenant = KNOWN_TENANTS.find(t => t.subdomain === subdomain);
if (fallbackTenant) {
TENANT_CACHE.set(subdomain, fallbackTenant);
return fallbackTenant;
}
return null;
}
function isMainAppRoute(pathname: string): boolean {
return MAIN_APP_ROUTES.some(route =>
pathname === route || pathname.startsWith(`${route}/`)
);
}
export async function middleware(request: NextRequest) {
const url = request.nextUrl;
const hostname = request.headers.get("host") || "";
const currentHost = hostname.split(":")[0];
const subdomain = currentHost.split(".")[0];
const pathname = url.pathname;
// Get root domain from environment or extract from hostname
const rootDomain = process.env.NEXT_PUBLIC_ROOT_DOMAIN ||
currentHost.split('.').slice(-2).join('.');
// Check if this is the main domain (no subdomain or www)
const isMainDomain = currentHost === rootDomain ||
subdomain === 'www' ||
subdomain === currentHost;
// If it's the main domain and accessing main app routes, allow it
if (isMainDomain && isMainAppRoute(pathname)) {
return NextResponse.next();
}
// If it's the main domain but not a main app route, handle accordingly
if (isMainDomain) {
// You can either:
// 1. Allow all routes on main domain
return NextResponse.next();
// 2. Or redirect unknown routes to a specific page
// return NextResponse.redirect(new URL('/login', request.url));
}
// Exclude system routes and API routes
const excludedSubdomains = ["app", "api", "admin"];
if (excludedSubdomains.includes(subdomain)) {
return NextResponse.next();
}
// Handle subdomain routing
const tenant = await identifyTenant(request);
// For non-existent tenants
if (!tenant) {
// Redirect to main domain login
const mainDomain = process.env.NEXT_PUBLIC_ROOT_DOMAIN || 'localhost:3000';
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
return NextResponse.redirect(`${protocol}://${mainDomain}/login`);
}
// Rewrite the URL to include the subdomain as a path parameter
url.pathname = `/${subdomain}${url.pathname}`;
return NextResponse.rewrite(url);
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - _vercel (Vercel internals)
*/
"/((?!api|_next/static|_next/image|favicon.ico|_vercel).*)",
],
};