| 2 | import { rootDomain } from '@/lib/utils'; |
| 3 | |
| 4 | function 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 | |
| 43 | export async function middleware(request: NextRequest) { |
| 44 | const { pathname } = request.nextUrl; |