Skip to content

borghei/Claude-Skills / engineering/senior-frontend

senior-frontend

Verified

Scaffold Next.js 16 or React + Vite 8 apps, generate components with tests and stories, and flag heavy bundle dependencies. Use when starting a React project, adding components or hooks, or reviewing frontend code or performance.

FileKindSize
SKILL.mdskill md12.2 KB
assets/sample-project-flawed/package.jsonmanifest413 B
assets/sample-project-flawed/src/App.tsxother268 B
assets/sample-project-sound/app/page.tsxother131 B
assets/sample-project-sound/next.config.jsscript255 B
assets/sample-project-sound/package.jsonmanifest476 B
assets/templates/component/client.tsx.tmplother297 B
assets/templates/component/hook.ts.tmplother826 B
assets/templates/component/index.ts.tmplother84 B
assets/templates/component/index_hook.ts.tmplother115 B
assets/templates/component/server.tsx.tmplother447 B
assets/templates/component/story.tsx.tmplother601 B
assets/templates/component/test.tsx.tmplother538 B
assets/templates/scaffold/config/eslint.config.mjs.tmplother190 B
assets/templates/scaffold/config/gitignore.tmplother246 B
assets/templates/scaffold/config/next.config.js.tmplother248 B
assets/templates/scaffold/config/postcss.config.js.tmplother151 B
assets/templates/scaffold/config/prettierrc.tmplother106 B
assets/templates/scaffold/config/tailwind.config.ts.tmplother1.3 KB
assets/templates/scaffold/config/tsconfig.json.tmplother572 B
assets/templates/scaffold/config/vite/eslint.config.js.tmplother361 B
assets/templates/scaffold/config/vite/index.html.tmplother303 B
assets/templates/scaffold/config/vite/postcss.config.js.tmplother149 B
assets/templates/scaffold/config/vite/tsconfig.app.json.tmplother649 B
assets/templates/scaffold/config/vite/tsconfig.json.tmplother119 B
assets/templates/scaffold/config/vite/tsconfig.node.json.tmplother557 B
assets/templates/scaffold/config/vite/vite.config.ts.tmplother282 B
assets/templates/scaffold/files/api_client.tsscript2.1 KB
assets/templates/scaffold/files/auth_client.tsscript1.3 KB
assets/templates/scaffold/files/auth_lib.tsscript2.7 KB
assets/templates/scaffold/files/auth_page.tsxother281 B
assets/templates/scaffold/files/auth_proxy.tsscript525 B
assets/templates/scaffold/files/constants.tsscript327 B
assets/templates/scaffold/files/empty.txtmarkdown0 B
assets/templates/scaffold/files/form_field.tsxother1.7 KB
assets/templates/scaffold/files/form_utils.tsscript762 B
assets/templates/scaffold/files/globals_css.cssother856 B
assets/templates/scaffold/files/health_route.tsscript171 B
assets/templates/scaffold/files/home_page.tsxother304 B
assets/templates/scaffold/files/hook_debounce.tsscript357 B
assets/templates/scaffold/files/hook_local_storage.tsscript659 B
assets/templates/scaffold/files/layout_footer.tsxother265 B
assets/templates/scaffold/files/layout_header.tsxother518 B
assets/templates/scaffold/files/layout_sidebar.tsxother287 B
assets/templates/scaffold/files/login_form.tsxother2.2 KB
assets/templates/scaffold/files/query_client.tsscript662 B
assets/templates/scaffold/files/query_provider.tsxother353 B
assets/templates/scaffold/files/react_app.tsxother403 B
assets/templates/scaffold/files/react_main.tsxother236 B
assets/templates/scaffold/files/register_form.tsxother3.2 KB
assets/templates/scaffold/files/require_auth.tsxother821 B
assets/templates/scaffold/files/root_layout.tsxother512 B
assets/templates/scaffold/files/storybook_main_next.tsscript302 B
assets/templates/scaffold/files/storybook_main_react.tsscript231 B
assets/templates/scaffold/files/storybook_preview_next.tsscript264 B
assets/templates/scaffold/files/storybook_preview_react.tsscript261 B
assets/templates/scaffold/files/test_setup.tsscript244 B
assets/templates/scaffold/files/test_utils.tsxother541 B
assets/templates/scaffold/files/types_index.tsscript309 B
assets/templates/scaffold/files/ui_button.tsxother1.4 KB
assets/templates/scaffold/files/ui_card.tsxother984 B
assets/templates/scaffold/files/ui_index.tsscript147 B
assets/templates/scaffold/files/ui_input.tsxother1.1 KB
assets/templates/scaffold/files/utils.tsscript478 B
assets/templates/scaffold/files/vitest_config_next.tsscript438 B
assets/templates/scaffold/files/vitest_config_react.tsscript389 B
assets/templates/scaffold/manifest.jsonconfig12.6 KB
references/bundle_rules.jsonconfig3.4 KB
references/code-patterns.mdmarkdown5.7 KB
references/frontend_best_practices.mdmarkdown19.4 KB
references/nextjs_optimization_guide.mdmarkdown17.3 KB
references/react_patterns.mdmarkdown16.9 KB
references/tooling-guide.mdmarkdown15.1 KB
scripts/bundle_analyzer.pyexecutablescript11.6 KB
scripts/component_generator.pyexecutablescript8.5 KB
scripts/frontend_scaffolder.pyexecutablescript11.0 KB

references/nextjs_optimization_guide.md

View on GitHub
# Next.js Optimization Guide

Performance optimization techniques for Next.js 16 applications.

---

## Table of Contents

- [Rendering Strategies](#rendering-strategies)
- [Image Optimization](#image-optimization)
- [Code Splitting](#code-splitting)
- [Data Fetching](#data-fetching)
- [Caching Strategies](#caching-strategies)
- [Bundle Optimization](#bundle-optimization)
- [Core Web Vitals](#core-web-vitals)

---

## Rendering Strategies

### Server Components (Default)

Server Components render on the server and send HTML to the client. Use for data-heavy, non-interactive content.

```tsx
// app/products/page.tsx - Server Component (default)
async function ProductsPage() {
  // This runs on the server - no client bundle impact
  const products = await db.products.findMany();

  return (
    <div className="grid grid-cols-3 gap-4">
      {products.map(product => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
}
```

### Client Components

Use `'use client'` only when you need:
- Event handlers (onClick, onChange)
- State (useState, useReducer)
- Effects (useEffect)
- Browser APIs (window, document)

```tsx
'use client';

import { useState } from 'react';

function AddToCartButton({ productId }: { productId: string }) {
  const [isAdding, setIsAdding] = useState(false);

  async function handleClick() {
    setIsAdding(true);
    await addToCart(productId);
    setIsAdding(false);
  }

  return (
    <button onClick={handleClick} disabled={isAdding}>
      {isAdding ? 'Adding...' : 'Add to Cart'}
    </button>
  );
}
```

### Mixing Server and Client Components

```tsx
// app/products/[id]/page.tsx - Server Component
async function ProductPage({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);

  return (
    <div>
      {/* Server-rendered content */}
      <h1>{product.name}</h1>
      <p>{product.description}</p>

      {/* Client component for interactivity */}
      <AddToCartButton productId={product.id} />

      {/* Server component for reviews */}
      <ProductReviews productId={product.id} />
    </div>
  );
}
```

### Static vs Dynamic Rendering

```tsx
// Force static generation at build time
export const dynamic = 'force-static';

// Force dynamic rendering at request time
export const dynamic = 'force-dynamic';

// Revalidate every 60 seconds (ISR)
export const revalidate = 60;

// Revalidate on-demand from a Server Action
'use server';
import { revalidatePath, updateTag } from 'next/cache';

export async function updateProduct(id: string, data: ProductData) {
  await db.products.update({ where: { id }, data });

  // Revalidate a specific path
  revalidatePath(`/products/${id}`);

  // Or expire a tag so the editor sees the change on the next request
  updateTag('products');
}
```

The segment exports (`dynamic`, `revalidate`) apply when Cache Components is off. With `cacheComponents: true`, data fetching is dynamic by default and you opt in with `'use cache'` (see [Caching Strategies](#caching-strategies)); follow the [migration guide](https://nextjs.org/docs/app/guides/migrating-to-cache-components) to replace segment configs.

---

## Image Optimization

### Next.js Image Component

```tsx
import Image from 'next/image';

// Basic optimized image
<Image
  src="/hero.jpg"
  alt="Hero image"
  width={1200}
  height={600}
  priority // Load immediately for LCP
/>

// Responsive image
<Image
  src="/product.jpg"
  alt="Product"
  fill
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  className="object-cover"
/>

// With placeholder blur
import productImage from '@/public/product.jpg';

<Image
  src={productImage}
  alt="Product"
  placeholder="blur" // Uses imported image data
/>
```

### Remote Images Configuration

```js
// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'cdn.example.com',
        pathname: '/images/**',
      },
      {
        protocol: 'https',
        hostname: '*.cloudinary.com',
      },
    ],
    // Image formats (webp is default)
    formats: ['image/avif', 'image/webp'],
    // Device sizes for srcset
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    // Image sizes for srcset
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },
};
```

### Lazy Loading Patterns

```tsx
// Images below the fold - lazy load (default)
<Image
  src="/gallery/photo1.jpg"
  alt="Gallery photo"
  width={400}
  height={300}
  loading="lazy" // Default behavior
/>

// Above the fold - load immediately
<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority
  loading="eager"
/>
```

---

## Code Splitting

### Dynamic Imports

```tsx
import dynamic from 'next/dynamic';

// Basic dynamic import
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
  loading: () => <ChartSkeleton />,
});

// Disable SSR for client-only components
const MapComponent = dynamic(() => import('@/components/Map'), {
  ssr: false,
  loading: () => <div className="h-[400px] bg-gray-100" />,
});

// Named exports
const Modal = dynamic(() =>
  import('@/components/ui').then(mod => mod.Modal)
);

// With suspense
const DashboardCharts = dynamic(() => import('@/components/DashboardCharts'), {
  loading: () => <Suspense fallback={<ChartsSkeleton />} />,
});
```

### Route-Based Splitting

```tsx
// app/dashboard/analytics/page.tsx
// This page only loads when /dashboard/analytics is visited
import { Suspense } from 'react';
import AnalyticsCharts from './AnalyticsCharts';

export default function AnalyticsPage() {
  return (
    <Suspense fallback={<AnalyticsSkeleton />}>
      <AnalyticsCharts />
    </Suspense>
  );
}
```

### Parallel Routes for Code Splitting

```
app/
├── dashboard/
│   ├── @analytics/
│   │   └── page.tsx    # Loaded in parallel
│   ├── @metrics/
│   │   └── page.tsx    # Loaded in parallel
│   ├── layout.tsx
│   └── page.tsx
```

```tsx
// app/dashboard/layout.tsx
export default function DashboardLayout({
  children,
  analytics,
  metrics,
}: {
  children: React.ReactNode;
  analytics: React.ReactNode;
  metrics: React.ReactNode;
}) {
  return (
    <div className="grid grid-cols-2 gap-4">
      {children}
      <Suspense fallback={<AnalyticsSkeleton />}>{analytics}</Suspense>
      <Suspense fallback={<MetricsSkeleton />}>{metrics}</Suspense>
    </div>
  );
}
```

---

## Data Fetching

### Server-Side Data Fetching

```tsx
// Parallel data fetching
async function Dashboard() {
  // Start both requests simultaneously
  const [user, stats, notifications] = await Promise.all([
    getUser(),
    getStats(),
    getNotifications(),
  ]);

  return (
    <div>
      <UserHeader user={user} />
      <StatsPanel stats={stats} />
      <NotificationList notifications={notifications} />
    </div>
  );
}
```

### Streaming with Suspense

```tsx
import { Suspense } from 'react';

async function ProductPage({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);

  return (
    <div>
      {/* Immediate content */}
      <h1>{product.name}</h1>
      <p>{product.description}</p>

      {/* Stream reviews - don't block page */}
      <Suspense fallback={<ReviewsSkeleton />}>
        <Reviews productId={params.id} />
      </Suspense>

      {/* Stream recommendations */}
      <Suspense fallback={<RecommendationsSkeleton />}>
        <Recommendations productId={params.id} />
      </Suspense>
    </div>
  );
}

// Slow data component
async function Reviews({ productId }: { productId: string }) {
  const reviews = await getReviews(productId); // Slow query
  return <ReviewList reviews={reviews} />;
}
```

### Request Memoization

```tsx
// Next.js automatically dedupes identical requests
async function Layout({ children }) {
  const user = await getUser(); // Request 1
  return <div>{children}</div>;
}

async function Header() {
  const user = await getUser(); // Same request - cached!
  return <div>Hello, {user.name}</div>;
}

// Both components call getUser() but only one request is made
```

---

## Caching Strategies

Next.js 16 sources: [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache), [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife), [`cacheTag`](https://nextjs.org/docs/app/api-reference/functions/cacheTag), [`revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag), [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag), [`cacheComponents`](https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents) (checked November 2026).

### Fetch Cache Options

```tsx
// Not cached by default (since Next 15): opt in explicitly
fetch('https://api.example.com/data', { cache: 'force-cache' });

// Always fresh
fetch('https://api.example.com/data', { cache: 'no-store' });

// Revalidate after time
fetch('https://api.example.com/data', {
  next: { revalidate: 3600 } // 1 hour
});

// Tag-based revalidation
fetch('https://api.example.com/products', {
  next: { tags: ['products'] }
});

// Later, revalidate by tag. Next 16 requires a profile as the second argument:
// 'max' serves stale content while it refreshes (stale-while-revalidate).
// The single-argument form is deprecated.
import { revalidateTag } from 'next/cache';
revalidateTag('products', 'max');

// From a webhook or Route Handler that needs the data gone now:
revalidateTag('products', { expire: 0 });
```

| Function | Where it runs | Behaviour |
|----------|---------------|-----------|
| `updateTag(tag)` | Server Actions only | Expires the tag; the next request waits for fresh data (read-your-own-writes) |
| `revalidateTag(tag, 'max')` | Server Actions, Route Handlers | Marks stale; visitors get stale content while it refreshes |
| `revalidateTag(tag, { expire: 0 })` | Server Actions, Route Handlers | Expires immediately, for webhooks where `updateTag` is not available |
| `revalidatePath(path)` | Server Actions, Route Handlers | Invalidates one page or layout path |

### Route Segment Config

```tsx
// app/products/page.tsx

// Revalidate every hour
export const revalidate = 3600;

// Or force dynamic
export const dynamic = 'force-dynamic';

// Generate static params at build
export async function generateStaticParams() {
  const products = await getProducts();
  return products.map(p => ({ id: p.id }));
}
```

### `use cache` for Custom Caching (Cache Components)

Enable it once in `next.config.ts`:

```ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true, // set explicitly; leaving it unset logs a warning
};

export default nextConfig;
```

Then mark async functions, components or whole files as cacheable. Give every scope an explicit `cacheLife` and tag what you will invalidate:

```tsx
import { cacheLife, cacheTag } from 'next/cache';

export async function getUser(userId: string) {
  'use cache';
  cacheLife('hours'); // presets: seconds, minutes, hours, days, weeks, max
  cacheTag('users', `user-${userId}`);
  return db.users.findUnique({ where: { id: userId } });
}

// In a Server Action after a write:
// updateTag(`user-${userId}`);
```

Arguments become the cache key and must be serializable; `cookies()` and `headers()` cannot be read inside a cached scope, so read them outside and pass the values in. `unstable_cache` still exists for data that must survive a redeploy (`use cache` entries are keyed by build ID), but for new code prefer `use cache`.

---

## Bundle Optimization

### Analyze Bundle Size

```bash
# Install analyzer
npm install @next/bundle-analyzer

# Update next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  // config
});

# Run analysis
ANALYZE=true npm run build
```

### Tree Shaking Imports

```tsx
// BAD - Imports entire library
import _ from 'lodash';
const result = _.debounce(fn, 300);

// GOOD - Import only what you need
import debounce from 'lodash/debounce';
const result = debounce(fn, 300);

// GOOD - Named imports (tree-shakeable)
import { debounce } from 'lodash-es';
```

### Optimize Dependencies

```js
// next.config.js
module.exports = {
  // Transpile specific packages
  transpilePackages: ['ui-library', 'shared-utils'],

  // Optimize package imports
  experimental: {
    optimizePackageImports: ['lucide-react', '@heroicons/react'],
  },

  // External packages for server
  serverExternalPackages: ['sharp', 'bcrypt'],
};
```

### Font Optimization

```tsx
// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
});

const robotoMono = Roboto_Mono({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-roboto-mono',
});

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={`${inter.variable} ${robotoMono.variable}`}>
      <body className="font-sans">{children}</body>
    </html>
  );
}
```

---

## Core Web Vitals

### Largest Contentful Paint (LCP)

```tsx
// Optimize LCP hero image
import Image from 'next/image';

export default function Hero() {
  return (
    <section className="relative h-[600px]">
      <Image
        src="/hero.jpg"
        alt="Hero"
        fill
        priority // Preload for LCP
        sizes="100vw"
        className="object-cover"
      />
      <div className="relative z-10">
        <h1>Welcome</h1>
      </div>
    </section>
  );
}

// Preload critical resources in layout
export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <link rel="preload" href="/hero.jpg" as="image" />
        <link rel="preconnect" href="https://fonts.googleapis.com" />
      </head>
      <body>{children}</body>
    </html>
  );
}
```

### Cumulative Layout Shift (CLS)

```tsx
// Prevent CLS with explicit dimensions
<Image
  src="/product.jpg"
  alt="Product"
  width={400}
  height={300}
/>

// Or use aspect ratio
<div className="aspect-video relative">
  <Image src="/video-thumb.jpg" alt="Video" fill />
</div>

// Skeleton placeholders
function ProductCard({ product }: { product?: Product }) {
  if (!product) {
    return (
      <div className="animate-pulse">
        <div className="h-48 bg-gray-200 rounded" />
        <div className="h-4 bg-gray-200 rounded mt-2 w-3/4" />
        <div className="h-4 bg-gray-200 rounded mt-1 w-1/2" />
      </div>
    );
  }

  return (
    <div>
      <Image src={product.image} alt={product.name} width={300} height={200} />
      <h3>{product.name}</h3>
      <p>{product.price}</p>
    </div>
  );
}
```

### First Input Delay (FID) / Interaction to Next Paint (INP)

```tsx
// Defer non-critical JavaScript
import Script from 'next/script';

export default function Layout({ children }) {
  return (
    <html>
      <body>
        {children}

        {/* Load analytics after page is interactive */}
        <Script
          src="https://analytics.example.com/script.js"
          strategy="afterInteractive"
        />

        {/* Load chat widget when idle */}
        <Script
          src="https://chat.example.com/widget.js"
          strategy="lazyOnload"
        />
      </body>
    </html>
  );
}

// Use web workers for heavy computation
// app/components/DataProcessor.tsx
'use client';

import { useEffect, useState } from 'react';

function DataProcessor({ data }: { data: number[] }) {
  const [result, setResult] = useState<number | null>(null);

  useEffect(() => {
    const worker = new Worker(new URL('../workers/processor.js', import.meta.url));

    worker.postMessage(data);
    worker.onmessage = (e) => setResult(e.data);

    return () => worker.terminate();
  }, [data]);

  return <div>Result: {result}</div>;
}
```

### Measuring Performance

```tsx
// app/components/PerformanceMonitor.tsx
'use client';

import { useReportWebVitals } from 'next/web-vitals';

export function PerformanceMonitor() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'LCP':
        console.log('LCP:', metric.value);
        break;
      case 'FID':
        console.log('FID:', metric.value);
        break;
      case 'CLS':
        console.log('CLS:', metric.value);
        break;
      case 'TTFB':
        console.log('TTFB:', metric.value);
        break;
    }

    // Send to analytics
    analytics.track('web-vital', {
      name: metric.name,
      value: metric.value,
      id: metric.id,
    });
  });

  return null;
}
```

---

## Quick Reference

### Performance Checklist

| Area | Optimization | Impact |
|------|-------------|--------|
| Images | Use next/image with priority for LCP | High |
| Fonts | Use next/font with display: swap | Medium |
| Code | Dynamic imports for heavy components | High |
| Data | Parallel fetching with Promise.all | High |
| Render | Server Components by default | High |
| Cache | Configure revalidate appropriately | Medium |
| Bundle | Tree-shake imports, analyze size | Medium |

### Config Template

```js
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [{ hostname: 'cdn.example.com' }],
    formats: ['image/avif', 'image/webp'],
  },
  experimental: {
    optimizePackageImports: ['lucide-react'],
  },
  headers: async () => [
    {
      source: '/(.*)',
      headers: [
        { key: 'X-Content-Type-Options', value: 'nosniff' },
        { key: 'X-Frame-Options', value: 'DENY' },
      ],
    },
  ],
};

module.exports = nextConfig;
```
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall