-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
68 lines (57 loc) · 2.17 KB
/
middleware.ts
File metadata and controls
68 lines (57 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { clerkMiddleware } from '@clerk/nextjs/server';
import { NextRequest, NextResponse } from 'next/server';
import { ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const protocol =
process.env.NODE_ENV === 'production' ? 'https' : 'http';
export const rootDomain =
process.env.NEXT_PUBLIC_ROOT_DOMAIN || 'localhost:3000';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
function extractSubdomain(request: NextRequest): string | null {
const url = request.url;
const host = request.headers.get('host') || '';
const hostname = host.split(':')[0];
// Local development environment
if (url.includes('localhost') || url.includes('127.0.0.1')) {
// Try to extract subdomain from the full URL
const fullUrlMatch = url.match(/http:\/\/([^.]+)\.localhost/);
if (fullUrlMatch && fullUrlMatch[1]) {
return fullUrlMatch[1];
}
// Fallback to host header approach
if (hostname.includes('.localhost')) {
return hostname.split('.')[0];
}
return null;
}
// Production environment
const rootDomainFormatted = rootDomain.split(':')[0];
// Handle preview deployment URLs (tenant---branch-name.vercel.app)
if (hostname.includes('---') && hostname.endsWith('.vercel.app')) {
const parts = hostname.split('---');
return parts.length > 0 ? parts[0] : null;
}
// Regular subdomain detection
const isSubdomain =
hostname !== rootDomainFormatted &&
hostname !== `www.${rootDomainFormatted}` &&
hostname.endsWith(`.${rootDomainFormatted}`);
return isSubdomain ? hostname.replace(`.${rootDomainFormatted}`, '') : null;
}
export default clerkMiddleware((auth,request)=>{
const { pathname } = request.nextUrl;
const subdomain = extractSubdomain(request);
if (subdomain) {
return NextResponse.rewrite(new URL(`/s/${subdomain}`, request.url));
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
};