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);
2
Answers
it depends on your use case but generally as you don’t have access to window object on server side you can use
getServerSideProps
and its context.you can utilize
useRouter
of next.js too.In Next.js, you can access the current URL without using
window.location.href
or React Router by utilizing theuseRouter
hook provided by Next.js. Here’s how you can do it:The
useRouter
hook fromnext/router
allows you to access various properties of the router, including the current URL via theasPath
property. This method is more preferable in Next.js compared to usingwindow.location.href
because it works on both the client and server side without any issues.