storybook: [Bug]: `@storybook/nextjs` does not work with Next v13.5.1

Describe the bug

After upgrading to Next v13.5.1, @storybook/nextjs fails to start.

Error: Cannot find module 'next/dist/shared/lib/router-context'
Require stack:
- ./node_modules/@storybook/nextjs/dist/preset.js
- ./node_modules/@storybook/core-common/dist/index.js
- ./node_modules/@storybook/telemetry/dist/index.js
- ./node_modules/@storybook/cli/dist/generate.js
- ./node_modules/@storybook/cli/bin/index.js
- ./node_modules/storybook/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at Module._resolveFilename (./node_modules/esbuild-register/dist/node.js:4799:36)
    at Function.resolve (node:internal/modules/cjs/helpers:127:19)
    at scopedResolve (./node_modules/@storybook/nextjs/dist/preset.js:1:9988)
    at addScopedAlias (./node_modules/@storybook/nextjs/dist/preset.js:1:9703)
    at configureRouting (./node_modules/@storybook/nextjs/dist/preset.js:1:13928)
    at Object.webpackFinal (./node_modules/@storybook/nextjs/dist/preset.js:1:29114)
    at async Object.webpack (./node_modules/@storybook/builder-webpack5/dist/presets/custom-webpack-preset.js:1:3214)
    at async starter (./node_modules/@storybook/builder-webpack5/dist/index.js:1:4658)
    at async Module.start (./node_modules/@storybook/builder-webpack5/dist/index.js:1:8521)
    at async storybookDevServer (./node_modules/@storybook/core-server/dist/index.js:101:8374)
    at async buildDevStandalone (./node_modules/@storybook/core-server/dist/index.js:116:3013)
    at async withTelemetry (./node_modules/@storybook/core-server/dist/index.js:101:4155)
    at async dev (./node_modules/@storybook/cli/dist/generate.js:471:401)
    at async Command.<anonymous> (./node_modules/@storybook/cli/dist/generate.js:473:225)

To Reproduce

Upgrade Next to latest v13.5.1. Install latest of @storybook/nextjs, v7.4.2.

System

Environment Info:

  System:
    OS: macOS 13.5.2
    CPU: (10) arm64 Apple M1 Pro
  Binaries:
    Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node
    npm: 9.8.1 - ~/.nvm/versions/node/v18.17.1/bin/npm
  Browsers:
    Chrome: 116.0.5845.187
    Edge: 117.0.2045.35
    Safari: 16.6
  npmPackages:
    @storybook/addon-a11y: ~7.4.2 => 7.4.2 
    @storybook/addon-coverage: ~0.0.9 => 0.0.9 
    @storybook/addon-designs: ~7.0.5 => 7.0.5 
    @storybook/addon-essentials: ~7.4.2 => 7.4.2 
    @storybook/addon-interactions: ~7.4.2 => 7.4.2 
    @storybook/addon-links: ~7.4.2 => 7.4.2 
    @storybook/addon-styling: ~1.3.7 => 1.3.7 
    @storybook/blocks: ~7.4.2 => 7.4.2 
    @storybook/manager-api: ~7.4.2 => 7.4.2 
    @storybook/nextjs: ~7.4.2 => 7.4.2 
    @storybook/react: ~7.4.2 => 7.4.2 
    @storybook/testing-library: ^0.2.1 => 0.2.1 
    @storybook/theming: ~7.4.2 => 7.4.2

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 9 months ago
  • Reactions: 40
  • Comments: 61 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Hey everyone! Thanks for reporting this, we know about the regression and are currently working on a fix for it. We will release it as soon as we can today.

updated my package.json to

"dependencies": {
    "next": "13.4.19",
  },

removed the ^ and did a yarn install and it works

After updating the import statement from import { RouterContext } from 'next/dist/shared/lib/router-context'; to import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime'; fixed the issue for me.

I’m in the process of doing a patch-release, with this fix in.

I would like to add one more thing since I wasn’t able to fix the error using the described methods in this issue. Even after upgrading and re-initializing, the error still occurred once I restored my configuration.

It kept failing with:

Module not found: Error: Can't resolve 'next/dist/shared/lib/router-context' in './node_modules/@storybook/nextjs/dist'

or:

Module not found: Error: Can't resolve 'next/dist/shared/lib/head-manager-context' in './node_modules/@storybook/nextjs/dist'

Turned out I had an error in my main.ts regarding the alias configuration, where I forgot to retain the alias from the original configuration:

    /* (...) */
    config.resolve = {
      ...config.resolve,
      ...{
        alias: {
+         ...config.resolve?.alias,
          '@': [path.resolve(__dirname, '../src/')]
        },
        /* (...) */
      }
    }
    /* (...) */

I can’t remember if this was an old example from the documentation or if I just forgot it in the first place, but it didn’t seem to be a problem in earlier versions.

I hope this helps someone else who made the same mistake.

If anyone on 12.x versions ends up here from seeing the error:

Error: Cannot find module ‘next/dist/shared/lib/app-router-context’

I see it (without possible resolution) on 12.1.5 and 12.1.6. It is fixable in 12.1.7-canary.8 (with a variant of the error, Module not found: Error: Can't resolve 'next/dist/shared/lib/router-context.shared-runtime') with the following webpack config in .storybook/main.js:

  webpack: (config) => {
    config.resolve = config.resolve || {};
    config.resolve.modules = config.resolve.modules || [];
    config.resolve.alias = {
      ...config.resolve.alias,
      "next/dist/shared/lib/router-context.shared-runtime":
        "next/dist/shared/lib/router-context",
      "next/dist/shared/lib/head-manager-context.shared-runtime":
        "next/dist/shared/lib/head-manager-context",
    };
    return config;
  },

The issue also does not appear at all (no configuration needed) in 12.3.3, which I was able to upgrade directly to, but YMMV there.

Just want to drop a note of thanks to the storybook team: thanks for looking into this bug in such a timely manner! After upgrading storybook-related dependencies to 7.4.3, I can verify that it works perfectly with next@13.5.2 🎊 g

I can confirm that the newly published version of 7.4.3 of Storybook and all of its addons has fixed the issue.

To be clear, I was not doing anything special with the Router context within Storybook and Next is being used simply to build components that can utilize things such as next/font, next/image, and next/link. It seems like there are more advanced use-cases being reported here as well. However, the simple act of using @storybook/nextjs as the framework was fixed in the patch that was pushed.

IMO, the advanced use-cases being defined here need a solid reproduction repo and likely a new issue to address them.

I’m still having error: Module not found: Error: Can’t resolve ‘next/dist/shared/lib/router-context’ “next”: “13.5.4-canary.8” “storybook”: “7.4.5”

same its not mentioned anywhere in my repo

next/dist/shared/lib/router-context

What file did you change? next/dist/shared/lib/router-context'; doesn’t seem to be referenced anywhere in the nextjs repo

The issue was fixed for me with npm upgrade @storybook/nextjs

Thanks!

As many people have mentioned in https://github.com/vercel/next.js/issues/55620, the error below is seen when upgrading either Storybook to 7.4.3+ and/or upgrading Next.js to 13.5+.

Error: Can't resolve 'react-dom/test-utils' in '...node_modules/@testing-library/react/dist/@testing-library'

@shilman can we reopen this issue and investigate further?

working for me on

"next": "^13.5.6",
"@storybook/nextjs": "^7.6.3",

I was still having issues, so I upgraded Storybook, even re-init’d it, but still had the problem.

However, somehow in the end what worked was making sure to run yarn upgrade @storybook/addon-actions @storybook/addon-essentials @storybook/addon-interactions @storybook/addon-links @storybook/addon-onboarding @storybook/addon-postcss @storybook/addon-styling @storybook/blocks @storybook/nextjs @storybook/react @storybook/testing-library ended up sorting my issue somehow.

I also have a bit more customization in my main.ts file, in case this helps anyone in the future:

import * as path from "path"

import type { StorybookConfig } from "@storybook/nextjs"
const config: StorybookConfig = {
  stories: ["../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-onboarding",
    "@storybook/addon-interactions",
    "@storybook/addon-styling",
    {
      name: "@storybook/addon-styling",
      options: {
        postCss: {
          implementation: require.resolve("postcss"),
        },
      },
    },
  ],
  framework: {
    name: "@storybook/nextjs",
    options: {
      nextConfigPath: path.resolve(__dirname, "../next.config.js"),
    },
  },
  docs: {
    autodocs: "tag",
  },
  typescript: {
    reactDocgen: false,
  },
  staticDirs: [
    "../public",
    {
      from: "../public/fonts",
      to: "public/fonts",
    },
    {
      from: "../public/fonts",
      to: "fonts",
    },
  ], //👈 Configures the static asset folder in Storybook
}
export default config

Hope this helps anyone else who was struggling to get this working. It also meant my Chromatic Workflow worked again, so we’re solid. Thank you everyone for pushing this update so quickly, great work!

Hei, Thanks for the quick response and patch, but it’s still the same with Release: Patch 7.4.3 #24209. 😦 image

I encountered the same problem again with the LTS version of Node (18.x):

SB_BUILDER-WEBPACK5_0002 (WebpackInvocationError): Module not found: Error: Can't resolve 'next/dist/shared/lib/router-context' in './.storybook'

With Node 20 I was able to resolve the error using the fix I described here: https://github.com/storybookjs/storybook/issues/24234#issuecomment-1730209029

For the LTS version I had to explicitly add the following to my alias configuration in main.ts:

    /* (...) */
    config.resolve = {
      ...config.resolve,
      ...{
        alias: {
          ...config.resolve?.alias,
+         'next/dist/shared/lib/router-context': 'next/dist/shared/lib/router-context.shared-runtime',
          '@': [path.resolve(__dirname, '../src/')]
        },
        /* (...) */
      }
    }
    /* (...) */

Depending on the installed Version of Next this can be different according to:
https://github.com/storybookjs/storybook/blob/855ab5faadb13b22b36bb2dbae304ebbb099d34d/code/frameworks/nextjs/src/dependency-map.ts#L1-L36

I have not yet paid closer attention to why the alias was not registered in the first place.

Error: Can't resolve 'react-dom/test-utils' in '...node_modules/@testing-library/react/dist/@testing-library'

I’m seeing this too with the latest stable versions of both Next and Storybook (as of today)

I updated storybook deps and this was not resolving my problem. I am using next-router-mock and this has the direct import of next/dist/shared/lib/router-context

What worked for me, and I am not happy with that, was adding to main.js a new alias like below:

config.resolve.alias = {
      ...(config.resolve.alias ?? {}),
     /* ... */
      'next/dist/shared/lib/router-context': require.resolve(
        './router-context.js'
      ),
    };`

and created in the same folder file router-context.js with content is taken form previous nextjs version:

"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "RouterContext", {
    enumerable: true,
    get: function() {
        return RouterContext;
    }
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const RouterContext = _react.default.createContext(null);
if (process.env.NODE_ENV !== "production") {
    RouterContext.displayName = "RouterContext";
}

//# sourceMappingURL=router-context.js.map

Guys, it works again. You have to remove previously generated files and re-run it. For me , since I was generating it again, just did the “npx create-next-app@latest” (or just go to your current project without storybook in it) and then “npx storybook@latest init”. It works, thanks for solving it so quickly!

Thank you very much for fixing this so fast! A patch within 24 hours is not the norm and definitely great reaction time.

After updating the import statement from import { RouterContext } from 'next/dist/shared/lib/router-context'; to import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime'; fixed the issue for me.

I thought we didn’t need that line anymore?

Does your preview file look something like this? I still see the issue.

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

const preview = {
  parameters: {
    nextRouter: {
      Provider: RouterContext.Provider,
    },
    nextjs: {
      router: {
        path: '/',
        asPath: '/',
        query: {},
      },
    },
  },
};

export default preview

@hwride Just fyi: We will drop Next.js < v13.5 support in Storybook 8. Upgrading Next.js to 13.5 or higher will very likely fix the issue.

I found the root cause of the error below: Error: Can't resolve 'react-dom/test-utils' in '...node_modules/@testing-library/react/dist/@testing-library'

The default Webpack configuration of Storybook resolves react-dom to @storybook/react-dom-shim, which doesn’t have a shim for test-utils. I managed to resolve this by overriding the Webpack config in .storybook/main:

  webpackFinal: async (config) => {
    config.resolve = config.resolve || {};
    config.resolve.alias = config.resolve.alias || {};
    config.resolve.alias["@testing-library/react"] = "@storybook/testing-library";
// OR
	config.resolve.alias["react-dom"] = "react-dom";
    return config;
  },

I think the right fix here would be to add a test-utils shim in @storybook/react-dom-shim, I’m opening a new issue to track that.

Still having the same problem even with all dependencies to 7.4.6 ModuleNotFoundError: Module not found: Error: Can't resolve 'next/dist/shared/lib/router-context' in './node_modules/@storybook/nextjs/dist'

Thanks, updating all storybook modules fixed it!!!

Thank you for the positive feedback @vitorsbmendes @Tottzi

Okay, I had to fire an npm upgrade @storybook/nextjs so it went forward, but other issue came up. I’ll report it in other place. 😃

I have run the following reproduction:

  • I run yarn create next-app
  • Follow the guide of the next CLI, and chose all the default options
  • I cd into the my-app directory
  • I run npm storybook@latest init
  • I go though the storybook CLI and chose all the default options
  • I run yarn storybook
  • The browser opens, everything looks good
  • I run yarn build-storybook
  • I host the storybook-static directory
  • I open it in my browser, everything looks good.

I conclude that can’t reproduce this anymore myself on my machine on sb 7.4.3.

If this problem indeed does persist, I’d need more help, there might be something I’m missing.

I re-installed the storybook. And regenerated the lock-files. Still the same.

@shilman this workaround does not work. this is a sev1 issue. I want to update next to 13.5.1 asap image