All posts

How to Fix Undefined Variable in Next.js

Fix Undefined Variable in your Next.js app. Understand the root cause and apply the right solution.

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 window or document in 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 Free