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
Here's what each line means:
- at Navbar (webpack-internal:///./src/components/Navbar.tsx:8:15): Line 8 of Navbar.tsx directly accesses document at the top level of the component, which runs during server-side rendering.
- at renderWithHooks (node_modules/react-dom/cjs/react-dom-server.browser.development.js:5658:16): This is the server-side rendering path of React DOM, confirming the code is executing on the server.
- at Object.renderToString (node_modules/react-dom/cjs/react-dom-server.browser.development.js:6543:9): Next.js calls renderToString to produce HTML on the server, where browser APIs like document are unavailable.
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.
export default function Navbar() {
const theme = document.documentElement.getAttribute('data-theme');
return <nav className={theme}>Navigation</nav>;
}
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Run the test suite locally to confirm SSR and client rendering both work.
- Open a pull request with the useEffect refactor.
- Wait for CI checks including the Next.js build step to pass.
- Have a teammate review and approve the PR.
- 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.