nextjs-performance-guard
v1.0.1
Published
A Next.js developer performance guard that detects heavy components, large bundles, and slow routes in development
Maintainers
Readme
nextjs-performance-guard
A Next.js developer performance guard that detects heavy components, large bundles, and slow routes in development.
What Problem Does This Solve?
Performance issues in Next.js applications often go unnoticed until they reach production. By the time users experience slow load times, heavy components, or bloated bundles, it's too late. nextjs-performance-guard provides real-time performance warnings during development, helping you catch and fix issues before they ship.
Why Performance Guard Matters
- Early Detection: Catch performance regressions during development, not in production
- Actionable Warnings: Clear, debounced console warnings with specific metrics
- Zero Production Impact: Automatically disabled in production builds
- Framework-Agnostic: Works with both App Router and Pages Router
- Lightweight: No runtime dependencies, tree-shakable, ESM-only
Installation
npm install --save-dev nextjs-performance-guardUsage
App Router
1. Heavy Component Detection
Wrap components that might be performance bottlenecks:
// app/components/DashboardCard.tsx
import { withPerformanceGuard } from 'nextjs-performance-guard';
function DashboardCard({ data }: { data: any }) {
// Your component logic
return <div>...</div>;
}
export default withPerformanceGuard(DashboardCard);2. Client Bundle Size Guard
Add bundle analysis to your root layout:
// app/layout.tsx
import { analyzeClientBundle } from 'nextjs-performance-guard';
import { useEffect } from 'react';
export default function RootLayout({ children }: { children: React.ReactNode }) {
useEffect(() => {
analyzeClientBundle({ maxSizeKB: 170 });
}, []);
return <html>{children}</html>;
}3. Route Load Analyzer
Track route performance in your layout:
// app/layout.tsx
import { analyzeRoutes } from 'nextjs-performance-guard';
import { useEffect } from 'react';
export default function RootLayout({ children }: { children: React.ReactNode }) {
useEffect(() => {
const analyzer = analyzeRoutes({ routeLoadThreshold: 1000 });
// Measure client-side navigation
return () => {
analyzer.measureNavigation();
};
}, []);
return <html>{children}</html>;
}Pages Router
1. Heavy Component Detection
Same as App Router:
// components/HeavyComponent.tsx
import { withPerformanceGuard } from 'nextjs-performance-guard';
function HeavyComponent() {
return <div>...</div>;
}
export default withPerformanceGuard(HeavyComponent);2. Client Bundle Size Guard
Add to _app.tsx:
// pages/_app.tsx
import { analyzeClientBundle } from 'nextjs-performance-guard';
import { useEffect } from 'react';
export default function App({ Component, pageProps }: AppProps) {
useEffect(() => {
analyzeClientBundle({ maxSizeKB: 170 });
}, []);
return <Component {...pageProps} />;
}3. Route Load Analyzer
Add to _app.tsx:
// pages/_app.tsx
import { analyzeRoutes } from 'nextjs-performance-guard';
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function App({ Component, pageProps }: AppProps) {
const router = useRouter();
const analyzer = analyzeRoutes({ routeLoadThreshold: 1000 });
useEffect(() => {
const handleRouteChange = () => {
analyzer.measureNavigation();
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router]);
return <Component {...pageProps} />;
}Configuration Options
All functions accept an optional PerformanceGuardConfig:
interface PerformanceGuardConfig {
enabled?: boolean; // Override NODE_ENV check (default: auto)
componentThreshold?: number; // Render time threshold in ms (default: 16)
bundleThresholdKB?: number; // Bundle size threshold in KB (default: 170)
routeLoadThreshold?: number; // Route load threshold in ms (default: 1000)
debounceMs?: number; // Warning debounce time in ms (default: 1000-2000)
}Example with Custom Configuration
import { withPerformanceGuard } from 'nextjs-performance-guard';
export default withPerformanceGuard(MyComponent, {
componentThreshold: 32, // Warn if render > 32ms
debounceMs: 2000, // Debounce warnings by 2s
});Warning Examples
Heavy Component
⚠️ [Next Perf Guard] Heavy component detected: DashboardCard (render: 68ms) (re-renders: 15)Large Bundle
⚠️ [Next Perf Guard] Client bundle exceeds 170kb on /dashboard (actual: 245kb)Slow Route
⚠️ [Next Perf Guard] Slow route detected: /profile (load: 1.9s) (hydration: 0.8s)Dev-Only Behavior
nextjs-performance-guard automatically disables itself when:
NODE_ENV === "production"- Running in a production build
- Server-side rendering (SSR) contexts
All performance monitoring logic is guarded behind development checks, ensuring zero runtime overhead in production.
API Reference
withPerformanceGuard<T>(Component, config?)
Wraps a React component to monitor render performance.
Returns: The same component type, wrapped with performance monitoring.
analyzeClientBundle(config?)
Analyzes the current page's client-side JavaScript bundle size.
Returns: Promise<BundleMetrics | null> (null in production or if under threshold).
analyzeRoutes(config?)
Creates a route analyzer instance that tracks load times, hydration delays, and navigation latency.
Returns: RouteAnalyzer instance with methods:
getMetrics(route?): Get metrics for a specific route or all routesmeasureNavigation(): Manually trigger navigation measurementreset(): Clear all collected metrics
Reset Functions
resetComponentGuard(): Clear component metricsresetBundleGuard(): Clear bundle analysis cacheresetRouteAnalyzer(): Clear route metrics
Limitations
- Development Only: Performance monitoring only works in development mode
- Client-Side Only: Bundle and route analysis require browser APIs
- Heuristic-Based: Component file size estimation is approximate
- Next.js 13+: Requires Next.js 13 or higher (App Router or Pages Router)
- React 18+: Requires React 18 or higher
License
MIT
Contributing
Contributions welcome! Please open an issue or pull request.
