forked from charmverse/app.charmverse.io
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
60 lines (48 loc) · 2.47 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
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
import { isDevEnv } from '@root/config/constants';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { DOMAIN_BLACKLIST } from 'lib/spaces/config';
import { getAppApexDomain } from 'lib/utils/domains/getAppApexDomain';
import { getCustomDomainFromHost } from 'lib/utils/domains/getCustomDomainFromHost';
import { getSpaceDomainFromHost } from 'lib/utils/domains/getSpaceDomainFromHost';
import { getSpaceDomainFromUrlPath } from 'lib/utils/domains/getSpaceDomainFromUrlPath';
// RegExp for public files
const PUBLIC_FILE = /\.(.*)$/; // Files
const FORCE_SUBDOMAINS = process.env.FORCE_SUBDOMAINS === 'true';
export function middleware(req: NextRequest) {
// Clone the URL
const url = req.nextUrl.clone();
// Skip public files
if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;
// Skip api routes
if (url.pathname.includes('/api/')) return;
// Skip public pages
const firstPart = url.pathname.split('/')[1]; // url.pathname starts with a "/", so grab the second element
const isPublicPage = DOMAIN_BLACKLIST.includes(firstPart);
if (isPublicPage) return;
const host = req.headers.get('host');
const customDomain = getCustomDomainFromHost(host);
const subdomain = customDomain ? null : getSpaceDomainFromHost(host);
const spaceDomainFromPath = getSpaceDomainFromUrlPath(url.pathname);
if (FORCE_SUBDOMAINS && !subdomain && !customDomain && spaceDomainFromPath) {
// We are on url without subdomain AND domain in path - redirect to subdomain url
const subdomainHost = `${spaceDomainFromPath}.${getAppApexDomain()}`;
const pathWithoutSpaceDomain = url.pathname.replace(`/${spaceDomainFromPath}`, '') || '/';
const port = isDevEnv ? `:${url.port}` : '';
const baseUrl = `${url.protocol}//${subdomainHost}${port}`;
const redirectUrl = new URL(pathWithoutSpaceDomain, baseUrl);
return NextResponse.redirect(redirectUrl);
}
if (subdomain && spaceDomainFromPath && spaceDomainFromPath === subdomain) {
// We are on url with subdomain AND domain in path - redirect to url without domain in path
const pathWithoutSpaceDomain = url.pathname.replace(`/${spaceDomainFromPath}`, '') || '/';
url.pathname = pathWithoutSpaceDomain;
return NextResponse.redirect(url);
}
const rewriteDomain = customDomain || subdomain;
if (rewriteDomain) {
// Subdomain available, rewriting
url.pathname = `/${rewriteDomain}${url.pathname}`;
return NextResponse.rewrite(url);
}
}