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 FreeRelated Articles
Fix Routing Error in Electron
Step-by-step guide to fix Routing Error in Electron. Includes root cause analysis, code examples, debugging tips, and prevention strategies.
Read moreHow to Fix Version Mismatch in Astro
Fix Version Mismatch in your Astro app. Understand the root cause and apply the right solution.
Read moreFix Container Error in Svelte
Learn how to fix the Container error in Svelte. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read moreHow to Fix Rangeerror in Kotlin In Production
Learn how to diagnose and fix the rangeerror in Kotlin in production. Includes code examples and prevention tips.
Read more