-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (40 loc) · 1.8 KB
/
Copy pathmiddleware.ts
File metadata and controls
46 lines (40 loc) · 1.8 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
import { NextRequest, NextResponse } from 'next/server'
import { DEFAULT_TENANT_ID, getSubdomainFromHost, isValidTenantId } from './lib/makeswift/tenants'
export function middleware(request: NextRequest) {
const host = request.headers.get('host') ?? ''
const url = request.nextUrl.clone()
// 1. Prefer the subdomain. This is how the Visual Builder connects, because a
// Makeswift host URL cannot contain a path (it is an origin only). The
// builder loads e.g. "siteA.localhost:3000", and we resolve the tenant
// from that subdomain.
const subdomain = getSubdomainFromHost(host)
if (subdomain != null && isValidTenantId(subdomain)) {
// Avoid double-prefixing when the path already starts with the tenant
// (e.g. a hand-typed "siteA.localhost:3000/siteA").
if (url.pathname !== `/${subdomain}` && !url.pathname.startsWith(`/${subdomain}/`)) {
url.pathname = `/${subdomain}${url.pathname}`
}
return NextResponse.rewrite(url)
}
// 2. Fall back to path-based routing for public viewing: if the first path
// segment is already a valid tenant (e.g. "/siteA/products"), let it
// through unchanged so the catch-all route reads the tenant from there.
const firstPathSegment = url.pathname.split('/').at(1) ?? null
if (firstPathSegment != null && isValidTenantId(firstPathSegment)) {
return NextResponse.next()
}
// 3. No tenant in the host or the path -> default tenant.
url.pathname = `/${DEFAULT_TENANT_ID}${url.pathname}`
return NextResponse.rewrite(url)
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}