useRouter() in _documnet.
Unanswered
Atlantic horse mackerel posted this in #help-forum
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:
postBodyComponents and the other are just an array of scripts.
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
Siamese
Hello @Atlantic horse mackerel . So If I understand correctly. You want to get the pathname in the server, correct?
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
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
Siamese
@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
they are using _document.js hence are using the pages router
@Atlantic horse mackerel 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.
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
_document.js is very limited and should not be used for this purpose