Next.js Discord

Discord Forum

How to get current route "id"?

Unanswered
Pachon Navarro posted this in #help-forum
Open in Discord
Pachon NavarroOP
Page useRouter provided route field which provided current route, which comes handy for dynamic page, such as checking if sidebar item is active.

How can this be achieved in app router using the new router from next/navigation since this field is no longer provided..?

import { useRouter } from 'next/router';

const router = useRouter();
const isSidebarItemActive = router.route === '/blog/[slug]';

17 Replies

if you want that slug serverside then await the props.params
and if you want it client side, either pass it in props or use useParams hook
Pachon NavarroOP
Not sure if I can understand. The goal I am trying to achieve is to detect if user is on some sort of dynamic page (in this example blog detail).

Previously I could get it from router.route which returned page route id and then I could compare it as router.route === '/blog/[slug]' // you are on blog detail.

This is no longer possible in app router, so I am asking, what are the other approaches to achieve this.
An alternative could be to use useSelectedLayoutSegments probably, from what I found during the research..
I mean if the page.tsx inside blog/[slug] is triggered, then that means user is indeed on blog detail page
if the triggered page.tsx is inside blog then user is still on blog list page(if any)
Pachon NavarroOP
Yeah, but not in the global layout context where the sidebar is.
ahhh
you can usePathname which gives you the exact path the current user is on
you can then run a String.replace on it
Pachon NavarroOP
Can you? How do you know what to replace and replace it with what?
running a .replace("/blog","") would give you the /slug
if that result of replace is empty, user is on blog list else on blog detail
Pachon NavarroOP
Yeah, this satisfies this current case, but let's say you have ultra dynamic route with multiple slugs (which may be same on multi level case) where you don't know what to replace with what..

But gotcha, if nothing like this no longer exists. I will try to tweak is to make it suit my use case..
you can try the hook you found but I haven't used it so I cannot comment on it
Pachon NavarroOP
it splits the path in following array ['blog', 'your-slug'], so it's doable by maybe filtering out params..
But thank you anyway thought