-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathmiddleware.ts
More file actions
64 lines (53 loc) · 2.39 KB
/
Copy pathmiddleware.ts
File metadata and controls
64 lines (53 loc) · 2.39 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// Exclude Next.js internals, public static assets, and global API routes
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
pathname.startsWith('/favicon.ico') ||
pathname.includes('.')
) {
return NextResponse.next()
}
const isMultiCommunity = process.env.NEXT_PUBLIC_FEATURE_MULTI_COMMUNITY === 'true'
const defaultCommunity = 'guildpass-demo'
const pathSegments = pathname.split('/').filter(Boolean)
const firstSegment = pathSegments[0]
const communityRoutes = ['dashboard', 'admin', 'developer', 'events', 'resources', 'upgrade']
if (!isMultiCommunity) {
// ── MULTI-COMMUNITY DISABLED ─────────────────────────────────────────────
// Internal rewrite /dashboard -> /guildpass-demo/dashboard
if (firstSegment && communityRoutes.includes(firstSegment)) {
const rewriteUrl = new URL(`/${defaultCommunity}${pathname}`, request.url)
return NextResponse.rewrite(rewriteUrl)
}
// Redirect /[anyCommunitySlug]/dashboard -> /dashboard
if (firstSegment && !communityRoutes.includes(firstSegment)) {
const secondSegment = pathSegments[1]
if (secondSegment && communityRoutes.includes(secondSegment)) {
const cleanPath = pathname.substring(firstSegment.length + 1)
const redirectUrl = new URL(cleanPath, request.url)
return NextResponse.redirect(redirectUrl)
}
}
} else {
// ── MULTI-COMMUNITY ENABLED ──────────────────────────────────────────────
if (pathname === '/') {
return NextResponse.next()
}
// Redirect /dashboard -> /[lastActiveCommunity]/dashboard
if (firstSegment && communityRoutes.includes(firstSegment)) {
const lastActiveCommunity = request.cookies.get('gp-active-community')?.value || defaultCommunity
const redirectUrl = new URL(`/${lastActiveCommunity}${pathname}`, request.url)
return NextResponse.redirect(redirectUrl)
}
}
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}