Next.js Discord

Discord Forum

Getting route from layout

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
Hi all! I'm creating a "blog" system with mdx, and using a layout to surround blog pages. In the layout, the post's title and description are shown.

However, in order to fetch this, I need to get the url path/which mdx file the app is loading. Is there a way to get the path/route in a layout? It needs to be a server component in order to async fetch the page data.

Here's what the fetch function looks like that works, I just need to populate the PAGE_SLUG HERE with the page's slug/the file name that the layout is displaying.

10 Replies

Asiatic LionOP
Would using a template for this instead be better? There's still not much info on route fetching.
Grand Griffon Vendéen
My understanding is that Layout is just another component, so you should be able to use navigation and usePathName() ? https://nextjs.org/docs/app/api-reference/functions/use-pathname
@Grand Griffon Vendéen My understanding is that Layout is just another component, so you should be able to use `navigation` and `usePathName()` ? https://nextjs.org/docs/app/api-reference/functions/use-pathname
Asiatic LionOP
This requires a client component though, I was hoping to stay server-side so that the async function above would still be possible. (that way project/post information like embedded titles is generated on the server side, not with a useEffect after page render)
@Asiatic Lion This requires a client component though, I was hoping to stay server-side so that the async function above would still be possible. (that way project/post information like embedded titles is generated on the server side, not with a useEffect after page render)
Grand Griffon Vendéen
yes, this makes sense. I'm also running into same type of issue. The only solution I found is make the component client-side, place the function in a separate, server-side component, and pass the path into the server side component as a prop. Kind of a headache.
Barbary Lion
hi, i think that this layout idea is for it to be the same accross subroutes, in order to not reload in when navigating inside of the subroutes

so it is not meant to depend on the route itself, you will have to move the layout jsx inside of the page.tsx file

https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#layouts
Layouts
A layout is UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.
Or just some way to put content on every page with a title based on the specific page loaded?
Example image for reference
i think using a dynamic system of importing may be better (ie contentlayer) instead of default mdx loader