Next.js Discord

Discord Forum

Way to query app router / slug from a parent component outside of my route?

Unanswered
American Crocodile posted this in #help-forum
Open in Discord
American CrocodileOP
Currently I have a Next.js 13 application set up using the app router structure.

I have a <Header> component that wraps my whole application in layout.tsx and handles things like authentication state. However because of my structure I need a way to know that I'm on a given subroute so that I can give access permissions.

Let me give a more concrete example:

I'm at localhost:3000, currently there is no need to know what route / slug I'm at, but I still might be logged into the application

I'm at localhost:3000/username

I now need to know what username is to do some logic (ie verify the username and logged in user are the same and give them access to certain views on that subroute that they should not be able to see on localhost:3000/username2).

My assumption was that I could just hook into the slug from Header, but with app it seems like I need to prop drill my params all the way down to get this information. Is there a better way to do this?

1 Reply

Unless your layout is under a dynamic route, you must use the usePathname hook (or useParams) from a client component.

https://nextjs.org/docs/app/api-reference/functions/use-pathname