This article is about fixing ReferenceError: navigator is not defined
  • 31-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing ReferenceError: navigator is not defined

ReferenceError: navigator is not defined in JedWatson React Codemirror

Lightrun Team
Lightrun Team
31-Jan-2023

Explanation of the problem

The following error occurs during runtime in a Node.js project that utilizes the CodeMirror library:

ReferenceError: navigator is not defined W20161022-17:29:38.375(-4)? (STDERR)     at /Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:24:19 W20161022-17:29:38.375(-4)? (STDERR)     at userAgent (/Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:12:22) W20161022-17:29:38.376(-4)? (STDERR)     at Object.<anonymous> (/Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:17:3) W20161022-17:29:38.376(-4)? (STDERR)     at Module._compile (module.js:409:26) W20161022-17:29:38.376(-4)? (STDERR)     at Object.Module._extensions..js (module.js:416:10) W20161022-17:29:38.376(-4)? (STDERR)     at Module.load (module.js:343:32) W20161022-17:29:38.377(-4)? (STDERR)     at Module.Mp.load (/Users/mattmacpherson/.meteor/packages/babel-compiler/.6.9.1_1.15j1r1l++os+web.browser+web.cordova/npm/node_modules/reify/node/runtime.js:16:23) W20161022-17:29:38.377(-4)? (STDERR)     at Function.Module._load (module.js:300:12) W20161022-17:29:38.378(-4)? (STDERR)     at Module.require (module.js:353:17) W20161022-17:29:38.378(-4)? (STDERR)     at require (internal/module.js:12:17)

The error is caused by the use of the codemirror library, specifically when requiring the following modes:

require('codemirror/mode/javascript/javascript'); 
require('codemirror/mode/xml/xml'); 
require('codemirror/mode/markdown/markdown');

It should be noted that the error only occurs when the mentioned codemirror modes are required.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for ReferenceError: navigator is not defined in JedWatson React Codemirror

The error “ReferenceError: navigator is not defined” is thrown when the ‘CodeMirror’ component is imported and rendered in a server-side environment. This is due to the fact that certain objects, such as ‘navigator’, are only defined in the client-side environment and not on the server.

To resolve this issue, the solution involves importing the necessary components and modules conditionally, by checking if certain objects are defined before attempting to import them. For example, the following code block checks if the ‘window’ object and ‘navigator’ object are defined before importing the ‘CodeMirror’ component and its required modules:

let CodeMirror = null;
if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
  CodeMirror = require('react-codemirror');
  require('codemirror/mode/yaml/yaml');
  require('codemirror/mode/dockerfile/dockerfile');
}

For users who are utilizing the NextJS framework, the solution involves using the ‘dynamic’ import feature and setting the ‘ssr’ property to ‘false’. This informs the framework to only render the ‘CodeMirror’ component on the client-side, and not on the server. The following code block demonstrates the usage of this solution:

import dynamic from 'next/dynamic';
const CodeMirror = dynamic(() => import('react-codemirror'), { ssr: false });

Other popular problems with JedWatson React Codemirror

Problem: ReferenceError: “navigator” is not defined

This error occurs when trying to import and render the ‘JedWatson React Codemirror’ component. It is because ‘navigator’ is not defined in the Node environment, but it is available in the browser environment.

Solution:

The solution is to conditionally import the component and modules and check if certain objects are defined. For example:

let CodeMirror = null;
if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
  CodeMirror = require('react-codemirror');
  require('codemirror/mode/yaml/yaml');
  require('codemirror/mode/dockerfile/dockerfile');
}

And then render the component with the condition:

// render
   { CodeMirror && <CodeMirror ... /> }

Problem: Compatibility issues with NextJS

When using NextJS, server-side rendering (SSR) can cause issues with the ‘JedWatson React Codemirror’ component. This is because the component relies on certain browser APIs that are not available in the Node environment.

Solution:

The solution is to use the ‘dynamic’ component provided by NextJS and set the ‘ssr’ property to ‘false’:

import dynamic from 'next/dynamic'; 
const CodeMirror = dynamic(() => import('react-codemirror'), { ssr: false });

Problem: Inefficient Rendering

In some cases, the ‘JedWatson React Codemirror’ component can cause slow rendering times, especially when dealing with large amounts of code or data. This can negatively impact the performance of the entire application.

Solution:

The solution is to optimize the rendering process by using the ‘shouldComponentUpdate’ lifecycle method to avoid unnecessary renderings and only render when there are actual changes to the component’s state. Additionally, the ‘key’ property can be used to ensure that the component only re-renders when the code or data changes:

class CodeEditor extends React.Component {
  shouldComponentUpdate(nextProps) {
    return nextProps.value !== this.props.value;
  }

  render() {
    return (
      <CodeMirror
        key={this.props.value}
        value={this.props.value}
        onChange={this.props.onChange}
      />
    );
  }
}

A brief introduction to JedWatson React Codemirror

JedWatson React Codemirror is a library that provides a React component for using the CodeMirror code editor in React applications. The library allows developers to easily integrate a feature-rich code editor into their projects without having to worry about managing the complexities of the underlying CodeMirror library.

The library provides a number of useful features for the code editor, such as syntax highlighting, line numbering, and the ability to set custom themes. It also supports a number of customization options that allow developers to modify the behavior and appearance of the editor to suit their needs. This includes options for controlling the size and position of the editor, as well as support for adding custom keybindings and customizing the context menu.

Most popular use cases for JedWatson React Codemirror

  1. Text Editing: JedWatson React Codemirror provides a text editing component for web applications, allowing users to create and edit source code, rich text, and other text-based content with syntax highlighting, line numbering, and more.
  2. Code Highlighting: The component supports a wide range of programming languages, providing accurate syntax highlighting for each language. This can be seen in the code block below where JavaScript code is rendered with syntax highlighting in the Codemirror component:
import React, { useState } from "react";
import Codemirror from "react-codemirror";

const App = () => {
  const [code, setCode] = useState("// type your code here");
  return (
    <Codemirror
      value={code}
      onChange={setCode}
      options={{
        mode: "javascript",
        lineNumbers: true,
      }}
    />
  );
};

export default App;
  1. Customization: JedWatson React Codemirror provides a rich set of customization options, including key bindings, themes, line wrapping, and more. This allows developers to tailor the component to the specific needs of their applications, providing a more seamless user experience.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.