How to access router.asPath in a function that uses next/navigation in the Next.js app directory? – Next.js

by
Ali Hasan
next.js reactjs

Quick Fix: In Next.js 13’s new app directory scheme, useRouter doesn’t work the same way. You will want usePathname instead: https://beta.nextjs.org/docs/upgrade-guide#step-5-migrating-routing-hooks

The Problem:

The Next.js app directory provides the useRouter hook from next/navigation to access routing information. However, when trying to access the router.asPath property within a function that uses next/navigation, the value is undefined. How can I access the router.asPath property in this scenario?

The Solutions:

Solution 2: using usePathname()

To access the router’s current pathname, you can use the `usePathname` hook provided by `next/navigation`. Here’s an example:

import { usePathname } from 'next/navigation';

export default function ExampleComponent() {
  const pathname = usePathname();
  return <p>Current pathname: {pathname}</p>;
}

Note that usePathname is a client-side hook, so it can only be used in components that are rendered on the client.

Q&A

How to access router.asPath in a function that uses next/navigation in the Next.js app directory?

In Next.js 13’s new app directory scheme, useRouter doesn’t work the same way. You will want usePathname instead:

How to solve the issue if router.asPath is not accessible within a function?

Make sure to import the correct module. If you’re using the app directory, import from next/navigation. Otherwise, import from next/router.

Is there an alternative to next/router?

Yes, you can use usePathname from next/navigation instead.

Video Explanation:

The following video, titled "Next.js App Router: Routing, Data Fetching, Caching - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

leerob, VP of Developer Experience at Vercel, explains new concepts and foundations of Next.js app router, including layouts, dynamic routes ...