Overview
Integrating Excalidraw with Next.js requires special handling due to server-side rendering (SSR). This guide covers both the App Router and Pages Router approaches, with solutions for SSR compatibility.Why Dynamic Import?
Excalidraw uses browser-specific APIs that aren’t available during SSR. To prevent errors, we need to:- Disable SSR for the Excalidraw component
- Use dynamic imports with
ssr: false - Handle client-side only rendering
Installation
App Router Integration (Next.js 13+)
The App Router uses React Server Components by default, requiring a client-only wrapper.Step 1: Create a Wrapper Component
Createsrc/excalidrawWrapper.tsx:
src/excalidrawWrapper.tsx
Step 2: Dynamic Import in Page
Create your page with dynamic import:src/app/page.tsx
Step 3: Create Layout
src/app/layout.tsx
Add Global Styles
Createsrc/app/globals.css:
src/app/globals.css
Pages Router Integration
For the traditional Pages Router, use a similar approach:Step 1: Create Wrapper Component
src/excalidrawWrapper.tsx
Step 2: Create Page with Dynamic Import
src/pages/index.tsx
Advanced Integration with Custom Features
Create a full-featured integration with custom UI and functionality:Loading State
Add a loading indicator while Excalidraw loads:TypeScript Configuration
Ensure yourtsconfig.json is properly configured:
tsconfig.json
Polyfills for Server-Side
If you encounter canvas-related errors during build, add polyfills:Deployment
Deploy to Vercel
The easiest way to deploy is using Vercel:
Common Issues
ReferenceError: window is not defined
ReferenceError: window is not defined
This occurs when SSR tries to access browser APIs. Make sure:
- You’re using
dynamicimport withssr: false - The
"use client"directive is at the top of your wrapper - Asset path is set using
next/scriptwithbeforeInteractivestrategy
Fonts not loading
Fonts not loading
Ensure:
- Fonts are copied to the public directory
EXCALIDRAW_ASSET_PATHis set correctly- Your build script includes the copy:assets step
TypeScript errors during build
TypeScript errors during build
If you see TypeScript errors related to JSX:
- Check your
tsconfig.jsonhas"jsx": "preserve" - Ensure all imports are correctly typed
- Consider adding
// @ts-expect-errorfor known Next.js issues
Canvas rendering issues
Canvas rendering issues
Install and import the path2d-polyfill:Then import it in your wrapper component.