How to fix Next.js error: Cannot find module 'next/dist/shared/lib/router-context' or its corresponding type declarations.

by Max Rohde,

I just upgraded Next.js in my Next.js templates from 13.1.1 to 13.5.1 and after upgrading it I encountered the following TypeScript compilation error:

Cannot find module 'next/dist/shared/lib/router-context' or its corresponding type declarations.

The offending code in my case was the following use of RouterContext in the test index.uispec.tsx:

import { RouterContext } from 'next/dist/shared/lib/router-context';

// ...

 render(
    <ThemeProviderPatched theme={theme}>
      <RouterContext.Provider value={{ ...mockRouter }}>
        <Front />
      </RouterContext.Provider>
    </ThemeProviderPatched>
  );

The same issue seems to have been encountered in a number of other projects, eg. #1 and #2.

The fix for this is thankfully very simple. We only need to update the import to:

import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime';
Categories: code