Fixing 'ReferenceError: window is not defined' in ApexCharts Next.js 14

Abstract: Resolve the ReferenceError: window is not defined in Next.js 14 by dynamically importing ApexCharts with ssr false to prevent server-side execution.

Created: 2026-10-10 by
The ReferenceError: window is not defined error occurs because ApexCharts attempts to access the browser's window object during server-side rendering in Next.js 14. Since the server environment lacks a DOM, this access throws an exception immediately upon import. The solution involves dynamically importing the chart component with ssr: false to ensure it only loads on the client side, effectively bypassing the server-side execution context that causes the crash.

Understanding the Server-Side Rendering Conflict

Next.js operates on a hybrid rendering model where components are initially rendered on the server before being hydrated in the browser. This architecture improves initial load times and search engine optimization but introduces challenges for libraries that rely heavily on browser-specific APIs. ApexCharts is one such library; it requires access to the Document Object Model (DOM) and the global window object to calculate dimensions, handle events, and render SVG elements. When you import ApexCharts directly at the top of a page or layout file, the module evaluation happens during the server build process. The server Node.js environment does not have a window property. Consequently, any code inside the ApexCharts initialization block that references window.innerWidth, window.innerHeight, or similar properties will fail immediately. This is not a bug in your code logic but a fundamental mismatch between the library's requirements and the server-side execution environment. To resolve this, you must prevent ApexCharts from loading during the server-render phase. The standard approach in React ecosystems is conditional loading based on the availability of browser globals. In Next.js 14, the recommended pattern leverages the dynamic import feature provided by the framework itself. This ensures that the heavy bundle containing ApexCharts is only fetched and executed after the component has mounted in the browser.

Implementing Dynamic Imports

The most robust way to fix this issue is to use Next.js's next/dynamic helper. This function allows you to split your code into separate chunks and control when they are loaded. By setting the ssr option to false, you instruct Next.js to skip rendering this specific component on the server entirely. It will only appear in the final HTML output once the client-side JavaScript takes over. First, create a new file for your chart component, for example, ChartClient.tsx. Move all ApexCharts-related logic here. Then, in your main page or parent component, import the dynamic wrapper. Do not import ApexCharts directly in the root scope. Instead, wrap the chart component using dynamic.
import dynamic from 'next/dynamic';
import React from 'react';

// Import the chart component dynamically with SSR disabled
const ApexChart = dynamic(() => import('../components/ApexChart'), {
  ssr: false,
});

export default function Dashboard() {
  return (
    <div className="chart-container">
      <ApexChart />
    </div>
  );
}
This structure isolates the problematic dependency. The server renders the rest of the page normally, skipping the ApexChart tag. When the browser receives the HTML, it executes the client-side script, imports the ApexChart module, and mounts the chart. Because this happens exclusively in the browser, the window object exists, and the error disappears.

Handling State and Data Passing

A common pitfall when using dynamic imports is managing data flow. Since the chart component is loaded asynchronously, you cannot pass props down in the traditional synchronous manner if those props trigger immediate ApexCharts initialization during the render cycle. However, because ssr: false still allows the component to receive props from the parent once mounted, you can safely pass configuration objects and data arrays. Ensure that your parent component prepares the data before passing it to the dynamic chart. If the data depends on user interaction or client-side state updates, make sure the chart re-renders correctly when those states change. ApexCharts supports updating via its API methods, which should be called within useEffect hooks in the client component. This ensures that updates happen only after the chart instance has been successfully created in the browser.
import { useEffect } from 'react';
import ApexCharts from 'apexcharts';

export default function ApexChart({ data }) {
  useEffect(() => {
    const options = {
      series: [{ name: 'Sales', data: data }],
      chart: { type: 'line' },
    };

    const chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();

    return () => chart.destroy();
  }, [data]);

  return <div id="chart" />;
}
By encapsulating the initialization logic inside useEffect, you guarantee that the DOM element exists before ApexCharts tries to attach to it. This pattern complements the dynamic import strategy and provides a stable foundation for complex visualizations in Next.js applications.

Alternative Solutions and Trade-offs

While dynamic imports are the preferred method, some developers might consider alternative approaches. One such alternative is checking for the existence of window manually before importing. However, this is fragile and often leads to inconsistent behavior across different parts of the application. Another option is disabling server-side rendering globally for the entire page using export const dynamic = 'force-dynamic' or export const runtime = 'edge'. While this stops the error, it negatively impacts performance and SEO by forcing the entire page to render client-side. You might also encounter issues with TypeScript definitions if your project uses strict typing. Ensure that your tsconfig.json includes the necessary types for ApexCharts. Outdated type definitions can cause compilation errors that mask the runtime error. Updating your dependencies to the latest versions usually resolves these typing conflicts. Additionally, verify that you are not accidentally importing ApexCharts in other files that run on the server, such as middleware or API routes. These environments also lack a window object and will throw similar errors if the library is used there. For more information on resolving related frontend library issues in Next.js, you may find the guide on handling React Flow context errors useful. That article discusses similar patterns for integrating complex visualization libraries without breaking the server-side rendering pipeline.

Frequently Asked Questions

Why does the error happen only in production builds?

The error often manifests in production because Next.js optimizes bundles differently, sometimes eager-loading modules that were lazy-loaded in development. Always test your production build locally using npm run build and npm start to catch these issues early.

Can I use ApexCharts with Next.js App Router?

Yes, the App Router supports dynamic imports just like the Pages Router. You simply apply the same next/dynamic pattern with ssr: false to any component within the App Router structure. The principles remain identical regardless of the routing system used.

Does disabling SSR hurt my SEO?

Disabling SSR for a single chart component has negligible impact on SEO since charts typically contain non-indexable visual data. The surrounding text and content remain server-rendered and accessible to crawlers. Only disable SSR for the specific widget, not the entire page.

What if I need to update the chart based on API calls?

You can fetch data in the parent component and pass it as props to the dynamic chart. Use useEffect inside the chart component to listen for prop changes and call the ApexCharts update method. This keeps the chart responsive to new data without reloading the entire page.

Are there lighter alternatives to ApexCharts for Next.js?

If bundle size is a concern, consider libraries like Recharts or Chart.js, which also support dynamic imports. Recharts is built specifically for React and often integrates more smoothly with Next.js due to its component-based architecture. Evaluate these based on your specific visualization needs.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More