0

In class components, this is my code to fetch URL/Path but it is not working. I guess it is probably because my project is using nextJS(9.3.0) not react-router

fetch_window_URL = () => {
  let ddd = window.location.href;
  console.log(`URL is ${ddd}`)
  let ccc = window.location.pathname;
  console.log(`Path is ${ccc}`)
  }

ReferenceError: window is not defined

My ultimate goal is to get a unique string value from URL-Path. I believe, I can achieve it by fetch URL-Path which will give me a string value, & then I will extract a sub-string(which i want) from that URL string. The URL i am fetching doesn't have query params in it, It is just a pathname(string value).

John V
  • 7
  • 2
  • 5
  • You're getting this error because initially the component is rendering server side. Since `window` is not available in server side, it throws an error. You should [check](https://nextjs.org/docs/migrating/from-create-react-app#safely-accessing-web-apis) if its client side rendering or server side? – Junaid Faryad Oct 03 '21 at 03:21
  • 1
    You can also look into using the `router` component of [next](https://nextjs.org/docs/api-reference/next/router) for getting the `url path and related params`. – Junaid Faryad Oct 03 '21 at 03:23
  • Does this answer your question: [Get URL pathname in nextjs](https://stackoverflow.com/questions/58022046/get-url-pathname-in-nextjs)? Use the built-in [`next/router`](https://nextjs.org/docs/api-reference/next/router) and retrieve the URL path with `const { asPath } = useRouter()`. – juliomalves Oct 03 '21 at 16:49

1 Answers1

-1
import { useRouter } from 'next/router';

const MyComponent = () => {
    const { pathname } = useRouter();

    useEffect(() => {
        console.log(pathname)
    }, []);
    //Rest of the code 
}

By this you can get path name for example for URL "http://localhost:3000/admin" pathname will be "/admin".

MD Jahid Hasan
  • 786
  • 1
  • 9
  • 19