-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathredirects.ts
236 lines (216 loc) · 7.85 KB
/
redirects.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/* eslint-disable max-lines */
import { NetlifyConfig } from '@netlify/build'
import { yellowBright } from 'chalk'
import { readJSON } from 'fs-extra'
import { NextConfig } from 'next'
import { PrerenderManifest } from 'next/dist/build'
import { outdent } from 'outdent'
import { join } from 'pathe'
import { HANDLER_FUNCTION_PATH, HIDDEN_PATHS, ODB_FUNCTION_PATH } from '../constants'
import { getMiddleware } from './files'
import { RoutesManifest } from './types'
import {
getApiRewrites,
getPreviewRewrites,
isApiRoute,
redirectsForNextRoute,
redirectsForNextRouteWithData,
routeToDataRoute,
} from './utils'
const matchesMiddleware = (middleware: Array<string>, route: string): boolean =>
middleware?.some((middlewarePath) => route.startsWith(middlewarePath))
const generateLocaleRedirects = ({
i18n,
basePath,
trailingSlash,
}: Pick<NextConfig, 'i18n' | 'basePath' | 'trailingSlash'>): NetlifyConfig['redirects'] => {
const redirects: NetlifyConfig['redirects'] = []
// If the cookie is set, we need to redirect at the origin
redirects.push({
from: `${basePath}/`,
to: HANDLER_FUNCTION_PATH,
status: 200,
force: true,
conditions: {
Cookie: ['NEXT_LOCALE'],
},
})
i18n.locales.forEach((locale) => {
if (locale === i18n.defaultLocale) {
return
}
redirects.push({
from: `${basePath}/`,
to: `${basePath}/${locale}${trailingSlash ? '/' : ''}`,
status: 301,
conditions: {
Language: [locale],
},
force: true,
})
})
return redirects
}
export const generateStaticRedirects = ({
netlifyConfig,
nextConfig: { i18n, basePath },
}: {
netlifyConfig: NetlifyConfig
nextConfig: Pick<NextConfig, 'i18n' | 'basePath'>
}) => {
// Static files are in `static`
netlifyConfig.redirects.push({ from: `${basePath}/_next/static/*`, to: `/static/:splat`, status: 200 })
if (i18n) {
netlifyConfig.redirects.push({ from: `${basePath}/:locale/_next/static/*`, to: `/static/:splat`, status: 200 })
}
}
// eslint-disable-next-line max-lines-per-function
export const generateRedirects = async ({
netlifyConfig,
nextConfig: { i18n, basePath, trailingSlash, appDir },
buildId,
}: {
netlifyConfig: NetlifyConfig
nextConfig: Pick<NextConfig, 'i18n' | 'basePath' | 'trailingSlash' | 'appDir'>
buildId: string
}) => {
const { dynamicRoutes: prerenderedDynamicRoutes, routes: prerenderedStaticRoutes }: PrerenderManifest =
await readJSON(join(netlifyConfig.build.publish, 'prerender-manifest.json'))
const { dynamicRoutes, staticRoutes }: RoutesManifest = await readJSON(
join(netlifyConfig.build.publish, 'routes-manifest.json'),
)
netlifyConfig.redirects.push(
...HIDDEN_PATHS.map((path) => ({
from: `${basePath}${path}`,
to: '/404.html',
status: 404,
force: true,
})),
)
if (i18n && i18n.localeDetection !== false) {
netlifyConfig.redirects.push(...generateLocaleRedirects({ i18n, basePath, trailingSlash }))
}
// This is only used in prod, so dev uses `next dev` directly
netlifyConfig.redirects.push(
// API routes always need to be served from the regular function
...getApiRewrites(basePath),
// Preview mode gets forced to the function, to bypass pre-rendered pages, but static files need to be skipped
...(await getPreviewRewrites({ basePath, appDir })),
)
const middleware = await getMiddleware(netlifyConfig.build.publish)
const routesThatMatchMiddleware = new Set<string>()
const handlerRewrite = (from: string) => ({
from: `${basePath}${from}`,
to: HANDLER_FUNCTION_PATH,
status: 200,
})
// Routes that match middleware need to always use the SSR function
// This generates a rewrite for every middleware in every locale, both with and without a splat
netlifyConfig.redirects.push(
...middleware
.map((route) => {
const unlocalized = [handlerRewrite(`${route}`), handlerRewrite(`${route}/*`)]
if (i18n?.locales?.length > 0) {
const localized = i18n?.locales?.map((locale) => [
handlerRewrite(`/${locale}${route}`),
handlerRewrite(`/${locale}${route}/*`),
handlerRewrite(`/_next/data/${buildId}/${locale}${route}/*`),
])
// With i18n, all data routes are prefixed with the locale, but the HTML also has the unprefixed default
return [...unlocalized, ...localized]
}
return [...unlocalized, handlerRewrite(`/_next/data/${buildId}${route}/*`)]
})
// Flatten the array of arrays. Can't use flatMap as it might be 2 levels deep
.flat(2),
)
const staticRouteEntries = Object.entries(prerenderedStaticRoutes)
const staticRoutePaths = new Set<string>()
// First add all static ISR routes
staticRouteEntries.forEach(([route, { initialRevalidateSeconds }]) => {
if (isApiRoute(route)) {
return
}
staticRoutePaths.add(route)
if (initialRevalidateSeconds === false) {
// These can be ignored, as they're static files handled by the CDN
return
}
// The default locale is served from the root, not the localised path
if (i18n?.defaultLocale && route.startsWith(`/${i18n.defaultLocale}/`)) {
route = route.slice(i18n.defaultLocale.length + 1)
staticRoutePaths.add(route)
if (matchesMiddleware(middleware, route)) {
routesThatMatchMiddleware.add(route)
}
netlifyConfig.redirects.push(
...redirectsForNextRouteWithData({
route,
dataRoute: routeToDataRoute(route, buildId, i18n.defaultLocale),
basePath,
to: ODB_FUNCTION_PATH,
force: true,
}),
)
} else if (matchesMiddleware(middleware, route)) {
// Routes that match middleware can't use the ODB
routesThatMatchMiddleware.add(route)
} else {
// ISR routes use the ODB handler
netlifyConfig.redirects.push(
// No i18n, because the route is already localized
...redirectsForNextRoute({ route, basePath, to: ODB_FUNCTION_PATH, force: true, buildId, i18n: null }),
)
}
})
// Add rewrites for all static SSR routes. This is Next 12+
staticRoutes?.forEach((route) => {
if (staticRoutePaths.has(route.page) || isApiRoute(route.page)) {
// Prerendered static routes are either handled by the CDN or are ISR
return
}
netlifyConfig.redirects.push(
...redirectsForNextRoute({ route: route.page, buildId, basePath, to: HANDLER_FUNCTION_PATH, i18n }),
)
})
// Add rewrites for all dynamic routes (both SSR and ISR)
dynamicRoutes.forEach((route) => {
if (isApiRoute(route.page)) {
return
}
if (route.page in prerenderedDynamicRoutes) {
if (matchesMiddleware(middleware, route.page)) {
routesThatMatchMiddleware.add(route.page)
} else {
netlifyConfig.redirects.push(
...redirectsForNextRoute({ buildId, route: route.page, basePath, to: ODB_FUNCTION_PATH, status: 200, i18n }),
)
}
} else {
// If the route isn't prerendered, it's SSR
netlifyConfig.redirects.push(
...redirectsForNextRoute({ route: route.page, buildId, basePath, to: HANDLER_FUNCTION_PATH, i18n }),
)
}
})
// Final fallback
netlifyConfig.redirects.push({
from: `${basePath}/*`,
to: HANDLER_FUNCTION_PATH,
status: 200,
})
const middlewareMatches = routesThatMatchMiddleware.size
if (middlewareMatches > 0) {
console.log(
yellowBright(outdent`
There ${
middlewareMatches === 1
? `is one statically-generated or ISR route`
: `are ${middlewareMatches} statically-generated or ISR routes`
} that match a middleware function, which means they will always be served from the SSR function and will not use ISR or be served from the CDN.
If this was not intended, ensure that your middleware only matches routes that you intend to use SSR.
`),
)
}
}
/* eslint-enable max-lines */