0

I am trying to check my page slug in a function and I get an error

Server Error
ReferenceError: window is not defined

I have another function that it works great in...

function Page() {

const thisPage = window.location.pathname.slice(1); 
console.log(thisPage);
....

Today I am trying to use it here below, but I get the error above

export default function Page() {
    
const thisPage = window.location.pathname.slice(1); 
console.log(thisPage);

Why does the code work in one function but not the other?

Justin Blayney
  • 671
  • 1
  • 6
  • 23
  • It looks like your error is being generated on the server. If so, the window object does not exist as you are not in the browser. – Dean James Dec 23 '20 at 00:11
  • The React components in Next.js are rendered on the server as well, which doesn't have a `window` object. It's good practice to guard against that with e.g. `if (typeof window !== 'undefined') { /* do some browser specific stuff */ }` – Tholle Dec 23 '20 at 00:14
  • thanks guys.. I did have tha Tholle but removed as it wasn't working anyway (no error, but also no log) . How should i write that for next? – Justin Blayney Dec 23 '20 at 00:18
  • It depends on what you want to do with `thisPage` once you have it, and if it's necessary to run it on the server or if it's sufficient to just run it in the browser. – Tholle Dec 23 '20 at 00:28
  • it will be my page slug, my plan is to use it to make a JSON query with GraphQL for the matching page slug and then display the data.. the JSON is from wordpress, to make a headless CMS – Justin Blayney Dec 23 '20 at 00:59
  • im trying to come up with troubleshooting techniques as well – Justin Blayney Dec 23 '20 at 01:00

1 Answers1

0

Next.js does it like this

router.pathname;

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Justin Blayney
  • 671
  • 1
  • 6
  • 23