I have a page, /trial, that I want to ensure is always visited with a route param. In my constructor, I check this.props.location.search, and if it's falsy (empty) I want to navigate to /trial/?product=foobar.
Here's my code
import React from 'react'
import { navigate } from 'gatsby'
class Foobar extends React.Component {
constructor(props) {
super(props)
this.redirectIfNecessary()
}
redirectIfNecessary() {
// Make prospect the default product
const { location } = this.props
const { search } = location
if (!search) {
navigate('/trial/?product=foobar', {
state: {
product: 'foobar',
},
})
}
}
render() {
return <div>Hello, world</div>
}
}
This works fine during dev time, but when I run gatsby build I get
error Building static HTML for pages failed
See our docs page on debugging HTML builds for help https://goo.gl/yL9lND
186 |
187 | var navigate = function navigate(to, options) {
> 188 | window.___navigate(withPrefix(to), options);
| ^
189 | };
190 |
191 | exports.navigate = navigate;
WebpackError: ReferenceError: window is not defined
gatsby info --clipboard
System:
OS: macOS 10.14.1
CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
Shell: 5.3 - /bin/zsh
Binaries:
Node: 11.3.0 - /usr/local/bin/node
Yarn: 1.12.3 - /usr/local/bin/yarn
npm: 6.4.1 - /usr/local/bin/npm
Browsers:
Chrome: 70.0.3538.110
Firefox: 63.0.3
Safari: 12.0.1
npmPackages:
gatsby: ^2.0.64 => 2.0.64
gatsby-image: ^2.0.20 => 2.0.22
gatsby-plugin-manifest: ^2.0.10 => 2.0.11
gatsby-plugin-offline: ^2.0.19 => 2.0.19
gatsby-plugin-react-helmet: ^3.0.4 => 3.0.4
gatsby-plugin-react-svg: ^2.0.0 => 2.0.0
gatsby-plugin-sass: ^2.0.7 => 2.0.7
gatsby-plugin-sharp: ^2.0.15 => 2.0.15
gatsby-source-filesystem: ^2.0.11 => 2.0.11
gatsby-transformer-sharp: ^2.1.8 => 2.1.9
npmGlobalPackages:
gatsby-cli: 2.4.6
Hey @kevinmichaelchen
Webpack is failing to build this because window is only available in the browser and not during build time.
You can fix this by moving the redirectIfNecessary call from the constructor to componentDidMount instead. That way it will only run on the client side and not during build time.
You can also do this declaratively in your render function by including the Redirect component from reach router
I'm closing this for now since this issue isn't specific to Gatsby but feel free to reopen if there's anything else.
User browser monads repo as a quick fix for this!
Most helpful comment
Hey @kevinmichaelchen
Webpack is failing to build this because
windowis only available in the browser and not during build time.You can fix this by moving the
redirectIfNecessarycall from theconstructortocomponentDidMountinstead. That way it will only run on the client side and not during build time.You can also do this declaratively in your render function by including the Redirect component from reach router
I'm closing this for now since this issue isn't specific to Gatsby but feel free to reopen if there's anything else.