🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): drop query-param writes issued before the Next.js router is ready (#15804)
Nikita Kabardin43b237a58031
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex dd7f2372af..2b49c8196e 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -13,7 +13,7 @@ import { CommandMenuProvider } from "@/src/features/command-k-menu/CommandMenuPrimport { api } from "@/src/utils/api";-import NextAdapterPages from "next-query-params/pages";+import { NextAdapterPagesWithReadyGuard } from "@/src/utils/nextAdapterPagesWithReadyGuard";import { QueryParamProvider } from "use-query-params";import "@/src/styles/globals.css";@@ -145,7 +145,7 @@ const MyApp: AppType<{ session: Session | null }> = ({return (<QueryParamProvider- adapter={NextAdapterPages}+ adapter={NextAdapterPagesWithReadyGuard}options={{ enableBatching: true }}><TooltipProvider>diff --git a/web/src/utils/nextAdapterPagesWithReadyGuard.clienttest.tsx b/web/src/utils/nextAdapterPagesWithReadyGuard.clienttest.tsxnew file mode 100644index 0000000000..9af75dc7aa--- /dev/null+++ b/web/src/utils/nextAdapterPagesWithReadyGuard.clienttest.tsx@@ -0,0 +1,105 @@+import type { Mock } from "vitest";+import { cleanup, render } from "@testing-library/react";+import { useRouter } from "next/router";+import type { QueryParamAdapter } from "use-query-params";++import { NextAdapterPagesWithReadyGuard } from "@/src/utils/nextAdapterPagesWithReadyGuard";++vi.mock("next/router", () => ({+ useRouter: vi.fn(),+}));++afterEach(cleanup);++const ROUTE_PATTERN = "/project/[projectId]/prompts/[[...folder]]";++// Minimal router stand-in: before hydration of a statically-optimized dynamic+// route, `asPath` is still the raw pattern and `isReady` is false.+function makeRouter(isReady: boolean) {+ return {+ isReady,+ pathname: ROUTE_PATTERN,+ asPath: isReady ? "/project/p1/prompts" : ROUTE_PATTERN,+ push: vi.fn(),+ replace: vi.fn(),+ };+}++function renderGuardedAdapter(router: ReturnType<typeof makeRouter>) {+ (useRouter as Mock).mockReturnValue(router);+ let adapter: QueryParamAdapter | undefined;+ render(+ <NextAdapterPagesWithReadyGuard>+ {(a) => {+ adapter = a;+ return null;+ }}+ </NextAdapterPagesWithReadyGuard>,+ );+ if (!adapter) throw new Error("adapter was not provided to children");+ return adapter;+}++describe("NextAdapterPagesWithReadyGuard", () => {+ let warnSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ });++ afterEach(() => {+ warnSpy.mockRestore();+ });++ test("drops replace issued before the router is ready and warns", () => {+ const router = makeRouter(false);+ const adapter = renderGuardedAdapter(router);++ adapter.replace({ search: "?filter=a" });++ expect(router.replace).not.toHaveBeenCalled();+ expect(router.push).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledTimes(1);+ });++ test("drops push issued before the router is ready and warns", () => {+ const router = makeRouter(false);+ const adapter = renderGuardedAdapter(router);++ adapter.push({ search: "?filter=a" });++ expect(router.push).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledTimes(1);+ });++ test("passes writes through unchanged once the router is ready", () => {+ const router = makeRouter(true);+ const adapter = renderGuardedAdapter(router);++ adapter.replace({ search: "?filter=a" });+ adapter.push({ search: "?page=2" });++ expect(router.replace).toHaveBeenCalledTimes(1);+ expect(router.replace).toHaveBeenCalledWith(+ expect.objectContaining({ pathname: ROUTE_PATTERN, search: "?filter=a" }),+ expect.anything(),+ expect.objectContaining({ shallow: true }),+ );+ expect(router.push).toHaveBeenCalledTimes(1);+ expect(warnSpy).not.toHaveBeenCalled();+ });++ test("reads readiness at call time: a write after the isReady flip passes even without a re-render", () => {+ const router = makeRouter(false);+ const adapter = renderGuardedAdapter(router);++ // The pages router is a singleton mutated in place; flip readiness on the+ // same object without re-rendering.+ router.isReady = true;+ adapter.replace({ search: "?filter=a" });++ expect(router.replace).toHaveBeenCalledTimes(1);+ expect(warnSpy).not.toHaveBeenCalled();+ });+});diff --git a/web/src/utils/nextAdapterPagesWithReadyGuard.tsx b/web/src/utils/nextAdapterPagesWithReadyGuard.tsxnew file mode 100644index 0000000000..22c678fbbf--- /dev/null+++ b/web/src/utils/nextAdapterPagesWithReadyGuard.tsx@@ -0,0 +1,58 @@+import NextAdapterPages from "next-query-params/pages";+import { useRouter } from "next/router";+import type {+ PartialLocation,+ QueryParamAdapterComponent,+} from "use-query-params";++/**+ * Wraps the next-query-params pages adapter to drop query-param writes issued+ * before `router.isReady` (Sentry LANGFUSE-5V5 / LANGFUSE-5EM).+ *+ * Before hydration of a statically-optimized dynamic route, `router.asPath`+ * is still the raw pattern (e.g. `/project/[projectId]/prompts/[[...folder]]`)+ * and the query is empty, so a write makes `router.replace`/`push` throw+ * "The provided `href` ... is missing query values" as an unhandled rejection.+ *+ * Dropping (rather than deferring) is deliberate: a pre-ready write computes+ * its new search string against the adapter's pre-ready location, which is+ * `{ search: "" }` — replaying it after hydration would clobber real URL+ * params from deep links. Today such writes never land anyway (the router+ * throws before navigating), so dropping preserves behavior minus the error.+ * Reads are untouched: the adapter's `location` already handles pre-ready+ * state, and post-ready writes pass through unchanged.+ */+export const NextAdapterPagesWithReadyGuard: QueryParamAdapterComponent = ({+ children,+}) => {+ const router = useRouter();++ const guardWrite =+ (method: "push" | "replace", write: (location: PartialLocation) => void) =>+ (location: PartialLocation) => {+ // Read `isReady` at call time, not render time: the pages router is a+ // singleton mutated in place, so a write issued between the readiness+ // flip and the next render is not incorrectly dropped.+ if (!router.isReady) {+ console.warn(+ "[use-query-params] Dropped query param write issued before the Next.js router was ready (dynamic route params are not hydrated yet):",+ method,+ location.search,+ );+ return;+ }+ write(location);+ };++ return (+ <NextAdapterPages>+ {(adapter) =>+ children({+ ...adapter,+ push: guardWrite("push", adapter.push),+ replace: guardWrite("replace", adapter.replace),+ })+ }+ </NextAdapterPages>+ );+};diff --git a/web/vitest.config.mts b/web/vitest.config.mtsindex da5a9962ea..2f086d0c63 100644--- a/web/vitest.config.mts+++ b/web/vitest.config.mts@@ -143,6 +143,17 @@ export default defineConfig({"../packages/shared/src/index.ts",),},+ // next-query-params ships a CJS `pages` entry whose default-export+ // interop breaks when the package is inlined (server.deps.inline+ // below, needed so vi.mock("next/router") intercepts the adapter's+ // own router import). Point at the ESM bundle instead.+ {+ find: /^next-query-params\/pages$/,+ replacement: join(+ import.meta.dirname,+ "node_modules/next-query-params/dist/pages.esm.js",+ ),+ },],// The runtime source resolves Mastra/AG-UI/Bedrock through shared's// node_modules symlinks — a different module id than the test files'@@ -172,7 +183,9 @@ export default defineConfig({testTimeout: 30_000,server: {deps: {- inline: [/@langfuse\//],+ // next-query-params is inlined so vi.mock("next/router") also+ // intercepts the adapter's own router import in clienttests.+ inline: [/@langfuse\//, "next-query-params"],},},projects: [