-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
33 lines (31 loc) · 1.14 KB
/
middleware.ts
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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
export const getValidSubdomain = (host?: string | null) => {
let subdomain: string | null = null;
if (!host && typeof window !== 'undefined') {
host = window.location.host;
}
if(host === 'localhost:3000' || host === 'heliup.xyz') {
return;
}
if (host && host.includes('.')) {
const parts = host.split('.');
const candidate = parts[0];
if (candidate && parts.length > 1 && !['www', 'localhost'].includes(candidate)) {
subdomain = candidate;
}
}
return subdomain;
};
export async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;
const host = req.headers.get('host');
const subdomain = getValidSubdomain(host);
if (subdomain) {
console.log(`>>> Rewriting: ${url.pathname} to /view-organization/${subdomain}${url.pathname}`);
url.pathname = `/view-organization/${subdomain}${url.pathname}`;
}
return NextResponse.rewrite(url);
}