-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathredirects.ts
323 lines (295 loc) · 10.2 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/* eslint-disable max-lines */
import type { NetlifyConfig } from '@netlify/build'
import { yellowBright } from 'chalk'
import { readJSON } from 'fs-extra'
import type { NextConfig } from 'next'
import type { PrerenderManifest, SsgRoute } 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 { ApiRouteConfig } from './functions'
import { RoutesManifest } from './types'
import {
getApiRewrites,
getPreviewRewrites,
is404Route,
isApiRoute,
redirectsForNextRoute,
redirectsForNextRouteWithData,
routeToDataRoute,
} from './utils'
const matchesMiddleware = (middleware: Array<string>, route: string): boolean =>
middleware.some((middlewarePath) => route.startsWith(middlewarePath))
const generateHiddenPathRedirects = ({ basePath }: Pick<NextConfig, 'basePath'>): NetlifyConfig['redirects'] =>
HIDDEN_PATHS.map((path) => ({
from: `${basePath}${path}`,
to: '/404.html',
status: 404,
force: true,
}))
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 })
}
}
/**
* 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
*/
const generateMiddlewareRewrites = ({ basePath, middleware, i18n, buildId }) => {
const handlerRewrite = (from: string) => ({
from: `${basePath}${from}`,
to: HANDLER_FUNCTION_PATH,
status: 200,
})
return (
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 generateStaticIsrRewrites = ({
staticRouteEntries,
basePath,
i18n,
buildId,
middleware,
}: {
staticRouteEntries: Array<[string, SsgRoute]>
basePath: string
i18n: NextConfig['i18n']
buildId: string
middleware: Array<string>
}): {
staticRoutePaths: Set<string>
staticIsrRoutesThatMatchMiddleware: Array<string>
staticIsrRewrites: NetlifyConfig['redirects']
} => {
const staticIsrRoutesThatMatchMiddleware: Array<string> = []
const staticRoutePaths = new Set<string>()
const staticIsrRewrites: NetlifyConfig['redirects'] = []
staticRouteEntries.forEach(([route, { initialRevalidateSeconds }]) => {
if (isApiRoute(route) || is404Route(route, i18n)) {
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)) {
staticIsrRoutesThatMatchMiddleware.push(route)
}
staticIsrRewrites.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
staticIsrRoutesThatMatchMiddleware.push(route)
} else {
// ISR routes use the ODB handler
staticIsrRewrites.push(
// No i18n, because the route is already localized
...redirectsForNextRoute({ route, basePath, to: ODB_FUNCTION_PATH, force: true, buildId, i18n: null }),
)
}
})
return {
staticRoutePaths,
staticIsrRoutesThatMatchMiddleware,
staticIsrRewrites,
}
}
/**
* Generate rewrites for all dynamic routes
*/
const generateDynamicRewrites = ({
dynamicRoutes,
prerenderedDynamicRoutes,
middleware,
basePath,
buildId,
i18n,
}: {
dynamicRoutes: RoutesManifest['dynamicRoutes']
prerenderedDynamicRoutes: PrerenderManifest['dynamicRoutes']
basePath: string
i18n: NextConfig['i18n']
buildId: string
middleware: Array<string>
}): {
dynamicRoutesThatMatchMiddleware: Array<string>
dynamicRewrites: NetlifyConfig['redirects']
} => {
const dynamicRewrites: NetlifyConfig['redirects'] = []
const dynamicRoutesThatMatchMiddleware: Array<string> = []
dynamicRoutes.forEach((route) => {
if (isApiRoute(route.page) || is404Route(route.page, i18n)) {
return
}
if (route.page in prerenderedDynamicRoutes) {
if (matchesMiddleware(middleware, route.page)) {
dynamicRoutesThatMatchMiddleware.push(route.page)
} else {
dynamicRewrites.push(
...redirectsForNextRoute({ buildId, route: route.page, basePath, to: ODB_FUNCTION_PATH, status: 200, i18n }),
)
}
} else {
// If the route isn't prerendered, it's SSR
dynamicRewrites.push(
...redirectsForNextRoute({ route: route.page, buildId, basePath, to: HANDLER_FUNCTION_PATH, i18n }),
)
}
})
return {
dynamicRoutesThatMatchMiddleware,
dynamicRewrites,
}
}
export const generateRedirects = async ({
netlifyConfig,
nextConfig: { i18n, basePath, trailingSlash, appDir },
buildId,
apiRoutes,
}: {
netlifyConfig: NetlifyConfig
nextConfig: Pick<NextConfig, 'i18n' | 'basePath' | 'trailingSlash' | 'appDir'>
buildId: string
apiRoutes: Array<ApiRouteConfig>
}) => {
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(...generateHiddenPathRedirects({ basePath }))
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, apiRoutes),
// 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)
netlifyConfig.redirects.push(...generateMiddlewareRewrites({ basePath, i18n, middleware, buildId }))
const staticRouteEntries = Object.entries(prerenderedStaticRoutes)
const routesThatMatchMiddleware: Array<string> = []
const { staticRoutePaths, staticIsrRewrites, staticIsrRoutesThatMatchMiddleware } = generateStaticIsrRewrites({
staticRouteEntries,
basePath,
i18n,
buildId,
middleware,
})
routesThatMatchMiddleware.push(...staticIsrRoutesThatMatchMiddleware)
netlifyConfig.redirects.push(...staticIsrRewrites)
// Add rewrites for all static SSR routes. This is Next 12+
staticRoutes?.forEach((route) => {
if (staticRoutePaths.has(route.page) || isApiRoute(route.page) || is404Route(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)
const { dynamicRewrites, dynamicRoutesThatMatchMiddleware } = generateDynamicRewrites({
dynamicRoutes,
prerenderedDynamicRoutes,
middleware,
basePath,
buildId,
i18n,
})
netlifyConfig.redirects.push(...dynamicRewrites)
routesThatMatchMiddleware.push(...dynamicRoutesThatMatchMiddleware)
// Final fallback
netlifyConfig.redirects.push({
from: `${basePath}/*`,
to: HANDLER_FUNCTION_PATH,
status: 200,
})
const middlewareMatches = new Set(routesThatMatchMiddleware).size
if (middlewareMatches > 0) {
console.log(
yellowBright(outdent`
There ${
middlewareMatches === 1
? `is one statically-generated or ISR route that matches`
: `are ${middlewareMatches} statically-generated or ISR routes that match`
} a middleware function. Matched routes 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 */