Next.js Discord

Discord Forum

useRouter() in _documnet.

Unanswered
Atlantic horse mackerel posted this in #help-forum
Open in Discord
Avatar
Atlantic horse mackerelOP
Hi devs, using page router and I understand _document.js is a component that is only rendered on the server, but I wonder if there is a way to make useRouter work there somehow.

what I am trying to do is to to have scripts based on the pathanme:

export default function Document() { return ( <Html> <Head/> <body> <Main /> <NextScript /> {pathname.includes('test') ? postBodyComponentsBase : postBodyComponents} </body> </Html> ); }
postBodyComponents and the other are just an array of scripts.

6 Replies

Avatar
Siamese
Hello @Atlantic horse mackerel . So If I understand correctly. You want to get the pathname in the server, correct?
Avatar
Atlantic horse mackerelOP
Yes!
Avatar
Siamese
There is no direct way to do this. As far as I know. but there is some workaround you can do.

You might find these helpful:
https://stackoverflow.com/questions/75362636/how-can-i-get-the-url-pathname-on-a-server-component-next-js-13

https://github.com/vercel/next.js/issues/43704
Avatar
Siamese
Avatar
joulev
they are using _document.js hence are using the pages router
use <Script> inside _app.js. you do have access to useRouter() inside _app.js.

_document.js is very limited and should not be used for this purpose