Unverified Commit 035a12ea authored by Josh Story's avatar Josh Story Committed by GitHub

[dynamicIO] Document client component remediations for sync IO (#79787)

When you use sync IO in the client in a way that needs to be fixed we
currently still just provide you with the explanation for server
components. The fixes when sync IO happens in the client are not the
same as when they happen in a server component so this update adds
client specific documentation for these situations.

Namely, the key difference is that on the server you can add caching
through "use cache" and this is not available to you in the client. sync
IO in general is (going to be) allowed in client components broadly as
long as Next.js has a fallback UI to prerender. This means that "fixing"
sync IO access in the client will usually be solved by wrapping in a
Suspense boundary. The alternative is to move the sync IO out of render
or move it to the server where it can be cached.
parent 33648de7
---
title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or another web or node crypto API that generates random values synchronously from a Client Component without a fallback UI defined
---
## Why This Error Occurred
A Client Component is accessing a random value synchronously from the Web Crypto API or from Node's `crypto` API.
Client Components primarily run in the browser however on an initial page visit, Next.js will serve an HTML page produced by simulating the client environment on the server. This process is called Server Side Rendering or SSR. Next.js will attempt to prerender this HTML ahead of time however if a Client Component accesses a random source during this prerender, it cannot include this component in the prerendered HTML, otherwise the value will be fixed on each user request and not random like expected. Next.js will use the nearest Suspense boundary around this component to prerender a fallback instead however in this instance there was no Suspense boundary.
There are a number of ways you might fix this issue depending on the specifics of your use case.
## Possible Ways to Fix It
### Provide Fallback UI
If your random value is intended to be unique per Request, add a Suspense boundary around the component that calls the crypto API that produces this value. This allows Next.js to prerender a fallback UI and fill in an actual random value when the user requests the page.
Before:
```jsx filename="app/blog/new/page.js"
'use client'
export default function Page() {
const newBlogId = crypto.randomUUID()
return <BlogAuthoringView id={newBlogId} />
}
```
After:
```jsx filename="app/blog/new/page.js"
"use client"
import { Suspense } from 'react'
export default function Page() {
return (
<Suspense fallback={<BlogAuthorSkeleton />}>
<DynamicAuthoringView />
</Suspense>
)
}
function BlogAuthorSkeleton() {
...
}
function DynamicAuthoringView() {
const newBlogId = crypto.randomUUID()
return <BlogAuthoringView id={newBlogId} />
}
```
### Only access crypto in the browser
If your random value is only intended for use in the browser you can move the call into an effect or event handler. React does not run effects during server rendering and there are no events during server rendering so neither option will require the prerender to exclude this component.
Before:
```jsx filename="app/workflow.js"
'use client'
function createSecureId() {
const array = new Uint8Array(16)
crypto.getRandomValues(array)
return array[0].toString(16)
}
export default function Workflow({ currentStep, onNext, onPrev }) {
const [id] = useState(createSecureId)
const next = onNext
? () => {
trackEvent(id, 'forward')
onNext()
}
: null
const previous = onPrev
? () => {
trackEvent(id, 'previous')
onPrev()
}
: null
return (
<>
{currentStep}
{next ? <button onClick={next}>Next</button> : null}
{previous ? <button onClick={previous}>Previous</button> : null}
</>
)
}
```
After:
```jsx filename="app/workflow.js"
'use client'
import { useRef } from 'react'
function createSecureId() {
const array = new Uint8Array(16)
crypto.getRandomValues(array)
return array[0].toString(16)
}
function getOrCreateId(ref) {
if (!ref.current) {
ref.current = createSecureId()
}
return ref.current
}
export default function Workflow({ currentStep, onNext, onPrev }) {
const idRef = useRef(null)
const next = onNext
? () => {
trackEvent(getOrCreateId(idRef), 'forward')
onNext()
}
: null
const previous = onPrev
? () => {
trackEvent(getOrCreateId(idRef), 'previous')
onPrev()
}
: null
return (
<>
{currentStep}
{next ? <button onClick={next}>Next</button> : null}
{previous ? <button onClick={previous}>Previous</button> : null}
</>
)
}
```
## Useful Links
- [`connection` function](/docs/app/api-reference/functions/connection)
- [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
- [Node Crypto API](https://nodejs.org/docs/latest/api/crypto.html)
- [`Suspense` React API](https://react.dev/reference/react/Suspense)
--- ---
title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or another web or node crypto API that generates random values synchronously while prerendering title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or another web or node crypto API that generates random values synchronously in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` API was called outside of a `"use cache"` scope and without first calling `await connection()`. Random values that are produced synchronously must either be inside a `"use cache"` scope or be preceded with `await connection()` to explicitly communicate to Next.js whether the random values produced can be reused across many requests (cached) or if they must be unique per Request (`await connection()`). An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` API was called outside of a `"use cache"` scope and without first calling `await connection()`. Random values that are produced synchronously must either be inside a `"use cache"` scope or be preceded with `await connection()` to explicitly communicate to Next.js whether the random values produced can be reused across many requests (cached) or if they must be unique per Request (`await connection()`).
If the API used has an async version you can also switch to that in instead of using `await connection()`. If the API used has an async version you can also switch to that instead of using `await connection()`.
## Possible Ways to Fix It ## Possible Ways to Fix It
...@@ -17,7 +17,7 @@ If you are generating a token to talk to a database that itself should be cached ...@@ -17,7 +17,7 @@ If you are generating a token to talk to a database that itself should be cached
Before: Before:
```jsx filename="app/page.js" ```jsx filename="app/page.js"
async function getCachedDate(token: string) { async function getCachedData(token: string) {
"use cache" "use cache"
return db.query(token, ...) return db.query(token, ...)
} }
...@@ -32,7 +32,7 @@ export default async function Page() { ...@@ -32,7 +32,7 @@ export default async function Page() {
After: After:
```jsx filename="app/page.js" ```jsx filename="app/page.js"
async function getCachedDate(token: string) { async function getCachedData() {
"use cache" "use cache"
const token = crypto.getRandomUUID() const token = crypto.getRandomUUID()
return db.query(token, ...) return db.query(token, ...)
...@@ -81,7 +81,7 @@ Before: ...@@ -81,7 +81,7 @@ Before:
```jsx filename="app/page.js" ```jsx filename="app/page.js"
export default async function Page() { export default async function Page() {
const uuid = crypto.randomUUID() const uuid = crypto.randomUUID()
return <RequestId id={uuid}> return <RequestId id={uuid} />
} }
``` ```
...@@ -93,7 +93,7 @@ import { connection } from 'next/server' ...@@ -93,7 +93,7 @@ import { connection } from 'next/server'
export default async function Page() { export default async function Page() {
await connection() await connection()
const uuid = crypto.randomUUID() const uuid = crypto.randomUUID()
return <RequestId id={uuid}> return <RequestId id={uuid} />
} }
``` ```
......
---
title: Cannot access current time from a Client Component without a fallback UI defined
---
## Why This Error Occurred
A Client Component is accessing the current time with `Date.now()`, `Date()`, or `new Date()`.
Client Components primarily run in the browser however on an initial page visit, Next.js will serve an HTML page produced by simulating the client environment on the server. This process is called Server Side Rendering or SSR. Next.js will attempt to prerender this HTML ahead of time however if a Client Component accesses the current time during this prerender, it cannot include this component in the prerendered HTML, otherwise it might contain content based on a time very different from when the HTML is sent to a user. Next.js will use the nearest Suspense boundary around this component to prerender a fallback instead however in this instance there was no Suspense boundary.
There are a number of ways you might fix this issue depending on the specifics of your use case.
## Possible Ways to Fix It
### Provide Fallback UI
If you want the time value to be part of the server rendered HTML you can add a Suspense boundary around the component which allows Next.js to prerender a fallback UI ahead of a user's request and fill in the actual content when the user request occurs.
Before:
```jsx filename="app/article.js"
'use client'
export function RelativeTime({ timestamp }) {
const now = Date.now()
return (
<span suppressHydrationWarning>{computeTimeAgo({ timestamp, now })}</span>
)
}
export default function Article({ articleData }) {
return (
<article>
<h1>...</h1>
<RelativeTime timestamp={articleData.publishedAt} />
</article>
)
}
```
After:
```jsx filename="app/article.js"
'use client'
import { Suspense } from 'react'
export function RelativeTime({ timestamp }) {
const now = Date.now()
return <span>{computeTimeAgo({ timestamp, now })}</span>
}
export default function Article({ articleData }) {
return (
<article>
<h1>...</h1>
<Suspense fallback={<span>...</span>}>
<RelativeTime timestamp={articleData.publishedAt} />
</Suspense>
</article>
)
}
```
### Only access the time in the browser
If you do not want to provide a fallback UI you may be able to move the time access into an effect. React does not run effects during server rendering so the time access will only occur in the browser.
Before:
```jsx filename="app/article.js"
'use client'
export function RelativeTime({ timestamp }) {
const now = Date.now()
return (
<span suppressHydrationWarning>{computeTimeAgo({ timestamp, now })}</span>
)
}
export default function Article({ articleData }) {
return (
<article>
<h1>...</h1>
<RelativeTime timestamp={articleData.publishedAt} />
</article>
)
}
```
After:
```jsx filename="app/article.js"
'use client'
import { useState, useEffect } from 'react'
export function RelativeTime({ timestamp }) {
const [timeAgo, setTimeAgo] = useState('')
useEffect(() => {
// The effect won't run while rendering on the server
const now = Date.now()
setTimeAgo(computeTimeAgo({ timestamp, now }))
}, [timestamp])
return <span>{timeAgo}</span>
}
export default function Article({ articleData }) {
return (
<article>
<h1>...</h1>
<RelativeTime timestamp={articleData.publishedAt} />
</article>
)
}
```
### Cache the time in a Server Component
While Next.js will treat reading the current time in a Server Component the same as in a Client Component, you have the additional option of caching the time read using `"use cache"`. With this approach the time value can be included in the prerendered HTML because you are explicitly indicating the value does not need to reflect the time of the user's request.
Before:
```jsx filename="app/home/layout.js"
'use client'
export default function Layout({ children }) {
return (
<>
<main>{children}</main>
<footer>
<span>Copyright {new Date().getFullYear()}</span>
</footer>
</>
)
}
```
After:
```jsx filename="app/home/layout.js"
async function getCurrentYear() {
'use cache'
return new Date().getFullYear()
}
export default async function Layout({ children }) {
return (
<>
<main>{children}</main>
<footer>
<span>Copyright {await getCurrentYear()}</span>
</footer>
</>
)
}
```
### Performance use case
If you are using the current time for performance tracking with elapsed time, use `performance.now()`.
Before:
```jsx filename="app/page.js"
"use client"
export default function Page() {
const start = Date.now();
const data = computeDataSlowly(...);
const end = Date.now();
console.log(`computeDataSlowly took ${end - start} milliseconds to complete`)
return ...
}
```
After:
```jsx filename="app/page.js"
"use client"
export default async function Page() {
const start = performance.now();
const data = computeDataSlowly(...);
const end = performance.now();
console.log(`computeDataSlowly took ${end - start} milliseconds to complete`)
return ...
}
```
> **Note**: If you need report an absolute time to an observability tool you can also use `performance.timeOrigin + performance.now()`.
## Useful Links
- [`Date.now` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)
- [`Date constructor` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)
- [`"use cache"`](/docs/app/api-reference/directives/use-cache)
- [`performance` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Performance)
- [`Suspense` React API](https://react.dev/reference/react/Suspense)
- [`useEffect` React Hook](https://react.dev/reference/react/useEffect)
--- ---
title: Cannot infer intended usage of current time with `Date.now()`, `Date()`, or `new Date()` title: Cannot infer intended usage of current time with `Date.now()`, `Date()`, or `new Date()` in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
Reading the current time can be ambiguous. Sometimes you intend to capture the time when something was cached, other times you intend to capture the time of a user Request. You might also be trying to measure runtime performance to track elapsed time. Reading the current time in a Server Component can be ambiguous. Sometimes you intend to capture the time when something was cached, other times you intend to capture the time of a user Request. You might also be trying to measure runtime performance to track elapsed time.
In this instance Next.js cannot determine your intent from usage so it needs you to clarify your intent. The way you do that depends on your use case. See the possible solutions below for how to move forward. Depending on your use case you might use alternative time APIs like `performance.now()`, you might cache the time read with `"use cache"`, or you might communicate that the time must be evaluated on each request by guarding it with `await connection()` or moving it into a Client Component.
## Possible Ways to Fix It ## Possible Ways to Fix It
...@@ -94,22 +94,29 @@ export default async function Page() { ...@@ -94,22 +94,29 @@ export default async function Page() {
} }
``` ```
### Reactive use case ### Request-time use case
#### Moving time to the client
If you want the current time to change and be reactive, consider moving this usage to a Client Component. Note that Server Side Rendering timestamps in a Client Component is also considered ambiguous so to implement this properly Next.js needs you to only read the time in the browser, for instance by using `useLayoutEffect()` or `useEffect()`. If the current time must be evaluated on each user Request consider moving the current time read into a Client Component. You might also find that this is more convenient when you want to do things like update the time independent of a page navigation. For instance imagine you have a relative time component. Instead of rendering the relative time in a Server Component on each Request you can render the relative time when the Client Component renders and then update it periodically.
If you go with this approach you will need to ensure the Client Component which reads the time during render has a Suspense boundary above it. You may be able to improve the loading experience by adopting a more narrowly scoped Suspense boundary. Use your judgement about what kind of UI loading sequence you want your users to experience to guide your decision here.
Before: Before:
```jsx filename="app/page.js" ```jsx filename="app/page.js"
function Timestamp() { function RelativeTime({ when }) {
return 'current time: ' + new Date().toString() return computeTimeAgo(new Date(), when)
} }
export default async function Page() { export default async function Page() {
const data = await ...
return ( return (
<main> <main>
... ...
<Timestamp /> <Suspense>
<RelativeTime when={data.createdAt} />
</Suspense>
</main> </main>
) )
} }
...@@ -117,41 +124,55 @@ export default async function Page() { ...@@ -117,41 +124,55 @@ export default async function Page() {
After: After:
```jsx filename="app/client-components.js" ```jsx filename="app/relative-time.js"
'use client' 'use client'
import { useState, useLayoutEffect } from 'react' import { useReducer } from 'react'
export function Timestamp() { export function RelativeTime({ when }) {
const [time, setTime] = useState(null) const [_, update] = useReducer(() => ({}), {})
useLayoutEffect(() => { const timeAgo = computeTimeAgo(new Date(), when)
// You can determine when and how often to update
// the time here. In this example we update it only once // Whenever the timeAgo value changes a new timeout is
setTime(new Date().toString()) // scheduled to update the component. Now the time can
}, []) // rerender without having the Server Component render again.
if (time) { useEffect(() => {
return 'current time: ' + time const updateAfter = computeTimeUntilNextUpdate(timeAgo)
} let timeout = setTimeout(() => {
return null update()
}, updateAfter)
return () => {
clearTimeout(timeout)
}
})
return timeAgo
} }
``` ```
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { Timestamp } from './client-components' import { RelativeTime } from './relative-time'
export default async function Page() { export default async function Page() {
const data = await ...
return ( return (
<main> <main>
... ...
<Timestamp /> <Suspense>
<RelativeTime when={data.createdAt} />
</Suspense>
</main> </main>
) )
} }
``` ```
### Request-time use case > **Note**: Accessing the current time in a Client Component will still cause it to be excluded from prerendered server HTML but Next.js allows this within Client Components because it can either compute the time dynamically when the user requests the HTML page or in the browser.
#### Guarding the time with `await connection()`
It may be that you want to make some rendering determination using the current time on the server and thus cannot move the time read into a Client Component. In this case you must instruct Next.js that the time read is meant to be evaluated at request time by preceding it with `await connection()`.
If you want the current time to represent the time of a user Request, add `await connection()` before you read the current time. This instructs Next.js that everything after the `await connection()` requires there to be a user Request before it can run. If you add `await connection()` you will also need to ensure there is a Suspense boundary somewhere above the waiting component that describes a fallback UI React can use. The Suspense can be anywhere in the parent component stack but it is shown here above the waiting component for demonstration purposes. Next.js enforces that it can always produce at least a partially static initial HTML page so you will also need to ensure that there is a Suspense boundary somewhere above this component that informs Next.js about the intended fallback UI to use while prerendering this page.
Before: Before:
...@@ -169,6 +190,7 @@ export default async function Page() { ...@@ -169,6 +190,7 @@ export default async function Page() {
After: After:
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
async function BannerSkeleton() { async function BannerSkeleton() {
......
---
title: Cannot access `Math.random()` from a Client Component without a fallback UI defined
---
## Why This Error Occurred
A Client Component is calling `Math.random()`.
Client Components primarily run in the browser however on an initial page visit, Next.js will serve an HTML page produced by simulating the client environment on the server. This process is called Server Side Rendering or SSR. Next.js will attempt to prerender this HTML ahead of time however if a Client Component accesses a random source during this prerender, it cannot include this component in the prerendered HTML, otherwise the value will be fixed on each user request and not random like expected. Next.js will use the nearest Suspense boundary around this component to prerender a fallback instead however in this instance there was no Suspense boundary.
There are a number of ways you might fix this issue depending on the specifics of your use case.
## Possible Ways to Fix It
### Provide Fallback UI
Typically it is not possible to use `Math.random()` in a Client Component that is Server Rendered without introducing a hydration error. However if you find yourself with a component that calls `Math.random()` during rendering, and you already handle the tricky case of hydrating this value consistently, then you can add a Suspense boundary around the component that calls `Math.random()` to allow Next.js to prerender a fallback UI and fill in an actual random value when the user requests the page.
Before:
```jsx filename="app/user-avatar.js"
'use client'
export function UserAvatar({ avatar }) {
let backgroundColor = avatar.preferredBackground
if (!backgroundColor) {
const randomColor = `#${Math.random().toString(16).slice(2, 8)}`
// imagine safelyGetRandomColor is a function that handles synchronizing
// the random color chosen between SSR and hydration to avoid hydration errors
backgroundColor = safelyGetRandomColor(randomColor)
}
return <Avatar background={backgroundColor} src={avatar.src} />
}
```
After:
```jsx filename="app/user-avatar.js"
"use client"
export function UserAvatar({ avatar }) {
return (
<Suspense fallback={<AvatarSkeleton />}>
<DynamicUserAvatar avatar={avatar} />
</Suspense>
)
}
function AvatarSkeleton() {
...
}
function DynamicUserAvatar({ avatar }) {
let backgroundColor = avatar.preferredBackground
if (!backgroundColor) {
const randomColor = `#${Math.random().toString(16).slice(2, 8)}`
// imagine safelyGetRandomColor is a function that handles synchronizing
// the random color chosen between SSR and hydration to avoid hydration errors
backgroundColor = safelyGetRandomColor(randomColor)
}
return <Avatar background={backgroundColor} src={avatar.src} />
}
```
### Only access `Math.random` in the browser
If your random value is only intended for use in the browser you can move the call into an effect or event handler. React does not run effects during server rendering and there are no events during server rendering so neither option will require the prerender to exclude this component.
Before:
```jsx filename="app/workflow.js"
'use client'
export default function Workflow({ currentStep, onNext, onPrev }) {
const [id] = useState(() => Math.random().toString(36).slice(2))
const next = onNext
? () => {
trackEvent(id, 'forward')
onNext()
}
: null
const previous = onPrev
? () => {
trackEvent(id, 'previous')
onPrev()
}
: null
return (
<>
{currentStep}
{next ? <button onClick={next}>Next</button> : null}
{previous ? <button onClick={previous}>Previous</button> : null}
</>
)
}
```
After:
```jsx filename="app/workflow.js"
'use client'
import { useRef } from 'react'
function getOrCreateId(ref) {
if (!ref.current) {
ref.current = Math.random().toString(36).slice(2)
}
return ref.current
}
export default function Workflow({ currentStep, onNext, onPrev }) {
const idRef = useRef(null)
const next = onNext
? () => {
trackEvent(getOrCreateId(idRef), 'forward')
onNext()
}
: null
const previous = onPrev
? () => {
trackEvent(getOrCreateId(idRef), 'previous')
onPrev()
}
: null
return (
<>
{currentStep}
{next ? <button onClick={next}>Next</button> : null}
{previous ? <button onClick={previous}>Previous</button> : null}
</>
)
}
```
## Useful Links
- [`Suspense` React API](https://react.dev/reference/react/Suspense)
--- ---
title: Cannot access `Math.random()` while prerendering title: Cannot infer intended usage of `Math.random()` in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
A function is calling `Math.random()`. Random values are not prerenderable and must be excluded. The correct solution depends on your use case. You can find more information below about possible ways to resolves this issue. A Server Component is calling `Math.random()` without specifying whether it should be cached or whether it should be evaluated on each user Request. If you want this random value to be included in the prerendered HTML for this page you must cache it using `"use cache"`. If you want this random value to be unique per Request you must precede it with `await connection()` so Next.js knows to exclude it from the prerendered HTML.
## Possible Ways to Fix It ## Possible Ways to Fix It
If your random value is intended to be unique per Request add `await connection()` before you call `Math.random()` and ensure there is a Suspense boundary somewhere above this component. This will inform Next.js that this component should be excluded from prerendering and communicate the necessary fallback UI that should be rendered while the component renders on each Request. ### Cache the random value
If your random value is cacheable, move the `Math.random()` call to a `"use cache"` function. For instance, imagine you have a product page and you want to randomize the product order periodically but you are fine with the random order being re-used for different users.
Before:
```jsx filename="app/page.js"
export default async function Page() {
const products = await getCachedProducts()
const randomSeed = Math.random()
const randomizedProducts = randomize(products, randomSeed)
return <ProductsView products={randomizedProducts} />
}
```
After:
```jsx filename="app/page.js"
export default async function Page() {
'use cache'
const products = await getCachedProducts()
const randomSeed = Math.random()
const randomizedProducts = randomize(products, randomSeed)
return <ProductsView products={randomizedProducts} />
}
```
> **Note**: `"use cache"` is a powerful API with some nuances. If your cache lifetime is too short Next.js may still exclude it from prerendering. Check out the docs for `"use cache"` to learn more.
### Indicate the random value is unique per Request
If you want the random value to be evaluated on each Request precede it with `await connection()`. Next.js will exclude this Server Component from the prerendered HTML and include the fallback UI from the nearest Suspense boundary wrapping this component instead. When a user makes a Request for this page the Server Component will be rendered and the updated UI will stream in dynamically.
Before: Before:
...@@ -32,12 +63,14 @@ async function ProductsSkeleton() { ...@@ -32,12 +63,14 @@ async function ProductsSkeleton() {
export default async function Page() { export default async function Page() {
const products = await getCachedProducts(); const products = await getCachedProducts();
return <Suspense fallback={<ProductsSkeleton />}> return (
<DynamicProductsView products={products} /> <Suspense fallback={<ProductsSkeleton />}>
</Suspense> <DynamicProductsView products={products} />
</Suspense>
)
} }
async function DynamicProductsView() { async function DynamicProductsView({ products }) {
await connection(); await connection();
const randomSeed = Math.random() const randomSeed = Math.random()
const randomizedProducts = randomize(products, randomSeed) const randomizedProducts = randomize(products, randomSeed)
......
...@@ -11,9 +11,10 @@ type ApiType = 'time' | 'random' | 'crypto' ...@@ -11,9 +11,10 @@ type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, type: ApiType) { export function io(expression: string, type: ApiType) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
let isClient = false
if ( if (
workUnitStore.type === 'prerender' || workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-client' (isClient = workUnitStore.type === 'prerender-client')
) { ) {
const prerenderSignal = workUnitStore.controller.signal const prerenderSignal = workUnitStore.controller.signal
if (prerenderSignal.aborted === false) { if (prerenderSignal.aborted === false) {
...@@ -24,13 +25,19 @@ export function io(expression: string, type: ApiType) { ...@@ -24,13 +25,19 @@ export function io(expression: string, type: ApiType) {
let message: string let message: string
switch (type) { switch (type) {
case 'time': case 'time':
message = `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time` message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`
: `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break break
case 'random': case 'random':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random` message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break break
case 'crypto': case 'crypto':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto` message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break break
default: default:
throw new InvariantError( throw new InvariantError(
......
...@@ -81,7 +81,7 @@ function runTests(options: { withMinification: boolean }) { ...@@ -81,7 +81,7 @@ function runTests(options: { withMinification: boolean }) {
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError( expectError(
'Error: Route "/" used `new Date()` instead of using `performance` or without explicitly calling `await connection()` beforehand.' 'Error: Route "/" used `new Date()` inside a Client Component without a Suspense boundary above it.'
) )
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
}) })
...@@ -167,7 +167,7 @@ function runTests(options: { withMinification: boolean }) { ...@@ -167,7 +167,7 @@ function runTests(options: { withMinification: boolean }) {
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError( expectError(
'Error: Route "/" used `new Date()` instead of using `performance` or without explicitly calling `await connection()` beforehand.' 'Error: Route "/" used `new Date()` inside a Client Component without a Suspense boundary above it.'
) )
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
}) })
......
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