Skip to content

Next.js: Return mocked router instead of actual router in useRouter #32131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

JulioJ11
Copy link
Contributor

@JulioJ11 JulioJ11 commented Jul 27, 2025

Closes #30390

What I did

Modified the useRouter export in the Next.js navigation mock to return the mocked navigationAPI instead of the actual Next.js router. This prevents Link components in Next.js 15 from breaking out of the Storybook context when clicked.

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!

Manual testing performed:

  • Set up local Storybook development environment with Next.js framework
  • Created a test story with Next.js 15 Link component pointing to non-existent route
  • Configured story with appDirectory: true to use App Router
  • Verified that clicking the Link component now stays within Storybook context instead of navigating to "Not Found" page
  • Confirmed that the mocked router is returned when useRouter() is called

To test this fix:

  • Run a sandbox for Next.js template: yarn task --task sandbox --template nextjs/default-ts
  • Create a story with a Next.js Link component that navigates to a non-existent route
  • Set appDirectory: true in story parameters
  • Click the Link component - it should now stay within Storybook instead of showing "Not Found"

-->

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

No documentation updates required - this is an internal bug fix that restores expected behavior.

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This pull request has been released as version 0.0.0-pr-32131-sha-cac9c086. Try it out in a new sandbox by running npx [email protected] sandbox or in an existing project with npx [email protected] upgrade.

More information
Published version 0.0.0-pr-32131-sha-cac9c086
Triggered by @valentinpalkovic
Repository JulioJ11/storybook
Branch fix/nextjs-15-link-component
Commit cac9c086
Datetime Mon Aug 11 11:34:50 UTC 2025 (1754912091)
Workflow run 16878848009

To request a new release of this pull request, mention the @storybookjs/core team.

core team members can create a new canary release here or locally with gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=32131

Greptile Summary

This PR fixes a critical issue in Next.js 15 where Link components would navigate outside of Storybook stories to actual routes, causing "Not Found" errors. The fix modifies the useRouter export in the Next.js navigation mock (code/frameworks/nextjs/src/export-mocks/navigation/index.ts) to return the mocked navigationAPI instead of the actual Next.js router.

Previously, useRouter was implemented as a passthrough mock that called the real Next.js router implementation. This worked in earlier versions but broke with Next.js 15's changes to the Link component behavior. The new implementation returns the mock navigationAPI object when available, ensuring all navigation actions (push, replace, forward, back, prefetch, refresh) stay within the Storybook context.

This change integrates seamlessly with the existing navigation mock system, which already provides the navigationAPI object through the createNavigation function and manages mock lifecycle through getRouter. The fix maintains the same error handling pattern used elsewhere in the mock system by throwing NextjsRouterMocksNotAvailable when mocks aren't initialized.

Confidence score: 4/5

• This fix addresses a clear regression and follows established patterns in the codebase
• The solution is targeted and minimal, changing only the problematic useRouter implementation
• Needs manual testing verification since automated test coverage is incomplete

- Modified useRouter export to return navigationAPI mock
- Prevents the Link components from using the real Next.js router
- Addresses Next.js 15 Link navigation issue in Storybook
- Fixes storybookjs#30390
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link

nx-cloud bot commented Aug 11, 2025

View your CI Pipeline Execution ↗ for commit cac9c08

Command Status Duration Result
nx run-many -t build --parallel=3 ✅ Succeeded 1m 10s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-11 12:01:14 UTC

@valentinpalkovic valentinpalkovic changed the title Fix: return mocked router instead of actual router in useRouter Next.js: Return mocked router instead of actual router in useRouter Aug 11, 2025
@valentinpalkovic valentinpalkovic added the patch:yes Bugfix & documentation PR that need to be picked to main branch label Aug 11, 2025
@valentinpalkovic valentinpalkovic merged commit f0d9efe into storybookjs:next Aug 11, 2025
57 of 65 checks passed
@storybook-pr-benchmarking
Copy link

Package Benchmarks

Commit: cac9c08, ran on 11 August 2025 at 12:54:21 UTC

The following packages have significant changes to their size or dependencies:

@storybook/addon-docs

Before After Difference
Dependency count 12 12 0
Self size 2.47 MB 2.42 MB 🎉 -53 KB 🎉
Dependency size 8.93 MB 8.93 MB 🎉 -14 B 🎉
Bundle Size Analyzer Link Link

storybook

Before After Difference
Dependency count 51 51 0
Self size 41.75 MB 41.37 MB 🎉 -387 KB 🎉
Dependency size 18.13 MB 18.13 MB 🎉 -2 B 🎉
Bundle Size Analyzer Link Link

sb

Before After Difference
Dependency count 52 52 0
Self size 1 KB 1 KB 🚨 +12 B 🚨
Dependency size 59.89 MB 59.50 MB 🎉 -387 KB 🎉
Bundle Size Analyzer Link Link

@storybook/cli

Before After Difference
Dependency count 220 220 0
Self size 585 KB 585 KB 🚨 +13 B 🚨
Dependency size 104.39 MB 103.99 MB 🎉 -394 KB 🎉
Bundle Size Analyzer Link Link

@storybook/codemod

Before After Difference
Dependency count 189 189 0
Self size 31 KB 31 KB 🎉 -2 B 🎉
Dependency size 88.46 MB 88.08 MB 🎉 -387 KB 🎉
Bundle Size Analyzer Link Link

yannbf pushed a commit that referenced this pull request Aug 11, 2025
Next.js: Return mocked router instead of actual router in useRouter

(cherry picked from commit f0d9efe)
@github-actions github-actions bot added the patch:done Patch/release PRs already cherry-picked to main/release branch label Aug 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug ci:normal nextjs patch:done Patch/release PRs already cherry-picked to main/release branch patch:yes Bugfix & documentation PR that need to be picked to main branch Stale
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: Next.js Link component causes navigation to a non-existent page in stories
2 participants