Skip to content

fix: support non-prerendered dynamic routes with fallback false #1541

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
61fe286
fix: bypass handler function for non-prerendered dynamic routes with …
orinokai Aug 16, 2022
b7a6872
fix: remove catch all handler redirect to support fallback false and …
orinokai Aug 16, 2022
b8e1950
feat: support custom 404 pages in all locales
orinokai Aug 16, 2022
0996adc
feat: add custom 404 handling for static routes
orinokai Aug 31, 2022
52ee02c
chore: refactor hidden path redirects
orinokai Aug 31, 2022
18c2333
feat: add support for isr 404 pages
orinokai Sep 2, 2022
8a361ae
feat: swap cache patch for forced manual revalidate
orinokai Sep 2, 2022
2073b27
chore: add docs for patches
orinokai Sep 2, 2022
046d375
feat: use revalidate header instead of server patch
orinokai Sep 6, 2022
69a4146
test: add dynamic routing and fallback tests
orinokai Sep 6, 2022
2b67d08
chore: fix eslint error
orinokai Sep 6, 2022
39d6ea9
fix: remove fallback: true handling until runtime fix lands
orinokai Sep 6, 2022
3f5e675
test: update tests while fallback:true works like fallback:blocking
orinokai Sep 6, 2022
5806400
test: fix jest tests
orinokai Sep 6, 2022
81d2d80
test: simplify cypress test names
orinokai Sep 6, 2022
bc0aace
Merge branch 'main' into rs/fallback-false-fix
orinokai Sep 6, 2022
94e732c
fix: revert header revalidation owing to side-effects
orinokai Sep 6, 2022
7a662ee
feat: patch next server to force revalidation only during cache fetches
orinokai Sep 6, 2022
dc424b3
test: update tests with new env var name
orinokai Sep 6, 2022
68461db
Merge branch 'main' into rs/fallback-false-fix
orinokai Sep 6, 2022
eec91b0
test: update test with reverted handler signature
orinokai Sep 6, 2022
f81b2c3
Merge branch 'rs/fallback-false-fix' of github.com:netlify/netlify-pl…
orinokai Sep 6, 2022
8732a49
fix: reinstate catch-all redirect for Next redirect handling
orinokai Sep 7, 2022
636d887
Merge branch 'main' into rs/fallback-false-fix
orinokai Sep 7, 2022
e056209
test: update snapshot with new redirects
orinokai Sep 7, 2022
987defd
test: update cypress tests for correct render mode
orinokai Sep 7, 2022
4f41b49
Merge branch 'rs/fallback-false-fix' of github.com:netlify/netlify-pl…
orinokai Sep 7, 2022
f77d276
Merge branch 'main' into rs/fallback-false-fix
orinokai Sep 9, 2022
55de50a
Merge branch 'main' into rs/fallback-false-fix
orinokai Sep 9, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/runtime/src/helpers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,13 @@ const getServerFile = (root: string, includeBase = true) => {
return findModuleFromBase({ candidates, paths: [root] })
}

// force manual revalidation so the ODB handler always receives fresh content
// ensure fallback behaviour is bypassed for pre-rendered pages
// ensure ISR 404 pages send the correct SWR cache headers
const baseServerReplacements: Array<[string, string]> = [
[`let ssgCacheKey = `, `let ssgCacheKey = process.env._BYPASS_SSG || `],
[`checkIsManualRevalidate(req, this.renderOpts.previewProps)`, `checkIsManualRevalidate({ headers: null }, null)`],
[`isManualRevalidate && (fallbackMode !== false || hadCache)`, `isManualRevalidate && hadCache`],
[`private: isPreviewMode || is404Page && cachedData`, `private: isPreviewMode && cachedData`],
]

const nextServerReplacements: Array<[string, string]> = [
Expand Down
82 changes: 64 additions & 18 deletions packages/runtime/src/helpers/redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { RoutesManifest } from './types'
import {
getApiRewrites,
getPreviewRewrites,
is404Route,
isApiRoute,
redirectsForNextRoute,
redirectsForNextRouteWithData,
Expand All @@ -23,6 +24,14 @@ import {
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,
Expand Down Expand Up @@ -56,6 +65,54 @@ const generateLocaleRedirects = ({
return redirects
}

const generate404Redirects = ({
staticRouteEntries,
basePath,
i18n,
buildId,
}: {
staticRouteEntries: Array<[string, SsgRoute]>
basePath: string
i18n: NextConfig['i18n']
buildId: string
}): NetlifyConfig['redirects'] => {
const redirects: NetlifyConfig['redirects'] = []

const isIsr404 = staticRouteEntries.some(
([route, { initialRevalidateSeconds }]) => is404Route(route, i18n) && initialRevalidateSeconds !== false,
)

if (isIsr404) {
redirects.push({
from: `${basePath}/*`,
to: ODB_FUNCTION_PATH,
status: 404,
},
)
} else if (i18n?.locales?.length) {
i18n.locales.forEach((locale) => {
redirects.push({
from: `${basePath}/${locale}/*`,
to: `${basePath}/server/pages/${locale}/404.html`,
status: 404,
})
})
redirects.push({
from: `${basePath}/*`,
to: `${basePath}/server/pages/${i18n.defaultLocale}/404.html`,
status: 404,
})
} else {
redirects.push({
from: `${basePath}/*`,
to: `${basePath}/server/pages/404.html`,
status: 404,
})
}

return redirects
}

export const generateStaticRedirects = ({
netlifyConfig,
nextConfig: { i18n, basePath },
Expand Down Expand Up @@ -123,7 +180,7 @@ const generateStaticIsrRewrites = ({
const staticRoutePaths = new Set<string>()
const staticIsrRewrites: NetlifyConfig['redirects'] = []
staticRouteEntries.forEach(([route, { initialRevalidateSeconds }]) => {
if (isApiRoute(route)) {
if (isApiRoute(route) || is404Route(route, i18n)) {
return
}
staticRoutePaths.add(route)
Expand Down Expand Up @@ -191,13 +248,14 @@ const generateDynamicRewrites = ({
const dynamicRewrites: NetlifyConfig['redirects'] = []
const dynamicRoutesThatMatchMiddleware: Array<string> = []
dynamicRoutes.forEach((route) => {
if (isApiRoute(route.page)) {
if (isApiRoute(route.page) || is404Route(route.page, i18n)) {
return
}
if (route.page in prerenderedDynamicRoutes) {
const { fallback } = prerenderedDynamicRoutes[route.page]
if (matchesMiddleware(middleware, route.page)) {
dynamicRoutesThatMatchMiddleware.push(route.page)
} else {
} else if (fallback !== false) {
dynamicRewrites.push(
...redirectsForNextRoute({ buildId, route: route.page, basePath, to: ODB_FUNCTION_PATH, status: 200, i18n }),
)
Expand Down Expand Up @@ -231,14 +289,7 @@ export const generateRedirects = async ({
join(netlifyConfig.build.publish, 'routes-manifest.json'),
)

netlifyConfig.redirects.push(
...HIDDEN_PATHS.map((path) => ({
from: `${basePath}${path}`,
to: '/404.html',
status: 404,
force: true,
})),
)
netlifyConfig.redirects.push(...generateHiddenPathRedirects({ basePath }))

if (i18n && i18n.localeDetection !== false) {
netlifyConfig.redirects.push(...generateLocaleRedirects({ i18n, basePath, trailingSlash }))
Expand Down Expand Up @@ -274,7 +325,7 @@ export const generateRedirects = async ({

// Add rewrites for all static SSR routes. This is Next 12+
staticRoutes?.forEach((route) => {
if (staticRoutePaths.has(route.page) || isApiRoute(route.page)) {
if (staticRoutePaths.has(route.page) || isApiRoute(route.page) || is404Route(route.page)) {
// Prerendered static routes are either handled by the CDN or are ISR
return
}
Expand All @@ -294,12 +345,7 @@ export const generateRedirects = async ({
netlifyConfig.redirects.push(...dynamicRewrites)
routesThatMatchMiddleware.push(...dynamicRoutesThatMatchMiddleware)

// Final fallback
netlifyConfig.redirects.push({
from: `${basePath}/*`,
to: HANDLER_FUNCTION_PATH,
status: 200,
})
netlifyConfig.redirects.push(...generate404Redirects({ staticRouteEntries, basePath, i18n, buildId }))

const middlewareMatches = new Set(routesThatMatchMiddleware).size
if (middlewareMatches > 0) {
Expand Down
3 changes: 3 additions & 0 deletions packages/runtime/src/helpers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ const netlifyRoutesForNextRoute = (route: string, buildId: string, i18n?: I18n):

export const isApiRoute = (route: string) => route.startsWith('/api/') || route === '/api'

export const is404Route = (route: string, i18n?: I18n) =>
i18n ? i18n.locales.some((locale) => route === `/${locale}/404`) : route === '/404'

export const redirectsForNextRoute = ({
route,
buildId,
Expand Down