Gatsby ‘window.location’ not available during SSR

The location parameter works via ‘gatsby develop’, but fails to compile via ‘gatsby build’.

Problem

Gatsby error message:

failed Building static HTML for pages - 4.279s

"location" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html

  WebpackError: ReferenceError: location is not defined
  
  - build-html.js:110 doBuildPages
    [cubic_gatsby]/[gatsby]/dist/commands/build-html.js:110:24
  
  - build-html.js:124 async buildHTML
    [cubic_gatsby]/[gatsby]/dist/commands/build-html.js:124:3
  
  - build.js:200 async build
    [cubic_gatsby]/[gatsby]/dist/commands/build.js:200:5Code language: JavaScript (javascript)

or

failed Building static HTML for pages - 4.279s

"window" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html

  WebpackError: ReferenceError: location is not defined
  
  - build-html.js:110 doBuildPages
    [cubic_gatsby]/[gatsby]/dist/commands/build-html.js:110:24
  
  - build-html.js:124 async buildHTML
    [cubic_gatsby]/[gatsby]/dist/commands/build-html.js:124:3
  
  - build.js:200 async build
    [cubic_gatsby]/[gatsby]/dist/commands/build.js:200:5Code language: JavaScript (javascript)

Solution

Place this at the top of your component and use pathname directly.

let pathname = typeof window !== "undefined" ? window.location.pathname : ""Code language: JavaScript (javascript)

‘typeof ‘ can be used in JavaScript to more gracefully handle an undefined value.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.