# Next.js Performance Optimization
Performance is crucial for modern web applications. Here are the techniques I use to optimize Next.js applications for production.
## Core Web Vitals
Focus on these key metrics:
- **LCP (Largest Contentful Paint)**: < 2.5s
- **FID (First Input Delay)**: < 100ms
- **CLS (Cumulative Layout Shift)**: < 0.1
## Image Optimization
Next.js Image component provides automatic optimization:
```jsx
import Image from 'next/image';
function OptimizedImage() {
return (
<Image
src="/hero-image.jpg"
alt="Hero"
width={800}
height={600}
priority // For above-the-fold images
placeholder="blur"
blurDataURL="data:image/jpeg;base64,..."
/>
);
}
```
## Code Splitting
Implement dynamic imports for better performance:
```jsx
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <div>Loading...</div>,
ssr: false // Disable SSR for client-only components
});
function MyPage() {
return (
<div>
<h1>My Page</h1>
<HeavyComponent />
</div>
);
}
```
## Bundle Analysis
Use webpack-bundle-analyzer to identify large dependencies:
```javascript
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// Your Next.js config
});
```
## Caching Strategies
### Static Generation
Use getStaticProps for static content:
```jsx
export async function getStaticProps() {
const data = await fetchData();
return {
props: { data },
revalidate: 3600 // Revalidate every hour
};
}
```
### API Route Caching
Implement caching in API routes:
```javascript
export default async function handler(req, res) {
// Set cache headers
res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate');
const data = await fetchExpensiveData();
res.json(data);
}
```
## Font Optimization
Use next/font for optimized font loading:
```jsx
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
});
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
);
}
```
## Real-World Results
At **Okhati Health Solutions**, these optimizations resulted in:
- **50% faster** initial page load
- **30% improvement** in Core Web Vitals
- **25% increase** in user engagement
- **15% boost** in conversion rates
## Monitoring
Use these tools to track performance:
1. **Lighthouse**: Built-in Chrome DevTools
2. **Web Vitals**: Real user monitoring
3. **Vercel Analytics**: Deployment-specific insights
4. **GTmetrix**: Comprehensive performance analysis
## Best Practices
### 1. Minimize JavaScript
Remove unused dependencies and code:
```bash
# Analyze bundle size
npm run build && npm run analyze
# Remove unused packages
npm uninstall unused-package
```
### 2. Optimize Third-Party Scripts
Load third-party scripts efficiently:
```jsx
import Script from 'next/script';
function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<Script
src="https://analytics.example.com/script.js"
strategy="afterInteractive"
/>
</>
);
}
```
### 3. Database Optimization
Optimize database queries:
- Use connection pooling
- Implement query caching
- Add proper indexes
- Use read replicas for heavy reads
## Conclusion
Performance optimization is an ongoing process. Focus on:
- Measuring before optimizing
- Prioritizing user-facing improvements
- Monitoring real-world performance
- Iterating based on data
Remember: premature optimization is the root of all evil, but ignoring performance is worse.