next.js: SyntaxError: Named export 'useRouter' not found

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
Binaries:
  Node: 16.17.0
  npm: 8.15.0
  Yarn: 1.22.19
  pnpm: 7.1.0
Relevant packages:
  next: 13.3.2-canary.3
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

No response

Link to the code that reproduces this issue

https://codesandbox.io/p/sandbox/nextjs-router-esm-qoquxr?file=%2Fpages%2Findex.tsx

To Reproduce

  1. Open the sandbox: https://codesandbox.io/p/sandbox/nextjs-router-esm-qoquxr?file=%2Fpages%2Findex.tsx
  2. Observe the following error on the home page:
Server Error
SyntaxError: Named export 'useRouter' not found. The requested module 'next/router.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'next/router.js';
const { useRouter } = pkg;
  1. Downgrade next version to 13.3.0 and the error goes away.

Describe the Bug

It appear that the release 13.3.1 includes certain changes to the named exports, so the following import no longer works in ESM:

import { useRouter } from "next/router.js";

The above code produces the following error:

Server Error
SyntaxError: Named export 'useRouter' not found. The requested module 'next/router.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'next/router.js';
const { useRouter } = pkg;

A use-case for ESM import is a 3rd-party ESM-only component library that uses next/router.

Expected Behavior

Named exports should work in ESM as they used to prior to 13.3.1.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 17 (15 by maintainers)

Commits related to this issue

Most upvoted comments

@CobyPear, it may be worth opening a separate ticket with specific example(s) as the issue described in this ticket was fixed in 13.3.2

I believe this problem is caused by swc new module transformer which was introduced by this PR: https://github.com/swc-project/swc/pull/4758

cc @kdy1 @magic-akari