All posts

Fix Load Balancer Error in Next.js

Fix Next.js deployment issues behind a load balancer, covering image optimization, ISR, WebSocket upgrades, and health endpoints.

Next.js Behind a Load Balancer

Next.js has unique challenges behind load balancers because of its hybrid rendering model — some pages are static, some server-rendered, and ISR pages need special cache handling.

Image Optimization Timeouts

Next.js Image Optimization runs on the server. Behind a load balancer, large images can time out:

// next.config.js
module.exports = {
  images: {
    minimumCacheTTL: 60,
    formats: ['image/webp'],
    // Use an external loader in production
    loader: 'custom',
    loaderFile: './lib/image-loader.js',
  },
};

ISR with Multiple Instances

Incremental Static Regeneration caches pages locally. With multiple pods, each has its own cache. Use a shared cache or accept eventual consistency:

// next.config.js
module.exports = {
  experimental: {
    isrMemoryCacheSize: 0, // Disable in-memory cache, use disk
  },
};

Health Check API Route

// app/api/health/route.ts
export function GET() {
  return Response.json({ status: 'ok' });
}

Trusted Headers

Next.js reads x-forwarded-host and x-forwarded-proto for generating absolute URLs:

// next.config.js
module.exports = {
  experimental: {
    trustHostHeader: true,
  },
};

WebSocket for HMR in Staging

If you run a non-production Next.js server behind an LB, HMR WebSockets need upgrade support — configure the load balancer to handle WebSocket protocol upgrades on /_next/webpack-hmr.

Bugsly's Next.js integration captures both server-side and client-side errors with automatic source map support, making it easy to debug production issues across your load-balanced instances.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free