Next.js Discord

Discord Forum

Get pathname in server page components

Answered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I am building a website builder. The database stores my pages as something like this:

{
  "name": "About Faq",
  "slug": "/about/faq",
  "content": [
      "pageContentHere": "..."
   ]
}


The next.js app that should display the pageContent has a top level dynamic page which should somehow get to what path a user has navigated to. So when the user goes to www.example.com/about/faq I need to somehow extract the /about/faq in server components to fetch the web page from the database.

In client components I can use usePathname() hook but is there something equivalent to it in server components/server pages.

I know that I can get /about from www.example.com/about using params but I would also like to allow nested routes.
Answered by joulev
Use a catch all dynamic route segment. Ignore any suggestions on getting the pathname in server components because you are not supposed to/cannot get pathname in server components. You can only get the dynamic param values and hence: catch all dynamic params
View full answer

10 Replies

https://www.propelauth.com/post/getting-url-in-next-server-components


Try this out. It's a good article and goes through all the possible stuff you can do :)
Sun bearOP
Thank you
is there a way without the use of middleware?
Answer
Sun bearOP
Thank you all
@B33fb0n3 yes, or directly do this: https://discord.com/channels/752553802359505017/1296784053428813886/1296790537688580107
This only helps with the domain, which is still important for multi tenant apps but not what the OP is looking for. “/about/faq” doesn’t match [slug], it matches […slug]
@joulev This only helps with the domain, which is still important for multi tenant apps but not what the OP is looking for. “/about/faq” doesn’t match [slug], it matches […slug]
I just tried to match his data structure. You are right, the / would be translated to a new route segment so he need to have a [...slug], yea