Loading...
Loading...
Optimize Next.js 15 applications for performance, Core Web Vitals, and production best practices using App Router patterns
npx skill4agent add atman36/ai-vibe-prompts nextjs-optimizationnext# Read package.json
# Check for "next": "^15.0.0" or higherapp/layout.tsxpage.tsxpages/// app/dashboard/page.tsx
export default async function DashboardPage() {
const data = await fetchData(); // Runs on server
return <Dashboard data={data} />;
}# Search for "use client" in components that don't need it
grep -r "use client" app/ | grep -v "onClick\|useState\|useEffect"// app/components/Counter.tsx
'use client';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}export const revalidate = 3600; // Revalidate every hour
export default async function BlogPost({ params }) {
const post = await getPost(params.slug);
return <Article post={post} />;
}export const revalidate = 60; // Revalidate every minute
export async function generateStaticParams() {
const products = await getProducts();
return products.map((p) => ({ slug: p.slug }));
}grep -rn "<img " app/ src/import Image from 'next/image';
<Image
src="/hero.jpg"
alt="Hero image"
width={1200}
height={600}
priority // For above-the-fold images
placeholder="blur" // Optional blur-up effect
/>module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
},
],
formats: ['image/avif', 'image/webp'], // Modern formats
},
};// app/layout.tsx
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap', // Prevent FOIT
variable: '--font-inter',
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={inter.variable}>
<body>{children}</body>
</html>
);
}import localFont from 'next/font/local';
const customFont = localFont({
src: './fonts/CustomFont.woff2',
display: 'swap',
variable: '--font-custom',
});const user = await getUser();
const posts = await getPosts(user.id); // Waits for userconst [user, posts] = await Promise.all([
getUser(),
getPosts(),
]);import { Suspense } from 'react';
export default function Page() {
return (
<>
<Header />
<Suspense fallback={<Skeleton />}>
<SlowComponent />
</Suspense>
<Footer />
</>
);
}// Aggressive caching
fetch('https://api.example.com/data', {
next: { revalidate: 3600 }, // Cache for 1 hour
});
// No caching
fetch('https://api.example.com/data', {
cache: 'no-store', // Always fresh
});
// Opt out of caching
export const dynamic = 'force-dynamic';# Add to package.json scripts
npm run build
npx @next/bundle-analyzerfind app -name "*.tsx" -exec wc -l {} \; | sort -rn | head -10import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <Skeleton />,
ssr: false, // Skip SSR if not needed
});grep -rn "export \* from" app/// Anti-pattern
import { Button, Card, Modal } from '@/components';
// Optimized
import { Button } from '@/components/Button';// app/layout.tsx
export const metadata = {
title: {
default: 'My App',
template: '%s | My App',
},
description: 'Description for SEO',
openGraph: {
title: 'My App',
description: 'Description for social sharing',
images: ['/og-image.jpg'],
},
twitter: {
card: 'summary_large_image',
},
};export async function generateMetadata({ params }) {
const post = await getPost(params.slug);
return {
title: post.title,
description: post.excerpt,
openGraph: {
images: [post.ogImage],
},
};
}// next.config.js
module.exports = {
reactStrictMode: true,
poweredByHeader: false, // Security
compress: true, // Gzip compression
// Compiler optimizations
compiler: {
removeConsole: process.env.NODE_ENV === 'production',
},
// Image optimization
images: {
formats: ['image/avif', 'image/webp'],
deviceSizes: [640, 750, 828, 1080, 1200, 1920],
},
// React Compiler (Next.js 15)
experimental: {
reactCompiler: true,
},
};// package.json
{
"scripts": {
"dev": "next dev --turbo"
}
}priority// Preload critical resources
<link rel="preload" href="/hero.jpg" as="image" />import Script from 'next/script';
<Script
src="https://analytics.example.com"
strategy="lazyOnload" // Load after page interactive
/>font-display: swap/* Reserve space for ads/banners */
.ad-container {
min-height: 250px;
}// app/dashboard/page.tsx
export const revalidate = 3600; // ISR every hour
export const dynamic = 'auto'; // Automatic optimization
export const fetchCache = 'force-cache'; // Aggressive caching// Deduplicated and cached automatically
const user = await fetch('https://api.example.com/user');
// Revalidate tag-based
export const revalidate = 60;
export const tags = ['user', 'profile'];// app/layout.tsx
import { SpeedInsights } from '@vercel/speed-insights/next';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<SpeedInsights />
</body>
</html>
);
}# Run Lighthouse
npx lighthouse http://localhost:3000 --view
# Check Core Web Vitals
npm run build
npm run start
npx lighthouse http://localhost:3000 --only-categories=performancenext/imagenext/fontdisplay: swap<Suspense>next.config.js# Next.js Optimization Report
## Current Status
- **Next.js Version**: 15.0.3
- **Rendering**: App Router
- **React Version**: 19.0.0
## Issues Found
### 🔴 Critical (3)
1. **Unoptimized Images**: 12 `<img>` tags found
- Files: `app/page.tsx`, `app/about/page.tsx`
- Fix: Replace with `next/image`
2. **Large Client Bundle**: 342 KB (target: < 200 KB)
- Cause: Heavy chart library loaded synchronously
- Fix: Use dynamic import for `Chart` component
3. **Missing Font Optimization**: Using Google Fonts via <link>
- Fix: Migrate to `next/font/google`
### 🟡 Warnings (2)
1. **Sequential Data Fetching**: Waterfall detected in `app/dashboard/page.tsx`
2. **No Metadata**: Missing OpenGraph tags on 5 pages
## Optimizations Applied
✅ Enabled React Compiler in next.config.js
✅ Added image optimization config
✅ Configured proper cache headers
✅ Added Suspense boundaries to slow routes
## Performance Impact (Estimated)
- **Load Time**: 3.2s → 1.8s (-44%)
- **Bundle Size**: 342 KB → 198 KB (-42%)
- **LCP**: 3.1s → 2.3s (✅ Good)
- **FID**: 85ms → 45ms (✅ Good)
- **CLS**: 0.15 → 0.05 (✅ Good)
## Next Steps
1. Replace 12 `<img>` tags with `next/image`
2. Split Chart component with dynamic import
3. Add metadata to 5 pages
4. Run Lighthouse to verify improvementscodebase-analysisquality-gatesreact-patternstesting-strategy