how to get current url in nextjs without using window.location.href or react router
const parse = require("url-parse");
parse("hostname", {});
console.log(parse.href);
how to get current url in nextjs without using window.location.href or react router
const parse = require("url-parse");
parse("hostname", {});
console.log(parse.href);
On
In Next.js, you can access the current URL without using window.location.href or React Router by utilizing the useRouter hook provided by Next.js. Here's how you can do it:
import { useRouter } from 'next/router';
function Page() {
const router = useRouter();
const currentUrl = router.asPath;
return (
<div>
Current URL: {currentUrl}
</div>
);
}
export default Page;
The useRouter hook from next/router allows you to access various properties of the router, including the current URL via the asPath property. This method is more preferable in Next.js compared to using window.location.href because it works on both the client and server side without any issues.
it depends on your use case but generally as you don't have access to window object on server side you can use
getServerSidePropsand its context.you can utilize
useRouterof next.js too.