Next.js Discord

Discord Forum

URL on server side?

Answered
StilauGamer posted this in #help-forum
Open in Discord
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

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

import { headers } from "next/headers";

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

export default Page;
Answer
Northeast Congo Lion
if it is page.
it has access to request object btw
It does?
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
In the app router?
Northeast Congo Lion
i think so anyway
hold on
sorry
im thinking about api routes, ignore my goofy ah
headers is right way haha
:thumbs:
@Northeast Congo Lion This doesn't fully work, the next-url header is not set when u refresh the tab 😅
Northeast Congo Lion
like full page refresh?
or u mean page change in nextjs
maybe this can help?