Skip to content

Component caching with Math.random in openapi-fetch #2486

@thebuilder

Description

@thebuilder

Description

Currently openapi-fetch use Math.random to generate a id for middleware requests. This however, conflicts with caching of Next.js server components.
https://nextjs.org/docs/messages/next-prerender-random

This doesn't currently throw an error, but as soon as you enable the new use cache or cacheComponents functionality, Next.js will throw an error if reading Math.random in a cached component. I believe the feature is planned for release in Next.js 16, so might as well be prepared.

Proposal

The simplest fix I can see, is to follow their recommendation and add use cache to randomId function. This will also require it to be converted into an async method, but that shouldn't be an issue (since everything is already async).

export async function randomID() {
  'use cache';
  return Math.random().toString(36).slice(2, 11);
}

Update: On further testing, this will be a solution - Running without useCache enabled, will throw an error if you are using use cache.

To use "use cache", please enable the experimental
 feature flag "useCache" in your Next.js config.

Is there another way around this issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions