skip to Main Content

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


  1. 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;
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search