4

I'm trying to use phaser along with ion-phaser/react to build a page with a game in a Next.js app. This is my pages/game.js (using the React example from here https://github.com/proyecto26/ion-phaser):

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}

export default App;

Running next dev and visiting the page gives the following error:

ReferenceError: navigator is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
init
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (69:14)
Object.<anonymous>
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (186:18)
Module._compile
internal/modules/cjs/loader.js (1063:30)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1092:10)
Module.load
internal/modules/cjs/loader.js (928:32)
Function.Module._load
internal/modules/cjs/loader.js (769:14)
Module.require
internal/modules/cjs/loader.js (952:19)
require
internal/modules/cjs/helpers.js (88:18)
Object.<anonymous>
file:///C:/git_projects/floam/node_modules/phaser/src/device/index.js (32:9)
Module._compile
internal/modules/cjs/loader.js (1063:30)

Why is navigator not defined?

These are my relevant package versions in package.json:

"next": "^9.5.5",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"phaser": "^3.55.2",
"@ion-phaser/react": "^1.3.0",
2

2 Answers 2

4

Probably this package is not suitable for SSR. It seems like it calls navigator without checking availability of the browser api and it throws an error on server side.

If this package is React component then you can try to use next/dynamic to import it (use ssr: false to exclude it from SSR):

import dynamic from 'next/dynamic'

const Phaser = dynamic(
  () => import('@ion-phaser/react'),
  { ssr: false }
)

If this does not work then you need to use regular non-Next.js dynamic import() to import the whole module (in useEffect probably)

Sign up to request clarification or add additional context in comments.

Comments

2

I had to use useEffect, like so:

useEffect(async () => (window.Phaser = await import(`phaser`)), []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.