-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmiddleware.ts
46 lines (41 loc) · 1.1 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
import { NextResponse, NextRequest } from 'next/server'
import { getPersonalizedURL } from '@builder.io/personalization-utils/next'
// Any page not included in here needs to handle the personalization rewrite
const noPersonalizePaths = [
'/api',
'/_next',
'/search',
'/orders',
'/profile',
'/search',
'/wishlist',
'/favicon',
]
const shouldRewrite = (pathname: string) => {
for (const path of noPersonalizePaths) {
if (pathname.startsWith(path)) {
return false
}
}
// don't rewrite for asset requests (has a file extension)
return !pathname.includes('.')
}
export default function middleware(request: NextRequest) {
if (shouldRewrite(request.nextUrl.pathname)) {
const sourcePath = request.nextUrl.pathname
const rewrite = getPersonalizedURL(request, {
cookiesPrefix: 'personalization',
})
// Log the rewrite that occured
console.info(
'rewrote',
sourcePath,
'to',
rewrite.pathname,
'with params',
atob(rewrite.pathname.split('/').at(-1)!)
)
return NextResponse.rewrite(rewrite)
}
return NextResponse.next()
}