Next.js Discord

Discord Forum

URL on server side?

Answered
StilauGamer posted this in #help-forum
Open in Discord
Avatar
Is there a way to get the current path on server side?

Basically get the domain.com/ -->dashboard/test<--, and use this somewhere on your site?
I know its possible through Client Comps with usePathname, but is it possible through server side?
Answered by StilauGamer
Solution:

import { headers } from "next/headers";

const Page = () => {
    const pathname = headers().get("next-url");
}

export default Page;
View full answer

28 Replies

Avatar
Northeast Congo Lion
can you not check the incoming request object?
Avatar
How would I do that? 🤔
I wnat to get the path inside a server component?
Avatar
Northeast Congo Lion
import { headers } from "next/headers";
headers().get('next-url')
maybe try this
uwc
Avatar
Ah yes!!
Thank you!! 😊
Avatar
Solution:

import { headers } from "next/headers";

const Page = () => {
    const pathname = headers().get("next-url");
}

export default Page;
Answer
Avatar
Northeast Congo Lion
if it is page.
it has access to request object btw
Avatar
It does?
Avatar
Northeast Congo Lion
import { headers } from "next/headers";

const Page = (req) => {
    console.log(req.headers);
    const pathname = headers().get("next-url");
}

export default Page;
ya
Avatar
In the app router?
Avatar
Northeast Congo Lion
i think so anyway
hold on
sorry
im thinking about api routes, ignore my goofy ah
headers is right way haha
Avatar
:thumbs:
Avatar
@Northeast Congo Lion This doesn't fully work, the next-url header is not set when u refresh the tab 😅
Avatar
Northeast Congo Lion
like full page refresh?
or u mean page change in nextjs
maybe this can help?
Image