Skip to content

ReferenceError: document is not defined when importing the package in Next.js (SSR / RSC) #149

@roanrobersson

Description

@roanrobersson

Environment

  • Package: @microlink/react-json-view (e.g. ^1.31.7)
  • Framework: Next.js (e.g. 16.x with App Router / Turbopack)
  • Node.js: v23.11.1

Description

Importing @microlink/react-json-view with a static top-level import causes the module to be evaluated in a Node.js context during the Next.js build / server render. The package (or one of its dependencies) accesses document at module evaluation time, not only inside a browser-only code path. In Node, document is undefined, which throws:

ReferenceError: document is not defined

Steps to reproduce

  1. Create a Next.js App Router project.

  2. Add a Client Component file with "use client" and a top-level:

    import ReactJsonView from "@microlink/react-json-view";
  3. Ensure this module is part of the server bundle graph (e.g. re-exported from a barrel that is imported by a layout or server component tree).

  4. Run next dev or next build and load a route that pulls in that graph.

Expected behavior

The package should be safe to import in SSR environments: no browser globals (document, window, etc.) should run at module top level. Browser-only code should run lazily (e.g. inside useEffect, or behind a conditional typeof document !== "undefined"), or the package should document that it must only be loaded via dynamic import with ssr: false / similar.

Actual behavior

ReferenceError: document is not defined during module evaluation.

Sample stack trace

ReferenceError: document is not defined
  at module evaluation (.../JsonViewer.tsx:5:1)
  ... (import chain through barrel exports / layout)

Workaround used

Lazy-load the component with next/dynamic and { ssr: false }, and isolate the static import in a separate module that is only loaded on the client.

Additional context

This matters for Next.js and any SSR setup where the dependency graph is analyzed on the server—even for files marked "use client", the bundler may still evaluate or include the module in ways that trigger top-level browser APIs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions