Next.js Discord

Discord Forum

Get current route (like '/users/[userId]/profile') in a client/server component?

Unanswered
Clay-colored Sparrow posted this in #help-forum
Open in Discord
Clay-colored SparrowOP
Hello, Next.js contributors!

Let's consider an App-router application.

I have a use case where I need to apply some logic before entering and after leaving a route. This logic depends not on the specific pathname, but rather on a route itself. Like '/users/[userId]/profile'.
usePathname returns actual pathname like '/users/123/profile', not the route. And it is 'use client' only.

Of course, for a specific route I could put some logic into the route's layout.tsx. But I'd like to handle this in the root layout.

Also, I could match a route with a regex. But since the route-matching logic is already present in the app router, is there any chance I can get current matched route in my .tsx files?

Thanks a lot!

5 Replies

In a client component just use usePathname https://nextjs.org/docs/app/api-reference/functions/use-pathname if in a server component create a headers instance and get the referer property from it
Just use JavaScript to detect whether or not if it is the correct format of /users/[userId]/profile
Clay-colored SparrowOP
Thank you, @Jesse and @Ray !

Jesse, yes, I think it is currently the only option - to use url matcher of some kind. My hope was, since this information is known at build time, that it could be somehow available.

Ray, I need it for two purposes on the client side. First is route guards. Another is related to global state. Once I enter some routing context, I want to initiate loading of some resource from API. And when leaving the routing context - I want to clean up. You can think of a routing context as some part of the app that deals with the same entity (user, project, customer, order).