Unverified Commit 9e0ce4f6 authored by Josh Story's avatar Josh Story Committed by GitHub

[dynamicIO] Instrument `Math.random()` to be considered synchronously dynamic (#70837)

`Math.random()` is IO though it is synchronous. When `dynamicIO` is
enabled we need to treat calls to `Math.random()` as IO and exclude them
from prerenders unless they are cached. This change sets up the
instrumentation for this behavior.

Unless the sync access of async request APIs this patch does not yet
have any dev warnings. These will be added in a future update when we
can instrument the environment name during dev to tell the difference
between the prerender phase, and render phase even without a build
parent 1e000f6f
...@@ -325,11 +325,18 @@ export function trackDynamicDataInDynamicRender( ...@@ -325,11 +325,18 @@ export function trackDynamicDataInDynamicRender(
// Despite it's name we don't actually abort unless we have a controller to call abort on // Despite it's name we don't actually abort unless we have a controller to call abort on
// There are times when we let a prerender run long to discover caches where we want the semantics // There are times when we let a prerender run long to discover caches where we want the semantics
// of tracking dynamic access without terminating the prerender early // of tracking dynamic access without terminating the prerender early
function abortOnSynchronousDynamicDataAccess( export function abortOnSynchronousDynamicDataAccess(
route: string, route: string,
expression: string, expression: string,
prerenderStore: PrerenderStoreModern prerenderStore: PrerenderStoreModern
): void { ): void {
if (prerenderStore.dynamicTracking) {
const disallowedDynamic = prerenderStore.dynamicTracking.disallowedDynamic
if (disallowedDynamic.syncDynamicExpression === '') {
disallowedDynamic.syncDynamicExpression = expression
}
}
const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.` const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`
const error = createPrerenderInterruptedError(reason) const error = createPrerenderInterruptedError(reason)
...@@ -367,12 +374,6 @@ export function abortAndThrowOnSynchronousDynamicDataAccess( ...@@ -367,12 +374,6 @@ export function abortAndThrowOnSynchronousDynamicDataAccess(
expression: string, expression: string,
prerenderStore: PrerenderStoreModern prerenderStore: PrerenderStoreModern
): never { ): never {
if (prerenderStore.dynamicTracking) {
const disallowedDynamic = prerenderStore.dynamicTracking.disallowedDynamic
if (disallowedDynamic.syncDynamicExpression === '') {
disallowedDynamic.syncDynamicExpression = expression
}
}
abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore) abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
throw createPrerenderInterruptedError( throw createPrerenderInterruptedError(
`Route ${route} needs to bail out of prerendering at this point because it used ${expression}.` `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`
...@@ -674,8 +675,10 @@ export function throwIfDisallowedDynamic( ...@@ -674,8 +675,10 @@ export function throwIfDisallowedDynamic(
for (let i = 0; i < syncDynamicErrors.length; i++) { for (let i = 0; i < syncDynamicErrors.length; i++) {
console.error(syncDynamicErrors[i]) console.error(syncDynamicErrors[i])
} }
const expression =
disallowedDynamic.syncDynamicExpression || 'a synchronous Dynamic API'
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${workStore.route} used a synchronous Dynamic API while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI. It is best to avoid synchronous Dynamic API access during prerendering.` `Route ${workStore.route} used ${expression} while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI. It is best to avoid synchronous Dynamic API access during prerendering.`
) )
} }
......
// This file should be imported before any others. It sets up the environment
// for later imports to work properly.
// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment
if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
const { AsyncLocalStorage } = require('async_hooks')
;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage
}
if (typeof (globalThis as any).WebSocket !== 'function') {
Object.defineProperty(globalThis, 'WebSocket', {
get() {
return require('next/dist/compiled/ws').WebSocket
},
})
}
/**
* We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness
* When dynamicIO is enabled. randomness is a form of IO even though it resolves synchronously. When dyanmicIO is
* enabled we need to ensure that randomness is excluded from prerenders.
*
* The extensions here never error nor alter the random generation itself and thus should be transparent to callers.
*/
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import {
isDynamicIOPrerender,
prerenderAsyncStorage,
} from '../app-render/prerender-async-storage.external'
import { abortOnSynchronousDynamicDataAccess } from '../app-render/dynamic-rendering'
const originalRandom = Math.random
Math.random = function random() {
const prerenderStore = prerenderAsyncStorage.getStore()
if (
prerenderStore &&
prerenderStore.type === 'prerender' &&
isDynamicIOPrerender(prerenderStore)
) {
const workStore = workAsyncStorage.getStore()
const route = workStore ? workStore.route : ''
const expression = '`Math.random()`'
if (workStore) {
abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
}
}
return originalRandom.apply(null, arguments as any)
// We bind here to alter the `toString` printing to match `Math.random`'s native `toString`.
// eslint-disable-next-line no-extra-bind
}.bind(null)
Object.defineProperty(Math.random, 'name', { value: 'random' })
// This file should be imported before any others. It sets up the environment // This file should be imported before any others. It sets up the environment
// for later imports to work properly. // for later imports to work properly.
// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment import './node-environment-baseline'
if (typeof (globalThis as any).AsyncLocalStorage !== 'function') { import './node-environment-extensions/random'
const { AsyncLocalStorage } = require('async_hooks')
;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage
}
if (typeof (globalThis as any).WebSocket !== 'function') {
Object.defineProperty(globalThis, 'WebSocket', {
get() {
return require('next/dist/compiled/ws').WebSocket
},
})
}
...@@ -462,6 +462,15 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -462,6 +462,15 @@ export class AppRouteRouteModule extends RouteModule<
} }
}) })
}) })
if (controller.signal.aborted) {
// We aborted from within the execution
throw createDynamicIOError(workStore.route)
} else {
// We didn't abort during the execution. We can abort now as a matter of semantics
// though at the moment nothing actually consumes this signal so it won't halt any
// inflight work.
controller.abort()
}
} else if (isStaticGeneration) { } else if (isStaticGeneration) {
res = await workUnitAsyncStorage.run( res = await workUnitAsyncStorage.run(
{ {
......
import { nextTestSetup } from 'e2e-utils'
const WITH_PPR = !!process.env.__NEXT_EXPERIMENTAL_PPR
const stackStart = /\s+at /
function createExpectError(cliOutput: string) {
let cliIndex = 0
return function expectError(
containing: string,
withStackContaining?: string
) {
const initialCliIndex = cliIndex
let lines = cliOutput.slice(cliIndex).split('\n')
let i = 0
while (i < lines.length) {
let line = lines[i++] + '\n'
cliIndex += line.length
if (line.includes(containing)) {
if (typeof withStackContaining !== 'string') {
return
} else {
while (i < lines.length) {
let stackLine = lines[i++] + '\n'
if (!stackStart.test(stackLine)) {
expect(stackLine).toContain(withStackContaining)
}
if (stackLine.includes(withStackContaining)) {
return
}
}
}
}
}
expect(cliOutput.slice(initialCliIndex)).toContain(containing)
}
}
function runTests(options: { withMinification: boolean }) {
const isTurbopack = !!process.env.TURBOPACK
const { withMinification } = options
describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => {
describe('Sync Dynamic - With Fallback - Math.random()', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname + '/fixtures/sync-random-with-fallback',
skipStart: true,
})
if (skipped) {
return
}
if (isNextDev) {
it('does not run in dev', () => {})
return
}
beforeEach(async () => {
if (!withMinification) {
await next.patchFile('next.config.js', (content) =>
content.replace(
'serverMinification: true,',
'serverMinification: false,'
)
)
}
})
it('should not error the build when calling Math.random() if all dynamic access is inside a Suspense boundary', async () => {
try {
await next.start()
} catch {
throw new Error('expected build not to fail for fully static project')
}
if (WITH_PPR) {
expect(next.cliOutput).toContain('◐ / ')
const $ = await next.render$('/')
expect($('[data-fallback]').length).toBe(2)
} else {
expect(next.cliOutput).toContain('ƒ / ')
const $ = await next.render$('/')
expect($('[data-fallback]').length).toBe(0)
}
})
})
describe('Sync Dynamic - Without Fallback - Math.random()', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname + '/fixtures/sync-random-without-fallback',
skipStart: true,
})
if (skipped) {
return
}
if (isNextDev) {
it('does not run in dev', () => {})
return
}
beforeEach(async () => {
if (!withMinification) {
await next.patchFile('next.config.js', (content) =>
content.replace(
'serverMinification: true,',
'serverMinification: false,'
)
)
}
})
it('should error the build if Math.random() happens before some component outside a Suspense boundary is complete', async () => {
try {
await next.start()
} catch {
// we expect the build to fail
}
const expectError = createExpectError(next.cliOutput)
if (WITH_PPR) {
expectError(
'Error: Route / used a synchronous Dynamic API: `Math.random()`. This particular component may have been dynamic anyway or it may have just not finished before the synchronous Dynamic API was invoked.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
} else {
expectError(
'Error: Route / used a synchronous Dynamic API: `Math.random()`, which caused this component to not finish rendering before the prerender completed and no fallback UI was defined.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
}
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / used `Math.random()` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
)
expectError('exiting the build.')
})
})
})
}
runTests({ withMinification: true })
runTests({ withMinification: false })
...@@ -128,7 +128,7 @@ function runTests(options: { withMinification: boolean }) { ...@@ -128,7 +128,7 @@ function runTests(options: { withMinification: boolean }) {
) )
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError( expectError(
'Error: Route / used a synchronous Dynamic API while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.' 'Error: Route / used `searchParams.foo` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
) )
expectError('exiting the build.') expectError('exiting the build.')
}) })
...@@ -228,7 +228,7 @@ function runTests(options: { withMinification: boolean }) { ...@@ -228,7 +228,7 @@ function runTests(options: { withMinification: boolean }) {
} }
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError( expectError(
'Error: Route / used a synchronous Dynamic API while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.' 'Error: Route / used `searchParams.foo` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
) )
expectError('exiting the build.') expectError('exiting the build.')
}) })
...@@ -328,7 +328,7 @@ function runTests(options: { withMinification: boolean }) { ...@@ -328,7 +328,7 @@ function runTests(options: { withMinification: boolean }) {
} }
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError( expectError(
'Error: Route / used a synchronous Dynamic API while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.' "Error: Route / used cookies().get('token') while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI."
) )
expectError('exiting the build.') expectError('exiting the build.')
}) })
......
'use client'
export function IndirectionOne({ children }) {
return children
}
export function IndirectionTwo({ children }) {
return children
}
export function IndirectionThree({ children }) {
return children
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { Suspense, use } from 'react'
import { IndirectionOne, IndirectionTwo, IndirectionThree } from './indirection'
type SearchParams = { foo: string | string[] | undefined }
export default async function Page(props: {
searchParams: Promise<SearchParams>
}) {
return (
<>
<p>
This page accesses Math.random() while prerendering but it does so late
enough in the render that all unfinished sub-trees have a defined
Suspense boundary. This is fine and doesn't need to error the build.
</p>
<Suspense fallback={<Fallback />}>
<IndirectionOne>
<RandomReadingComponent />
</IndirectionOne>
</Suspense>
<Suspense fallback={<Fallback />}>
<IndirectionTwo>
<LongRunningComponent />
</IndirectionTwo>
</Suspense>
<IndirectionThree>
<ShortRunningComponent />
</IndirectionThree>
</>
)
}
function RandomReadingComponent() {
if (typeof window === 'undefined') {
use(new Promise((r) => process.nextTick(r)))
}
const random = Math.random()
return (
<div>
<span id="rand">{random}</span>
</div>
)
}
function LongRunningComponent() {
if (typeof window === 'undefined') {
use(
new Promise((r) =>
process.nextTick(async () => {
await 1
process.nextTick(r)
})
)
)
}
return (
<div>
this component took a long time to resolve (but still before the dynamicIO
cutoff). It might not be done before the Math.random() access happens.
</div>
)
}
function ShortRunningComponent() {
return (
<div>
This component runs quickly (in a microtask). It should be finished before
the Math.random() access happens.
</div>
)
}
function Fallback() {
return <div data-fallback="">loading...</div>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
pprFallbacks: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
dynamicIO: true,
serverMinification: true,
},
}
module.exports = nextConfig
'use client'
export function IndirectionOne({ children }) {
return children
}
export function IndirectionTwo({ children }) {
return children
}
export function IndirectionThree({ children }) {
return children
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { Suspense, use } from 'react'
import { IndirectionOne, IndirectionTwo, IndirectionThree } from './indirection'
type SearchParams = { foo: string | string[] | undefined }
export default async function Page(props: {
searchParams: Promise<SearchParams>
}) {
return (
<>
<p>
This page accesses Math.random() while prerendering and does so before
something that is not wrapped in a Suspense boundary has finished
rendering
</p>
<Suspense fallback={<Fallback />}>
<IndirectionOne>
<RandomReadingComponent />
</IndirectionOne>
</Suspense>
<IndirectionTwo>
<LongRunningComponent />
</IndirectionTwo>
<IndirectionThree>
<ShortRunningComponent />
</IndirectionThree>
</>
)
}
function RandomReadingComponent() {
if (typeof window === 'undefined') {
use(new Promise((r) => process.nextTick(r)))
}
const random = Math.random()
return (
<div>
<span id="rand">{random}</span>
</div>
)
}
function LongRunningComponent() {
if (typeof window === 'undefined') {
use(
new Promise((r) =>
process.nextTick(async () => {
await 1
process.nextTick(r)
})
)
)
}
return (
<div>
this component took a long time to resolve (but still before the dynamicIO
cutoff). It might not be done before the Math.random() access happens.
</div>
)
}
function ShortRunningComponent() {
return (
<div>
This component runs quickly (in a microtask). It should be finished before
the Math.random() access happens.
</div>
)
}
function Fallback() {
return <div data-fallback="">loading...</div>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
pprFallbacks: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
dynamicIO: true,
serverMinification: true,
},
}
module.exports = nextConfig
...@@ -35,7 +35,7 @@ async function Foo({ children }) { ...@@ -35,7 +35,7 @@ async function Foo({ children }) {
} }
async function Bar({ children }) { async function Bar({ children }) {
let length = (Math.random() * 10) | 0 let length = 7
for (let i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
await 1 await 1
} }
......
...@@ -6,14 +6,6 @@ export function getSentinelValue() { ...@@ -6,14 +6,6 @@ export function getSentinelValue() {
: 'at runtime' : 'at runtime'
} }
export function LayoutSentinel() { export function SentinelValue() {
return <div id="layout">{getSentinelValue()}</div> return getSentinelValue()
}
export function PageSentinel() {
return <div id="page">{getSentinelValue()}</div>
}
export function InnerSentinel() {
return <div id="inner">{getSentinelValue()}</div>
} }
import { SentinelValue } from '../../getSentinelValue'
export default async function Page() {
const random = await getRandom()
return (
<div>
<label>random</label>
<span id="value">{random}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
async function getRandom() {
'use cache'
return Math.random()
}
import { Suspense } from 'react'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<Suspense fallback={<div data-fallback="">loading...</div>}>
{children}
</Suspense>
)
}
import { SentinelValue } from '../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const random = Math.random()
return (
<div>
<label>random</label>
<span id="value">{random}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
const WITH_PPR = !!process.env.__NEXT_EXPERIMENTAL_PPR
describe('dynamic-io', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
it('should prerender pages with cached Math.random() calls', async () => {
let $ = await next.render$('/random/cached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
}
})
it('should not prerender pages with uncached Math.random() calls', async () => {
let $ = await next.render$('/random/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
} else if (WITH_PPR) {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
} else {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
}
})
})
export const runtime = 'edge'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
export const runtime = 'edge'
export function GET() {
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
export function GET() {
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
export default async function Page() {
if (typeof process !== 'undefined') {
// we delay the random calls to avoid triggering dynamic in other component trees
await new Promise((r) => process.nextTick(r))
}
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { unstable_cache as cache } from 'next/cache'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { unstable_cache as cache } from 'next/cache'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
import { connection } from 'next/server'
export async function GET() {
await connection()
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { connection } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
export async function GET() {
await connection()
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { connection } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
export default async function Page() {
await connection()
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { connection } from 'next/server'
export async function GET() {
await connection()
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>
<Suspense fallback="loading...">{children}</Suspense>
</main>
</body>
</html>
)
}
export default async function Page() {
return <section>rewritten</section>
}
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (Math.random() > -1 && request.nextUrl.pathname === '/rewrite') {
return NextResponse.rewrite(new URL('/rewritten', request.url))
}
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
pprFallbacks: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
dynamicIO: true,
},
}
module.exports = nextConfig
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
rand1: number
rand2: number
}
export default function handler(
_req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ rand1: Math.random(), rand2: Math.random() })
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
Page.getInitialProps = async () => {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { rand1, rand2 }
}
export async function getStaticProps() {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { props: { rand1, rand2 } }
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
export async function getServerSideProps() {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { props: { rand1, rand2 } }
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
export const runtime = 'edge'
export function GET() {
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
export const revalidate = 1
export function GET() {
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
export default async function Page() {
if (typeof process !== 'undefined') {
// we delay the random calls to avoid triggering dynamic in other component trees
await new Promise((r) => process.nextTick(r))
}
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
export const revalidate = 1
import { unstable_cache as cache } from 'next/cache'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { unstable_cache as cache } from 'next/cache'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { connection } from 'next/server'
export async function GET() {
await connection()
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { connection } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
export async function GET() {
await connection()
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { connection } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
export default async function Page() {
await connection()
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>
<Suspense fallback="loading...">{children}</Suspense>
</main>
</body>
</html>
)
}
export default async function Page() {
return <section>rewritten</section>
}
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (Math.random() > -1 && request.nextUrl.pathname === '/rewrite') {
return NextResponse.rewrite(new URL('/rewritten', request.url))
}
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
pprFallbacks: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
},
}
module.exports = nextConfig
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
rand1: number
rand2: number
}
export default function handler(
_req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ rand1: Math.random(), rand2: Math.random() })
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
Page.getInitialProps = async () => {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { rand1, rand2 }
}
export async function getStaticProps() {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { props: { rand1, rand2 } }
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
export async function getServerSideProps() {
const rand1 = Math.random()
const rand2 = Math.random()
// Pass data to the page via props
return { props: { rand1, rand2 } }
}
export default function Page({ rand1, rand2 }) {
return (
<main>
<ul>
<li>{rand1}</li>
<li>{rand2}</li>
</ul>
</main>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment