How It Works Features Pricing Blog
Log In Start Free Trial
Next.js · TypeScript/React

Fix ReferenceError: document is not defined in Next.js

This error occurs when server-side code tries to access the browser-only document object. In Next.js, components render on the server first where document does not exist. Fix it by wrapping document access in a useEffect hook or by using dynamic imports with ssr disabled.

Reading the Stack Trace

ReferenceError: document is not defined at Navbar (webpack-internal:///./src/components/Navbar.tsx:8:15) at renderWithHooks (node_modules/react-dom/cjs/react-dom-server.browser.development.js:5658:16) at renderElement (node_modules/react-dom/cjs/react-dom-server.browser.development.js:5901:5) at renderNodeDestructiveImpl (node_modules/react-dom/cjs/react-dom-server.browser.development.js:6053:11) at renderNodeDestructive (node_modules/react-dom/cjs/react-dom-server.browser.development.js:6025:14) at renderIndeterminateComponent (node_modules/react-dom/cjs/react-dom-server.browser.development.js:5680:7) at renderElement (node_modules/react-dom/cjs/react-dom-server.browser.development.js:5893:7) at renderNode (node_modules/react-dom/cjs/react-dom-server.browser.development.js:6117:16) at Object.renderToString (node_modules/react-dom/cjs/react-dom-server.browser.development.js:6543:9) at renderDocument (node_modules/next/dist/server/render.js:843:30)

Here's what each line means:

Common Causes

1. Direct document access in component body

Calling document.querySelector or similar APIs directly in the component function body runs during SSR where document does not exist.

export default function Navbar() {
  const theme = document.documentElement.getAttribute('data-theme');
  return <nav className={theme}>Navigation</nav>;
}

2. Third-party library accessing document on import

Some libraries access document at import time, which fails during server-side rendering in Next.js.

import Carousel from 'some-carousel-lib'; // This lib accesses document on import

export default function Hero() {
  return <Carousel items={slides} />;
}

3. Window/document check missing in custom hook

A custom hook reads from document without first checking that it exists, crashing during SSR.

function usePageTitle() {
  return document.title;
}

The Fix

Move the document access into a useEffect hook, which only runs on the client after the component mounts. Provide a sensible default via useState so the server render produces valid HTML.

Before (broken)
export default function Navbar() {
  const theme = document.documentElement.getAttribute('data-theme');
  return <nav className={theme}>Navigation</nav>;
}
After (fixed)
import { useEffect, useState } from 'react';

export default function Navbar() {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    const current = document.documentElement.getAttribute('data-theme');
    if (current) setTheme(current);
  }, []);

  return <nav className={theme}>Navigation</nav>;
}

Testing the Fix

import { render, screen } from '@testing-library/react';
import Navbar from './Navbar';

describe('Navbar', () => {
  it('renders with default theme on server', () => {
    render(<Navbar />);
    expect(screen.getByText('Navigation')).toBeInTheDocument();
  });

  it('picks up data-theme attribute on client', () => {
    document.documentElement.setAttribute('data-theme', 'dark');
    render(<Navbar />);
    const nav = screen.getByText('Navigation');
    expect(nav).toBeInTheDocument();
    document.documentElement.removeAttribute('data-theme');
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/referenceerror-document-ssr,git add src/components/Navbar.tsx src/components/__tests__/Navbar.test.tsx,git commit -m "fix: move document access to useEffect for SSR safety",git push origin fix/referenceerror-document-ssr

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
      - run: npm run build

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the test suite locally to confirm SSR and client rendering both work.
  2. Open a pull request with the useEffect refactor.
  3. Wait for CI checks including the Next.js build step to pass.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify server-side rendering works correctly in staging.

Frequently Asked Questions

BugStack validates the fix in both server and client rendering contexts, runs your test suite, and confirms the Next.js build succeeds before marking it safe.

Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.

Yes. Next.js dynamic() with { ssr: false } is ideal for third-party components that access document on import. For your own code, useEffect is simpler.

Content inside useEffect renders only on the client. If the content is critical for SEO, consider fetching it in getServerSideProps instead of relying on document.