forked from wishonia/wishonia
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
109 lines (96 loc) · 2.82 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { NextResponse } from "next/server"
import { getToken } from "next-auth/jwt"
import { withAuth } from "next-auth/middleware"
import { getDomainConfig } from "@/lib/utils/domain-config"
// Define redirects with string literals
const redirects = [
{
source: "/dfda/right-to-trial",
destination: "/dfda/docs/cure-acceleration-act",
permanent: true,
description: "Redirect to new name of the Right to Trial Act",
},
{
source: "/dfda/right-to-trial-act",
destination: "/dfda/docs/cure-acceleration-act",
permanent: true,
description: "Redirect to new name of the Right to Trial Act",
},
{
source: "/dfda/health-savings-sharing",
destination: "/dfda/docs/health-savings-sharing",
permanent: true,
description: "Redirect to health savings sharing documentation",
},
// Add more redirects here
// Make sure to add the source path to the matcher array below 👇
] as const
export default withAuth(
async function middleware(req) {
const token = await getToken({ req })
const isAuth = !!token
const pathname = req.nextUrl.pathname
// Check redirects first
const redirect = redirects.find(r => r.source === pathname)
if (redirect) {
const newUrl = new URL(redirect.destination, req.url)
// Preserve query parameters
const searchParams = new URLSearchParams(req.nextUrl.search)
searchParams.forEach((value, key) => {
newUrl.searchParams.set(key, value)
})
// Preserve hash fragment
if (req.nextUrl.hash) {
newUrl.hash = req.nextUrl.hash
}
return NextResponse.redirect(
newUrl,
redirect.permanent ? { status: 308 } : { status: 307 }
)
}
const isAuthPage =
req.nextUrl.pathname.startsWith("/signin") ||
req.nextUrl.pathname.startsWith("/signup")
const hostname = req.headers.get("host")
const domainConfig = getDomainConfig(hostname)
// Check if we're on the root path
if (req.nextUrl.pathname === "/") {
// Only redirect if defaultHomepage is not root path
if (domainConfig.defaultHomepage !== "/") {
return NextResponse.redirect(
new URL(domainConfig.defaultHomepage, req.url)
)
}
return null
}
// Handle auth pages
if (isAuthPage) {
if (isAuth) {
return NextResponse.redirect(
new URL(domainConfig.afterLoginPath, req.url)
)
}
return null
}
return null
},
{
callbacks: {
async authorized() {
return true
},
},
}
)
// IMPORTANT: When adding new redirects above☝️, add the source path here too 👇
export const config = {
matcher: [
"/",
"/dashboard/:path*",
"/signin",
"/signup",
"/dfda/right-to-trial",
"/dfda/right-to-trial-act",
"/dfda/health-savings-sharing",
],
}