MCPcopy Index your code
hub / github.com/vercel/platforms / extractSubdomain

Function extractSubdomain

middleware.ts:4–41  ·  view source on GitHub ↗
(request: NextRequest)

Source from the content-addressed store, hash-verified

2import { rootDomain } from '@/lib/utils';
3
4function extractSubdomain(request: NextRequest): string | null {
5 const url = request.url;
6 const host = request.headers.get('host') || '';
7 const hostname = host.split(':')[0];
8
9 // Local development environment
10 if (url.includes('localhost') || url.includes('127.0.0.1')) {
11 // Try to extract subdomain from the full URL
12 const fullUrlMatch = url.match(/http:\/\/([^.]+)\.localhost/);
13 if (fullUrlMatch && fullUrlMatch[1]) {
14 return fullUrlMatch[1];
15 }
16
17 // Fallback to host header approach
18 if (hostname.includes('.localhost')) {
19 return hostname.split('.')[0];
20 }
21
22 return null;
23 }
24
25 // Production environment
26 const rootDomainFormatted = rootDomain.split(':')[0];
27
28 // Handle preview deployment URLs (tenant---branch-name.vercel.app)
29 if (hostname.includes('---') && hostname.endsWith('.vercel.app')) {
30 const parts = hostname.split('---');
31 return parts.length > 0 ? parts[0] : null;
32 }
33
34 // Regular subdomain detection
35 const isSubdomain =
36 hostname !== rootDomainFormatted &&
37 hostname !== `www.${rootDomainFormatted}` &&
38 hostname.endsWith(`.${rootDomainFormatted}`);
39
40 return isSubdomain ? hostname.replace(`.${rootDomainFormatted}`, '') : null;
41}
42
43export async function middleware(request: NextRequest) {
44 const { pathname } = request.nextUrl;

Callers 1

middlewareFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected