Search code examples
javascriptreactjsnext.jsnetlify

Nextjs getInitialProps error preventing build on Netlify


Hey folks I inherited a project built with nextjs and running on Netlify. I am trying to load a component when a user is using IE. Locally I am am able to render the component view without any issues. But when a build gets ran (code pushed to a specific branch) the build fails on Netlify. Netlify does not seem to like the following.

const userAgent = props ? props.req.headers['user-agent'] : navigator.userAgent

Open to any suggestions. I am new to Netlify and simply trying to display a component that lets users know that their browser is not supported. Below is the code I have in _document.js

_document.js

class MyDocument extends Document {

 static async getInitialProps(props) {
  const page = props.renderPage()
  const userAgent = props ? props.req.headers['user-agent'] : navigator.userAgent

  return {
    ...page,
    userAgent
  }
 }

renderBrowserSupport() {
  let msie = this.props.userAgent.indexOf('MSIE ');
  let ie11 = this.props.userAgent.indexOf('Trident/');

  if(msie > 0 || ie11 > 0) {
    return (
      <BrowserSupport/>
    )
  }

  else return false;
}

render() {
  <html lang="en">

  <body>
  {this.renderBrowserSupport()}
  </body>

  </html>
 }
}

export default MyDocument

Error when running npm run build

Cannot read property 'user-agent' of undefined

Solution

  • I ran into several issues with adding code to _document.js so I went with a different approach which is as follows:

    1. created a route update-browser
    2. added a component with messaging and alternative browsers to IE
    3. added script to check if browser is IE 11 or IE and redirected to update-browser page if so