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);
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.
export const getServerSideProps = async (context) => {
const { req } = context;
const host = req.headers.host;
return {
props : { host }
}
}
you can utilize useRouter
of next.js too.
const router = useRouter();
const { pathname } = router;
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.