Files
next.js/errors/next-prerender-random.mdx
T
74a19b7467 docs: unify the header deps by removing # (#72391)
## Summary
Remove redundant `#` from [error
pages](https://github.com/vercel/next.js/tree/canary/errors).

## Description
Follow up #52038 and #72263.
Updated
[template.txt](https://github.com/vercel/next.js/blob/canary/errors/template.txt)
and clarified the header deps.
Then rewrite as per the template.

### Improving Documentation

- [x] Run `pnpm prettier-fix` to fix formatting issues before opening
the PR.
- [x] Read the Docs Contribution Guide to ensure your contribution
follows the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

Co-authored-by: Delba de Oliveira <[email protected]>
2024-11-07 08:58:43 +00:00

52 lines
1.7 KiB
Plaintext

---
title: Cannot access `Math.random()` while prerendering
---
## 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.
## 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.
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"
import { connection } from 'next/server'
async function ProductsSkeleton() {
...
}
export default async function Page() {
const products = await getCachedProducts();
return <Suspense fallback={<ProductsSkeleton />}>
<DynamicProductsView products={products} />
</Suspense>
}
async function DynamicProductsView() {
await connection();
const randomSeed = Math.random()
const randomizedProducts = randomize(products, randomSeed)
return <ProductsView products={randomizedProducts} />
}
```
## Useful Links
- [`connection` function](https://nextjs.org/docs/app/api-reference/functions/connection)
- [`Suspense` React API](https://react.dev/reference/react/Suspense)