-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathmiddleware.ts
63 lines (51 loc) · 2.06 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
61
62
63
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { readSiteDomain } from "./utils/actions/sites/read-site-domain";
// Define the routes that require authentication
const isProtectedRoute = createRouteMatcher(["/cms(.*)"]);
// Main middleware function
export default clerkMiddleware(async (auth, req) => {
// Check if the route is protected and enforce authentication if it is
if (isProtectedRoute(req)) auth().protect();
const url = req.nextUrl;
const pathname = url.pathname;
// Get hostname (e.g., 'mike.com', 'test.mike.com')
const hostname = req.headers.get("host");
let currentHost;
if (process.env.NODE_ENV === "production") {
// In production, use the custom base domain from environment variables
const baseDomain = process.env.BASE_DOMAIN;
currentHost = hostname?.replace(`.${baseDomain}`, "");
} else {
// In development, handle localhost case
currentHost = hostname?.replace(`.localhost:3000`, "");
}
// If there's no currentHost, likely accessing the root domain, handle accordingly
if (!currentHost) {
// Continue to the next middleware or serve the root content
return NextResponse.next();
}
// Fetch tenant-specific data based on the subdomain
const response = await readSiteDomain(currentHost);
// Handle the case where no subdomain data is found
if (!response || !response.length) {
// Continue to the next middleware or serve the root content
return NextResponse.next();
}
const site_id = response?.[0]?.site_id;
// Get the tenant's subdomain from the response
const tenantSubdomain = response[0]?.site_subdomain;
if (tenantSubdomain) {
return NextResponse.rewrite(
new URL(`/${site_id}${pathname}`, req.url)
);
}
// Rewrite the URL to the tenant-specific path
return NextResponse.rewrite(
new URL(tenantSubdomain === "/" ? "" : `tsafi.xyz`, req.url)
);
});
// Define which paths the middleware should run for
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};