Component caching with Math.random in openapi-fetch
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?
Maybe the createClient options could be expanded to include a randomID or generateMiddlewareId option, allowing the user to override the default.
For now I have fixed it locally with a pnpm patch:
diff --git a/dist/index.cjs b/dist/index.cjs
index bbd6d4e05368d402387ea621ca7571e5ba01f571..d27acca3330e8f5784408d7abbbfe956b8cf636a 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -6,7 +6,8 @@ const PATH_PARAM_RE = /\{[^{}]+\}/g;
const supportsRequestInitExt = () => {
return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
};
-function randomID() {
+async function randomID() {
+ 'use cache';
return Math.random().toString(36).slice(2, 11);
}
function createClient(clientOptions) {
diff --git a/dist/index.mjs b/dist/index.mjs
index 724ebef59d87aa57d240b233c73f6922ac609007..224343627ea2a11c772af639abc9f44682ec9238 100644
--- a/dist/index.mjs
+++ b/dist/index.mjs
@@ -2,7 +2,8 @@ const PATH_PARAM_RE = /\{[^{}]+\}/g;
const supportsRequestInitExt = () => {
return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
};
-function randomID() {
+async function randomID() {
+ 'use cache';
return Math.random().toString(36).slice(2, 11);
}
function createClient(clientOptions) {
diff --git a/src/index.js b/src/index.js
index 261f5b147db1d93e0d7be08825e13e612aa2b8e2..ea2f914f44e683f3784181921df59969267a4b98 100644
--- a/src/index.js
+++ b/src/index.js
@@ -13,7 +13,8 @@ const supportsRequestInitExt = () => {
* Returns a cheap, non-cryptographically-secure random ID
* Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)
*/
-export function randomID() {
+export async function randomID() {
+ 'use cache';
return Math.random().toString(36).slice(2, 11);
}
The same issue