/
static-generation-bailout.ts
45 lines (35 loc) · 1.21 KB
/
static-generation-bailout.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
import { DynamicServerError } from './hooks-server-context'
import { staticGenerationAsyncStorage } from './static-generation-async-storage'
class StaticGenBailoutError extends Error {
code = 'NEXT_STATIC_GEN_BAILOUT'
}
export type StaticGenerationBailout = (
reason: string,
opts?: { dynamic?: string; link?: string }
) => boolean | never
export const staticGenerationBailout: StaticGenerationBailout = (
reason,
opts
) => {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (staticGenerationStore?.forceStatic) {
return true
}
if (staticGenerationStore?.dynamicShouldError) {
const { dynamic = 'error', link } = opts || {}
const suffix = link ? ` See more info here: ${link}` : ''
throw new StaticGenBailoutError(
`Page with \`dynamic = "${dynamic}"\` couldn't be rendered statically because it used \`${reason}\`.${suffix}`
)
}
if (staticGenerationStore) {
staticGenerationStore.revalidate = 0
}
if (staticGenerationStore?.isStaticGeneration) {
const err = new DynamicServerError(reason)
staticGenerationStore.dynamicUsageDescription = reason
staticGenerationStore.dynamicUsageStack = err.stack
throw err
}
return false
}