Skip to content

usePathname returns invalid value on SSR #688

@matej-io

Description

@matej-io

The app router usePathname() hook in client component causes hydration error because the value on server render is always just '/' but on client is actual correct current path.

Minimal example code would be:

'use client'

import { usePathname } from 'next/navigation'

export default function UsePathname() {
  const pathname = usePathname()
  console.log(pathname)
  return <div>{pathname}</div>
}

Browser console output:

[Log] pathname check – "/" (page.tsx, line 9)
[Log] pathname check – "/use_pathname" (page.tsx, line 9)
[Error] Error: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:

- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it along with the HTML.
- Invalid HTML tag nesting.

It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.

https://react.dev/link/hydration-mismatch

  <LayoutSegmentProvider childSegments={[...]}>
    <link>
    <RemoveDuplicateServerCss>
    <default>
      <RootLayout>
        <html lang="en" className="__variable...">
          <body className="min-h-full...">
            <meta>
            <title>
            <meta>
            <meta>
            <LayoutSegmentProvider childSegments={[...]}>
              <UsePathname params={Promise} searchParams={Promise}>
                <div>
+                 /
-                 /use_pathname

	reportError (react-dom_client.js:2967)
	defaultOnRecoverableError (react-dom_client.js:5276)
	runWithFiberInDEV (react-dom_client.js:850:132)
	flushSpawnedWork (react-dom_client.js:8740)
	commitRoot (react-dom_client.js:8584)
	commitRootWhenReady (react-dom_client.js:8078)
	performWorkOnRoot (react-dom_client.js:8050)
	performWorkOnRootViaSchedulerTask (react-dom_client.js:9058)
	performWorkUntilDeadline (react-dom_client.js:35)

I'm attaching minimal project with above code example.
Once vinext server is running (pnpm dev:vinext) open http://localhost:3001/use_pathname to reproduce the issue.

my-app.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions