Next.js Discord

Discord Forum

How can I get previous route?

Unanswered
Common carp posted this in #help-forum
Open in Discord
Common carpOP
Hi guys, How can I get previous route? I have tried to access asPath property inside useRouter but it returns undefined

11 Replies

Are you working with App route?
import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  // Access the previous route using router.query._next
  const previousRoute = router.query._next;

  return (
    <div>
      <p>Current Route: {router.pathname}</p>
      <p>Previous Route: {previousRoute}</p>
    </div>
  );
}

export default MyComponent;

I hope it will work for you
Common carpOP
I'm facing this error "NextRouter was not mounted". I have tried to search on gg. It said I should import useRouter from next/navigation
But useRouter in next/navigation does not have query property
are you working with app route?
Common carpOP
Yes, i'm currently working with app route
American black bear
can you give me the structure of your project ? I mean where you have coded thid code in your project and in which file?

Mostly this error occur if you attempt to use useRouter outside of a page component/App component or within the _document file, you might encounter the "NextRouter was not mounted" error.

So tell me how is your project structured and then I will be able to help you though.
Common carpOP
Yes, I'm use it outside of app folder. Is there anyway to fix it ?
Common carpOP
app/product/page.tsx
components/ProductDetail.tsx
I use useRouter in ProductDetail component and I put ProductDetail inside page.tsx
Common carpOP
I have tried to use it inside page.tsx but i sitll face that error
American black bear
show me the whole code Product-detail and product/page.tsx