Files
next.js/errors/next-prerender-random.md
T
Josh StoryandGitHub f93d8178ea [dynamicIO] Error in dev when using sync platform APIs that are dynamic (#71346)
stacked on #71345 

When dynamicIO is enabled certain platform APIs that provide access to
outside state like randomness and current time are augmented to bail out
of prerendering. When running in Dev there is no true Prerender but we
still want to communicate to the developer when they are using APIs that
might not work as they intend in Production. This change adds warnings
when you use these platform APIs during the Prerender portion of the dev
render.
2024-10-16 15:18:49 -07:00

1.7 KiB

title
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:

export default async function Page() {
  const products = await getCachedProducts()
  const randomSeed = Math.random()
  const randomizedProducts = randomize(products, randomSeed)
  return <ProductsView products={randomizedProducts} />
}

After:

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} />
}