/nextjs-performance-audit
Comprehensive Next.js performance audit with actionable optimization recommendations
$ npx -y skills add davila7/claude-code-templates --agent claude-codeHow it fires
How this command gets triggered: by you, by Claude, or both.
- Fires itselfClaude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/nextjs-performance-audit
Context preview
What this command does when you run it.
Comprehensive Next.js performance audit with actionable optimization recommendations
Command definition
nextjs-performance-audit.mdallowed-tools: Read, Edit, Bash
argument-hint: [--lighthouse] [--bundle] [--runtime] [--all]
description: Comprehensive Next.js performance audit with actionable optimization recommendations
Next.js Performance Audit
**Audit Type**: $ARGUMENTS
Current Application Analysis
Application State
- Build status: !`ls -la .next/ 2>/dev/null || echo "No build found - run 'npm run build' first"`
- Application running: !`curl -s http://localhost:3000 > /dev/null && echo "App is running" || echo "App not running - start with 'npm run dev'"`
- Bundle analysis: !`ls -la .next/analyze/ 2>/dev/null || echo "No bundle analysis found"`
Project Configuration
- Next.js config: @next.config.js
- Package.json: @package.json
- TypeScript config: @tsconfig.json (if exists)
- Vercel config: @vercel.json (if exists)
Performance Monitoring Setup
- Web Vitals: Check for @next/web-vitals or similar
- Analytics: Check for Vercel Analytics or Google Analytics
- Monitoring tools: Check for Sentry, DataDog, or other APM tools
Performance Audit Framework
1. Lighthouse Audit
# Install Lighthouse CLI if not available
npm install -g lighthouse
# Run Lighthouse audit
lighthouse http://localhost:3000 \
--output=json \
--output=html \
--output-path=./performance-audit \
--chrome-flags="--headless" \
--preset=perf
# Mobile performance audit
lighthouse http://localhost:3000 \
--output=json \
--output-path=./performance-audit-mobile \
--preset=perf \
--form-factor=mobile \
--throttling-method=devtools \
--chrome-flags="--headless"
# Generate detailed report
lighthouse http://localhost:3000 \
--output=html \
--output-path=./lighthouse-report.html \
--view
2. Bundle Analysis
// next.config.js - Enable bundle analysis
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// ... your config
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Bundle analysis optimizations
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
};
}
return config;
},
});3. Runtime Performance Analysis
# Build and analyze bundle
ANALYZE=true npm run build
# Check bundle sizes
ls -lah .next/static/chunks/ | grep -E "\\.js$" | sort -k5 -hr | head -10
# Analyze dependencies
npm ls --depth=0 --prod | grep -v "deduped"
# Check for duplicate dependencies
npm ls --depth=0 | grep -E "UNMET|invalid"
Performance Metrics Collection
1. Core Web Vitals Implementation
// lib/analytics.ts
export function reportWebVitals({ id, name, label, value }: any) {
// Send to analytics service
if (typeof window !== 'undefined') {
// Client-side reporting
fetch('/api/analytics/web-vitals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id,
name,
label,
value,
url: window.location.href,
timestamp: Date.now(),
}),
}).catch(console.error);
}
}
// Track specific metrics
export function trackMetric(name: string, value: number, labels?: Record<string, string>) {
reportWebVitals({
id: `${name}-${Date.now()}`,
name,
label: 'custom',
value,
...labels,
});
}
// Performance observer for custom metrics
export function initPerformanceObserver() {
if (typeof window === 'undefined') return;
// Largest Contentful Paint
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
trackMetric('LCP', entry.startTime);
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
// First Input Delay
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
trackMetric('FID', entry.processingStart - entry.startTime);
}
}).observe({ entryTypes: ['first-input'] });
// Cumulative Layout Shift
new PerformanceObserver((entryList) => {
let clsValue = 0;
for (const entry of entryList.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
trackMetric('CLS', clsValue);
}).observe({ entryTypes: ['layout-shift'] });
}2. Server-Side Performance Monitoring
// middleware.ts - Performance monitoring
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const start = Date.now();
const response = NextResponse.next();
// Add performance headers
response.headers.set('X-Response-Time', `${Date.now() - start}ms`);
response.headers.set('X-Timestamp', new Date().toISOString());
return response;
}Performance Analysis Areas
1. Loading Performance
// Analyze loading performance
const loadingPerformanceAudit = {
// First Contentful Paint (FCP)
fcp: {
target: '< 1.8s',
current: '?', // From Lighthouse
optimizations: [
'Optimize critical rendering path',
'Inline critical CSS',
'Preload key resources',
'Minimize render-blocking resources',
],
},
// Largest Contentful Paint (LCP)
lcp: {
target: '< 2.5s',
current: '?', // From Lighthouse
optimizations: [
'Optimize images (Next.js Image component)',
'Preload LCP element',
'Optimize server response time',
'Use CDN for static assets',
],
},
// Time to Interactive (TTI)
tti: {
target: '< 3.8s',
current: '?', // From Lighthouse
optimizations: [
'Reduce JavaScript bundle size',
'Code splitting',
'Remove unused code',
'Optimize third-party scripts',
],
},
// Speed Index
speedIndex: {
target: '< 3.4s',Read more
allowed-tools: Read, Edit, Bash argument-hint: [--lighthouse] [--bundle] [--runtime] [--all] description: Comprehensive Next.js performance audit with actionable optimization recommendations
Next.js Performance Audit
**Audit Type**: $ARGUMENTS
Current Application Analysis
Application State
- Build status: !`ls -la .next/ 2>/dev/null || echo "No build found - run 'npm run build' first"`
- Application running: !`curl -s http://localhost:3000 > /dev/null && echo "App is running" || echo "App not running - start with 'npm run dev'"`
- Bundle analysis: !`ls -la .next/analyze/ 2>/dev/null || echo "No bundle analysis found"`
Project Configuration
- Next.js config: @next.config.js
- Package.json: @package.json
- TypeScript config: @tsconfig.json (if exists)
- Vercel config: @vercel.json (if exists)
Performance Monitoring Setup
- Web Vitals: Check for @next/web-vitals or similar
- Analytics: Check for Vercel Analytics or Google Analytics
- Monitoring tools: Check for Sentry, DataDog, or other APM tools
Performance Audit Framework
1. Lighthouse Audit
# Install Lighthouse CLI if not available npm install -g lighthouse # Run Lighthouse audit lighthouse http://localhost:3000 \ --output=json \ --output=html \ --output-path=./performance-audit \ --chrome-flags="--headless" \ --preset=perf # Mobile performance audit lighthouse http://localhost:3000 \ --output=json \ --output-path=./performance-audit-mobile \ --preset=perf \ --form-factor=mobile \ --throttling-method=devtools \ --chrome-flags="--headless" # Generate detailed report lighthouse http://localhost:3000 \ --output=html \ --output-path=./lighthouse-report.html \ --view
2. Bundle Analysis
// next.config.js - Enable bundle analysis
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// ... your config
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Bundle analysis optimizations
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
};
}
return config;
},
});3. Runtime Performance Analysis
# Build and analyze bundle ANALYZE=true npm run build # Check bundle sizes ls -lah .next/static/chunks/ | grep -E "\\.js$" | sort -k5 -hr | head -10 # Analyze dependencies npm ls --depth=0 --prod | grep -v "deduped" # Check for duplicate dependencies npm ls --depth=0 | grep -E "UNMET|invalid"
Performance Metrics Collection
1. Core Web Vitals Implementation
// lib/analytics.ts
export function reportWebVitals({ id, name, label, value }: any) {
// Send to analytics service
if (typeof window !== 'undefined') {
// Client-side reporting
fetch('/api/analytics/web-vitals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id,
name,
label,
value,
url: window.location.href,
timestamp: Date.now(),
}),
}).catch(console.error);
}
}
// Track specific metrics
export function trackMetric(name: string, value: number, labels?: Record<string, string>) {
reportWebVitals({
id: `${name}-${Date.now()}`,
name,
label: 'custom',
value,
...labels,
});
}
// Performance observer for custom metrics
export function initPerformanceObserver() {
if (typeof window === 'undefined') return;
// Largest Contentful Paint
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
trackMetric('LCP', entry.startTime);
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
// First Input Delay
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
trackMetric('FID', entry.processingStart - entry.startTime);
}
}).observe({ entryTypes: ['first-input'] });
// Cumulative Layout Shift
new PerformanceObserver((entryList) => {
let clsValue = 0;
for (const entry of entryList.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
trackMetric('CLS', clsValue);
}).observe({ entryTypes: ['layout-shift'] });
}2. Server-Side Performance Monitoring
// middleware.ts - Performance monitoring
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const start = Date.now();
const response = NextResponse.next();
// Add performance headers
response.headers.set('X-Response-Time', `${Date.now() - start}ms`);
response.headers.set('X-Timestamp', new Date().toISOString());
return response;
}Performance Analysis Areas
1. Loading Performance
// Analyze loading performance
const loadingPerformanceAudit = {
// First Contentful Paint (FCP)
fcp: {
target: '< 1.8s',
current: '?', // From Lighthouse
optimizations: [
'Optimize critical rendering path',
'Inline critical CSS',
'Preload key resources',
'Minimize render-blocking resources',
],
},
// Largest Contentful Paint (LCP)
lcp: {
target: '< 2.5s',
current: '?', // From Lighthouse
optimizations: [
'Optimize images (Next.js Image component)',
'Preload LCP element',
'Optimize server response time',
'Use CDN for static assets',
],
},
// Time to Interactive (TTI)
tti: {
target: '< 3.8s',
current: '?', // From Lighthouse
optimizations: [
'Reduce JavaScript bundle size',
'Code splitting',
'Remove unused code',
'Optimize third-party scripts',
],
},
// Speed Index
speedIndex: {
target: '< 3.4s',Ready-to-use configurations for Anthropic's Claude Code. A comprehensive collection of AI agents, custom commands, settings, hooks, external integrations (MCPs), and project templates to enhance your development workflow.
Repo: davila7/claude-code-templates
Other commands on claude-code-templates.
- /cleanup-cache
Clean system caches (npm, Homebrew, Yarn, browsers, Python/ML) to free disk space
Open command - /create-blog-article
Create an SEO-optimized blog article for a Claude Code component with AI-generated cover image
Open command - /lint
Run Python code linting and formatting tools.
Open command - /test
Run Python tests with pytest, unittest, or other testing frameworks.
Open command - /worktree-check
Check current worktree status, branch, and assigned task
Open command - /worktree-cleanup
Clean up merged worktrees and their branches
Open command

