Undefined Variable in Next.js
Next.js renders components on both server and client. Undefined variable errors frequently stem from this duality — a variable exists client-side but not during SSR, or vice versa.
Common Causes
- Accessing
windowordocumentin a Server Component - Environment variables without
NEXT_PUBLIC_prefix used client-side - Dynamic imports not properly handled
The Fix
Separate server and client concerns:
'use client';
import { useEffect, useState } from 'react';
export default function ScreenSize() {
const [width, setWidth] = useState(0);
useEffect(() => {
// window is safely available here
setWidth(window.innerWidth);
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
if (width === 0) return <p>Loading...</p>;
return <p>Screen width: {width}px</p>;
}For environment variables, use NEXT_PUBLIC_ prefix for client-side access, and access server-only variables exclusively in Server Components or API routes.
Prevention Tips
To avoid this issue recurring, add automated checks to your CI/CD pipeline. Write integration tests that exercise the failure path — not just the happy path. Use linting rules to enforce best practices across your team. Consider adding health checks that detect this class of error early in staging before it reaches production.
Bugsly for Next.js
Bugsly identifies whether an undefined variable error occurred during SSR or client-side rendering, and shows the rendering context. This eliminates guesswork about which environment caused the issue.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
How to Fix Deployment Error in Node.js
Learn how to fix the Deployment Error in Node.js. Step-by-step guide with code examples.
Read moreFix Authentication Failed Error in TypeScript
Learn how to fix the Authentication Failed error in TypeScript. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read moreFix NotFoundError in Spring Boot in Production
Resolve 404 errors in production Spring Boot apps caused by context path changes, missing controllers, and static resource handling.
Read moreHow to Fix Validationerror in Flask When Deploying
Fix Validationerror in your Flask app when deploying. Understand the root cause and apply the right solution.
Read more