- Home
- Skills
- Frontend & Web Apps
- React & Next.js Performance & Bundle Optimizer
Works with the AI Agents you already use
React & Next.js Performance & Bundle Optimizer
by Tushar
- Icon and utility barrels (lucide-react, lodash, @mui/material) fail Webpack tree-shaking, packaging thousands of unused modules.
$5.67
React & Next.js Performance & Bundle Optimizer
Example session with this skill installed
Our Next.js 14 App Router dashboard is slow to load, and bundle analysis shows a 1.2MB client bundle on /dashboard. The page imports Prisma directly, uses lucide-react icons, loads Chart.js, and loops over orders to fetch user details. Audit this page for boundary leaks, barrel bloat, and N+1 queries, then provide a refactored solution.
- Read your context and instructions
- Compiled the react & next
- Generated the document
Summary
Audited dashboard/page.tsx using the bundled performance auditor. Identified 7 critical and warning-level architectural violations:
- Server Boundary Leak: Top-level
"use client"coupled with direct@prisma/clientimport in client bundle. - Barrel Bloat: Monolithic imports from
lucide-reactandlodashimporting full barrel packages. - Unsplit Heavy Widget: Synchronous import of
chart.js(~180KB) loaded on initial critical path. - N+1 ORM Query Loop:
prisma.user.findUniqueexecuted inside afor...ofloop over orders. - Sequential Waterfall: Independent database queries for orders and site stats awaiting sequentially.
| Metric | Before (Leaky Dashboard) | After (Optimized Architecture) | Improvement |
|---|---|---|---|
| Client Bundle Size | ~1,240 KB | ~48 KB (Leaf UI only) | -96.1% JS payload |
| Database Roundtrips | 1 + N (21 roundtrips for 20 orders) | 2 parallel batch queries | -90.5% DB roundtrips |
| Initial TTFB | ~850 ms (Sequential network waterfall) | ~190 ms (Parallel Server Component) | 4.4x faster initial render |
| Tree-Shaking Efficiency | 0% (Full barrel bundled) | 100% (Subpath / Compiler optimized) | Zero dead-code icons |
| Server Security | Database driver exposed in client | Database isolated strictly on server | Zero credential exposure |
1. Refactored Server Component (page.tsx)
// React Server Component (Zero Client Bundle Payload)
import React, { Suspense, cache } from 'react';
import dynamic from 'next/dynamic';
import LayoutDashboard from 'lucide-react/dist/esm/icons/layout-dashboard';
import CreditCard from 'lucide-react/dist/esm/icons/credit-card';
import Users from 'lucide-react/dist/esm/icons/users';
import prisma from '@/lib/db';
// Lazy-load heavy visualization library (isolated from initial JS bundle)
const SalesChart = dynamic(() => import('@/components/SalesChart'), {
ssr: false,
loading: () => <div className="h-48 animate-pulse bg-muted rounded" />,
});
// Request-scoped deduplicated data fetcher
const getDashboardData = cache(async () => {
// 1. Parallelize independent initial queries (Zero Waterfall)
const [orders, stats] = await Promise.all([
prisma.order.findMany({ take: 20 }),
prisma.siteStat.findFirst()
]);
// 2. Batch N+1 query: Gather unique user IDs and fetch in one roundtrip
const userIds = Array.from(new Set(orders.map(o => o.userId)));
const users = await prisma.user.findMany({
where: { id: { in: userIds } }
});
// 3. Fast O(1) in-memory correlation
const userMap = new Map(users.map(u => [u.id, u.name]));
const enrichedOrders = orders.map(o => ({
...o,
userName: userMap.get(o.userId) ?? 'Unknown',
}));
return { orders: enrichedOrders, stats };
});
export default async function DashboardPage() {
const { orders, stats } = await getDashboardData();
const totalRevenue = orders.reduce((sum, o) => sum + o.amount, 0);
return (
<div className="p-8">
<header className="flex items-center gap-2 mb-6">
<LayoutDashboard className="w-6 h-6" />
<h1 className="text-2xl font-bold">Sales Overview</h1>
</header>
<div className="grid grid-cols-2 gap-4 mb-6">
<div className="border p-4 rounded">
<div className="flex items-center gap-2 text-muted">
<CreditCard className="w-4 h-4" />
<span>Total Revenue</span>
</div>
<p className="text-xl font-semibold">${totalRevenue.toLocaleString()}</p>
</div>
<div className="border p-4 rounded">
<div className="flex items-center gap-2 text-muted">
<Users className="w-4 h-4" />
<span>Processed Orders</span>
</div>
<p className="text-xl font-semibold">{orders.length}</p>
</div>
</div>
<Suspense fallback={<div>Loading chart...</div>}>
<SalesChart revenue={totalRevenue} />
</Suspense>
</div>
);
}
2. Next.js Compiler Tuning (next.config.mjs)
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
optimizePackageImports: ['lucide-react', 'lodash-es'],
},
serverExternalPackages: ['@prisma/client'],
};
export default nextConfig;
3. Verification Report via Bundled CLI
$ python scripts/bundle_perf_auditor.py app/dashboard/page.tsx
========================================================================
REACT & NEXT.JS PERFORMANCE & BUNDLE AUDITOR
========================================================================
Target: app/dashboard/page.tsx
Total Rules: 9 (Boundary Leaks, Barrel Traps, N+1 Queries, Waterfalls)
Violations: 0 finding(s) (Filtered by >= INFO)
------------------------------------------------------------------------
Summary: CRITICAL: 0 | WARNING: 0 | INFO: 0
------------------------------------------------------------------------
[OK] No performance or bundle optimization issues detected.
========================================================================
Next steps
- Run
ANALYZE=true npm run buildto verify client bundle footprint with@next/bundle-analyzer. - Integrate
python scripts/bundle_perf_auditor.py src/ --fail-on criticalinto your PR validation workflow. - Ensure all backend data access files in
lib/db/includeimport 'server-only'.
page.tsx
PDF · document
Example file from a real run - the skill writes it into your workspace.
Connects securely to your tools. The creator never sees your data.
About this skill
Stop Shipping Bloated Next.js Bundles and Latency Waterfalls
Full-stack React with the Next.js App Router promises zero-bundle server rendering and fast page loads. In practice, codebases degrade quickly:
- Developers slap
"use client"at the top ofpage.tsxorlayout.tsx, forcing entire page subtrees and dependencies into the client JavaScript bundle. - Backend database packages like
@prisma/client,drizzle-orm, or crypto libraries accidentally get imported into client-rendered components, inflating bundle sizes by hundreds of kilobytes. - Icon and utility barrels (
lucide-react,lodash,@mui/material) fail Webpack tree-shaking, packaging thousands of unused modules. - Server Components execute ORM database queries inside loops or
.map()callbacks, causing severe N+1 latency roundtrips and blocking page streaming.
React & Next.js Performance & Bundle Optimizer turns your AI coding agent (Claude Code, Cursor, Copilot, Antigravity, or local LLMs) into a Senior Performance Architect that detects and refactors these bottlenecks.
The 4-Vector Optimization Architecture
- Client/Server Boundary Enforcement: Pushes
"use client"down from page roots to isolated interactive leaf components. Flags any server-only or database imports that leak into client bundles. - Tree-Shaking & Barrel Optimization: Deconstructs monolithic imports from
lucide-react,lodash,@mui/material, anddate-fns. Configuresexperimental.optimizePackageImportsinnext.config.jsto eliminate dead code. - N+1 ORM & Query Waterfall Elimination: Detects Prisma, Drizzle, and SQL queries invoked inside loops. Rewrites them into batched queries (
where: { id: { in: ids } }) and parallelizes independent awaits withPromise.all. - Code Splitting & Dynamic Bundles: Isolates heavy visualization libraries (Chart.js, Recharts, Monaco) using
next/dynamicwith{ ssr: false }, shedding hundreds of kilobytes from initial page loads.
Included Tools & Examples
scripts/bundle_perf_auditor.py: Offline CLI that scans code for boundary leaks, barrel traps, and N+1 query loops with exact line numbers and remediation snippets.examples/leaky_dashboard.tsx: Typical anti-pattern dashboard exhibiting root"use client", Prisma client leak, monolithic barrel imports, and N+1 query loops.examples/optimized_dashboard.tsx: Fully refactored implementation demonstrating zero client bundle overhead, batched database queries, and parallel data loading.examples/next.config.mjs: Production Next.js configuration featuringoptimizePackageImportsand bundle analyzer setup.
Requires Next.js App Router for boundary optimizations. Static analysis might miss complex dynamic imports or non-standard ORM patterns.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 12 days ago
- Software
Python 3.9+
Operates 100% locally on your machine. Inspects code ASTs offline without sending code or tokens to third-party servers. No credentials, environment keys, or network access required.
Permissions
File Scopes
What's inside
Frequently Asked Questions
New in Frontend & Web Apps
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Frontend & Web Apps.