amannn/next-query-params

Running Under `NODE_ENV=test` Errors with "NextRouter was not mounted"

nbibler opened this issue · 4 comments

Describe the bug

Standing up a new NextJS application, using the Pages router, adding this library, and running under NODE_ENV=test errors immediately with:

Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

Object.useRouter         in /node_modules/next/dist/client/router.js  (146:15)
exports.NextAdapterPages in /node_modules/next-query-params/dist/NextAdapterPages-b4b86ccd.js (1:293)

This does not appear to be an issue when NODE_ENV=development nor NODE_ENV=production (via npm run build && NODE_ENV=production npm run start.

To Reproduce

  1. npx create-next-app@13.5.6, do not use the App Router and switch into the new directory,
  2. npm install --save next-query-params use-query-params,
  3. Modify the _app.tsx to:
 import '@/styles/globals.css'
 import type { AppProps } from 'next/app'
+import NextAdapterPages from "next-query-params/pages";
+import { QueryParamProvider } from "use-query-params";
 
 export default function App({ Component, pageProps }: AppProps) {
-  return <Component {...pageProps} />
+  return (
+    <QueryParamProvider adapter={NextAdapterPages}>
+      <Component {...pageProps} />
+    </QueryParamProvider>
+  );
 }
  1. Run the app under NODE_ENV=test npm run dev

Expected behavior

There should not be a NextRouter error and the application should display the generic NextJS welcome page.

This error also occurs in NextJS 14.0.1 using the same steps provided above, but with npx create-next-app@latest using the Pages router.

Hi @nbibler,

I was experiencing the same issue. I fixed it by upgrading the following packages:

"next-query-params": "^5.0.0",
"use-query-params": "^2.2.1"

Note: I'm using "next": "14.0.4".

I'm having this issue even with the above versions mentioned by @n-d-r-d-g

This doesn't just happen with NODE_ENV=test. @n-d-r-d-g 's suggestion doesn't fix. We're on next@14.1.0 and next-query-params@5.0.0

Seems router.isReady should checked before using the router here:

const match = router.asPath.match(pathnameRegex);

Our workaround is currently to use a custom wrapper around QueryParamProvider like this:

export const NextQueryParamProvider = ({ children }) => {
  const router = useRouter()

  return router.isReady ? (
    <QueryParamProvider adapter={NextAdapterPages} options={{ removeDefaultsFromUrl: true }}>
      {children}
    </QueryParamProvider>
  ) : children
}

Hopefully we'll have time to submit a PR. Thanks for a very useful library @amannn !