How to use webrtc-adapter npm package in Next.js

Viewed 1544

I am creating a React with Next.js. My ES6 imports work just fine for the .js files I create, but when I import webrtc-adapter it fails in next, but succeeds in react-app:

import {adapterFactory} from './adapter_factory.js';
       ^
SyntaxError: Unexpected token {

For example here are the two links which repro:

The following is the reduced test case. Just import webrtc-adapter and console it out. Works in CRA but not in Next.

Importing ES6 in my own files work great, but not foreign packages. Any ideas?

{
  "name": "webrtc-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "next": "^7.0.2",
    "react": "^16.8.0-alpha.0",
    "react-dom": "^16.8.0-alpha.0",
    "webrtc-adapter": "^7.1.1"
  },
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

In pages/index.js

import adapter from 'webrtc-adapter';
console.log(adapter);
export default () => <div>Welcome to next!</div>;

I even tried:

import 'webrtc-adapter';

Any help would be appreciated!

1 Answers

Since Next.JS compiles on the server and the client, you can't be sure you are in a browser context (window is undefined).

To fix this often you can use a simple check like:

if (typeof window !== 'undefined') {
  var adapter = require('webrtc-adapter')
}

to ensure you're within a browser context

Related