debug:nextjs
Debug Next.js issues systematically. Use when encountering SSR errors, hydration mismatches like "Text content did not match", routing issues with App Router or Pages Router, build failures, dynamic import problems, API route errors, middleware issues, caching and revalidation problems, or performance bottlenecks. Covers both Pages Router and App Router architectures.
What this skill does
# Next.js Debugging Guide
This guide provides a systematic approach to debugging Next.js applications, covering common error patterns, debugging tools, and resolution strategies for both development and production environments.
## Common Error Patterns
### 1. Hydration Mismatches
**Symptoms:**
```
Warning: Text content did not match. Server: '...' Client: '...'
Warning: Expected server HTML to contain a matching <div> in <div>
Hydration failed because the initial UI does not match what was rendered on the server
```
**Common Causes:**
- Using `Date.now()`, `Math.random()`, or timestamps in render
- Browser-only APIs accessed during SSR (`window`, `localStorage`, `document`)
- Conditional rendering based on client-only state
- Extension-injected HTML elements
- Invalid HTML nesting (e.g., `<p>` inside `<p>`, `<div>` inside `<p>`)
**Solutions:**
```tsx
// BAD: Causes hydration mismatch
function Component() {
return <p>Current time: {new Date().toLocaleString()}</p>
}
// GOOD: Use useEffect for client-only values
'use client'
import { useState, useEffect } from 'react'
function Component() {
const [time, setTime] = useState<string>('')
useEffect(() => {
setTime(new Date().toLocaleString())
}, [])
return <p>Current time: {time || 'Loading...'}</p>
}
// GOOD: Suppress hydration warning for intentional mismatches
<time suppressHydrationWarning>
{new Date().toLocaleString()}
</time>
```
### 2. Server/Client Component Confusion
**Symptoms:**
```
Error: useState only works in Client Components. Add the "use client" directive
Error: You're importing a component that needs useEffect. It only works in a Client Component
Error: createContext only works in Client Components
```
**Understanding the Boundary:**
```tsx
// Server Component (default in App Router)
// - Can't use hooks (useState, useEffect, etc.)
// - Can't use browser APIs
// - CAN use async/await directly
// - CAN access backend resources directly
// app/page.tsx (Server Component)
async function Page() {
const data = await db.query('SELECT * FROM posts') // Direct DB access
return <PostList posts={data} />
}
// Client Component
// - CAN use hooks
// - CAN use browser APIs
// - Must be marked with 'use client'
// components/Counter.tsx
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(c => c + 1)}>{count}</button>
}
```
**Context Provider Pattern:**
```tsx
// providers/theme-provider.tsx
'use client'
import { createContext, useContext, useState } from 'react'
const ThemeContext = createContext<{ theme: string } | null>(null)
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState('light')
return (
<ThemeContext.Provider value={{ theme }}>
{children}
</ThemeContext.Provider>
)
}
// app/layout.tsx (Server Component that uses Client Provider)
import { ThemeProvider } from '@/providers/theme-provider'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
)
}
```
### 3. Dynamic Import Issues
**Symptoms:**
```
Error: Element type is invalid. Received undefined
Module not found errors in production
Components rendering as null
```
**Solutions:**
```tsx
// Dynamic import with SSR disabled (for browser-only libraries)
import dynamic from 'next/dynamic'
const MapComponent = dynamic(() => import('@/components/Map'), {
ssr: false,
loading: () => <p>Loading map...</p>
})
// Dynamic import with named exports
const Modal = dynamic(() =>
import('@/components/Modal').then(mod => mod.Modal)
)
// Dynamic import with error handling
const Chart = dynamic(
() => import('@/components/Chart').catch(err => {
console.error('Failed to load Chart:', err)
return () => <div>Failed to load chart</div>
}),
{ ssr: false }
)
```
### 4. API Route Errors
**App Router (Route Handlers):**
```tsx
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
// GET is cached by default - use dynamic to opt out
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const id = searchParams.get('id')
const data = await fetchUser(id)
return NextResponse.json(data)
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ error: 'Internal Server Error' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// Validate body...
const result = await createUser(body)
return NextResponse.json(result, { status: 201 })
} catch (error) {
if (error instanceof SyntaxError) {
return NextResponse.json(
{ error: 'Invalid JSON' },
{ status: 400 }
)
}
throw error
}
}
```
**Common API Route Issues:**
```tsx
// ISSUE: Route Handler cached unexpectedly
// SOLUTION: Force dynamic rendering
export const dynamic = 'force-dynamic'
export const revalidate = 0
// ISSUE: Can't access cookies/headers
// SOLUTION: Import from next/headers
import { cookies, headers } from 'next/headers'
export async function GET() {
const cookieStore = await cookies()
const token = cookieStore.get('token')
const headersList = await headers()
const userAgent = headersList.get('user-agent')
}
// ISSUE: CORS errors
// SOLUTION: Add CORS headers
export async function GET() {
const response = NextResponse.json({ data: 'test' })
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
return response
}
export async function OPTIONS() {
return new NextResponse(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
})
}
```
### 5. Build Failures
**Common Build Errors:**
```bash
# Type errors during build
Error: Type error: Property 'x' does not exist on type 'y'
# Solution: Fix TypeScript errors or use type assertions
# Module resolution failures
Error: Module not found: Can't resolve '@/components/...'
# Solution: Check tsconfig.json paths and next.config.js
# Static generation failures
Error: getStaticPaths is required for dynamic SSG pages
# Solution: Add getStaticPaths or use generateStaticParams
# Image optimization errors
Error: Invalid src prop on next/image
# Solution: Configure domains in next.config.js
```
**next.config.js Debugging:**
```js
/** @type {import('next').NextConfig} */
const nextConfig = {
// Enable verbose build output
logging: {
fetches: {
fullUrl: true,
},
},
// Debug image domains
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
// Analyze bundle size
webpack: (config, { isServer }) => {
if (process.env.ANALYZE) {
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: isServer
? '../analyze/server.html'
: './analyze/client.html',
})
)
}
return config
},
}
module.exports = nextConfig
```
### 6. Middleware Issues
**Symptoms:**
```
Middleware triggered unexpectedly
Infinite redirect loops
Middleware not executing
Edge runtime compatibility errors
```
**Debugging Middleware:**
```tsx
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Debug: Log all middleware invocations
console.log('Middleware:', request.method, request.nextUrl.pathname)
/Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.