All posts

Fix Memory Leak in Next.js

Identify and fix memory leaks in Next.js applications caused by SSR caching, module-level state, and improper data fetching patterns.

Memory Leaks in Next.js

Next.js server processes can leak memory through module-level caches, improperly cleaned-up API connections, and SSR-specific patterns that aren't obvious from client-side thinking.

Module-Level State

In Next.js, server modules persist across requests. A module-level cache grows with each request:

// BAD — this cache lives forever in the server process
const cache: Record<string, any> = {};

export async function getData(id: string) {
  if (!cache[id]) {
    cache[id] = await fetchFromDB(id);
  }
  return cache[id];
}

Fix by using a bounded cache with TTL:

import { LRUCache } from 'lru-cache';

const cache = new LRUCache<string, any>({
  max: 500,
  ttl: 1000 * 60 * 5, // 5 minutes
});

export async function getData(id: string) {
  const cached = cache.get(id);
  if (cached) return cached;
  const data = await fetchFromDB(id);
  cache.set(id, data);
  return data;
}

Prisma Client Leak

Creating a new Prisma client per request leaks connections:

// BAD
export async function GET() {
  const prisma = new PrismaClient();
  const users = await prisma.user.findMany();
  return Response.json(users);
  // prisma never disconnected
}

// GOOD — singleton
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
export const prisma = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

Monitoring

Bugsly tracks Node.js heap usage over time in your Next.js deployment. When memory grows monotonically across requests, it flags the trend so you can investigate before the process crashes.

Try Bugsly Free

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

Get Started Free