It is correct that there is no window object in SSR, so window.location.href
cannot be used and the useRouter()
hook is only available on the client side. However, with the useRouter
hook, you can still obtain the current path name in SSR.
Potential Solution
To resolve this issue, you can install the package npm install nextjs-current-url
. This package provides a function called getURL
, which requires the req
object typically available in the getServerSideProps
.
export async function getServerSideProps(context) {
const { req } = context;
const the_url = await getUrl({ req });
return {
props: {
the_url,
},
};
}
Usage in your component:
const YourComponent = ({ the_url }) => {
return (
<div>
<h1>{the_url}</h1>
</div>
);
};
export default YourComponent;
UPDATED
You can also utilize it with AppRouter by importing and using it with an await
keyword as shown below:
import { getUrl } from 'nextjs-current-url';
const YourComponent = () => {
const url = await getUrl();
return (
<div>
<h1>{url}</h1>
</div>
);
};
export default YourComponent;
UPDATED 2nd version
Similarly to the previous example with serverSideProps, you can use the context
object to acquire the URL information. The context object contains data about the current request.
import { getUrl } from 'nextjs-current-url';
const ServerComponentLayout = ({ children }) => {
const the_url = getUrl({ req: context.req });
return (
<div>
{children}
<p>URL: {the_url}</p>
</div>
);
};
export default ServerComponentLayout;
Then include this layout component in your own component like this:
<ServerComponentLayout>
<h1>My Component</h1>
</ServerComponentLayout>