Next.js Discord

Discord Forum

Get pathname in server page components

Answered
American black bear posted this in #help-forum
Open in Discord
Avatar
American black 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

Avatar
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 :)
Avatar
American black bearOP
Thank you
is there a way without the use of middleware?
Avatar
for that you need a solid middleware. Why?

The middleware rewrites the path so it looks normal for your user, but your app can handle it in the background.
So you want to setup a good middleware, that does that. It could look [like this](https://github.com/vercel/platforms/blob/main/middleware.ts).

And then you can work with your dynamic routes as you said: (see attached)
Image
Avatar
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
Answer
Avatar
American black bearOP
so I can do this and then join the slug array with "/"?
Image
Avatar
American black bearOP
Thank you all
Avatar
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]
Avatar
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
Image