Works with the AI Agents you already use

    React & Next.js Performance & Bundle Optimizer

    by Tushar

    1

    - Icon and utility barrels (lucide-react, lodash, @mui/material) fail Webpack tree-shaking, packaging thousands of unused modules.

    $5.67

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned
    React & Next.js Performance & Bundle Optimizer

    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:

    1. Server Boundary Leak: Top-level "use client" coupled with direct @prisma/client import in client bundle.
    2. Barrel Bloat: Monolithic imports from lucide-react and lodash importing full barrel packages.
    3. Unsplit Heavy Widget: Synchronous import of chart.js (~180KB) loaded on initial critical path.
    4. N+1 ORM Query Loop: prisma.user.findUnique executed inside a for...of loop over orders.
    5. Sequential Waterfall: Independent database queries for orders and site stats awaiting sequentially.
    MetricBefore (Leaky Dashboard)After (Optimized Architecture)Improvement
    Client Bundle Size~1,240 KB~48 KB (Leaf UI only)-96.1% JS payload
    Database Roundtrips1 + 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 Efficiency0% (Full barrel bundled)100% (Subpath / Compiler optimized)Zero dead-code icons
    Server SecurityDatabase driver exposed in clientDatabase isolated strictly on serverZero 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

    1. Run ANALYZE=true npm run build to verify client bundle footprint with @next/bundle-analyzer.
    2. Integrate python scripts/bundle_perf_auditor.py src/ --fail-on critical into your PR validation workflow.
    3. Ensure all backend data access files in lib/db/ include import 'server-only'.

    page.tsx

    PDF · document

    Generated

    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 of page.tsx or layout.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

    1. 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.
    2. Tree-Shaking & Barrel Optimization: Deconstructs monolithic imports from lucide-react, lodash, @mui/material, and date-fns. Configures experimental.optimizePackageImports in next.config.js to eliminate dead code.
    3. 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 with Promise.all.
    4. Code Splitting & Dynamic Bundles: Isolates heavy visualization libraries (Chart.js, Recharts, Monaco) using next/dynamic with { 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 featuring optimizePackageImports and 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. 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. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 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

    Terminal / Shell
    Read Files
    Write Files

    File Scopes

    app/**
    src/**
    components/**
    lib/**
    next.config.*
    Listed12 days ago

    What's inside

    Frequently Asked Questions

    This skill identifies and resolves 'boundary leaks' where server-side logic or heavy dependencies accidentally end up in your client bundle, significantly reducing your Time-to-First-Byte (TTFB) and bundle size.

    It is specifically tuned for Next.js 14 and 15 using the App Router, and it provides deep integration support for projects using Prisma or Drizzle ORM to resolve database N+1 issues.

    You receive the `bundle_perf_auditor.py` script for deep codebase analysis, a library of specific refactoring patterns for App Router boundaries, and optimized configuration templates for your build pipeline.

    Yes, this skill is designed to work within your existing IDE or AI agent workflow by providing structured reports and refactoring instructions that your AI can execute against your local file system.

    The skill excels at static analysis and pattern matching for App Router architecture; however, it may not detect dependencies loaded through complex dynamic runtime evaluations.

    Updates are released to coincide with major Next.js and React releases, ensuring the optimization patterns remain compatible with the latest changes in Server Components and Turbopack.

    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.