-
Notifications
You must be signed in to change notification settings - Fork 73
/
redirects.js
81 lines (65 loc) · 2.31 KB
/
redirects.js
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
// Note: This will not work in dev mode and will throw an error upon startup
// This is because the Payload APIs are not yet running when the Next.js server starts
// This is not a problem in production as Payload is booted up before building Next.js
// For this reason the errors can be silently ignored in dev mode
module.exports = async () => {
const internetExplorerRedirect = {
destination: '/ie-incompatible.html',
has: [
{
key: 'user-agent',
type: 'header',
value: '(.*Trident.*)', // all ie browsers
},
],
permanent: false,
source: '/:path((?!ie-incompatible.html$).*)', // all pages except the incompatibility page
}
try {
const redirectsRes = await fetch(
`${process.env.NEXT_PUBLIC_SERVER_URL}/api/redirects?limit=1000&depth=1`,
)
const redirectsData = await redirectsRes.json()
const { docs } = redirectsData
let dynamicRedirects = []
if (docs) {
docs.forEach((doc) => {
const { from, to: { reference, type, url } = {} } = doc
let source = from
.replace(process.env.NEXT_PUBLIC_SERVER_URL, '')
.split('?')[0]
.toLowerCase()
if (source.endsWith('/')) source = source.slice(0, -1) // a trailing slash will break this redirect
let destination = '/'
if (type === 'custom' && url) {
destination = url.replace(process.env.NEXT_PUBLIC_SERVER_URL, '')
}
if (
type === 'reference' &&
typeof reference.value === 'object' &&
reference?.value?._status === 'published'
) {
destination = `${process.env.NEXT_PUBLIC_SERVER_URL}/${
reference.relationTo !== 'pages' ? `${reference.relationTo}/` : ''
}${reference.value.slug}`
}
const redirect = {
destination,
permanent: true,
source,
}
if (source.startsWith('/') && destination && source !== destination) {
return dynamicRedirects.push(redirect)
}
return
})
}
const redirects = [internetExplorerRedirect, ...dynamicRedirects]
return redirects
} catch (error) {
if (process.env.NODE_ENV === 'production') {
console.error(`Error configuring redirects: ${error}`) // eslint-disable-line no-console
}
return []
}
}