-1

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);
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • If you're in a browser, the current URL is in `window.location.href`. If you're not in a browser, there is no current URL. Where do you need this? – Tim Roberts Aug 25 '23 at 19:13

2 Answers2

0

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;
0

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.

uttam kamar
  • 3,069
  • 2
  • 6
  • 10