Next.js Hot Tips Cheatsheet
By Ankita Kulkarni
Routing
Use [slug] for single, predictable URL segments and Use [...slug] for multiple/nested segments
// Dynamic Routes:
// matches: /blog/my-post
`app/blog/[slug]/page.tsx`
// Catch-all Routes:
// matches: /blog/tech/nextjs/routing
`app/blog/[...slug]/page.tsx`
Server Components vs Actions
Server Components never re-render on client and Server Actions get exposed as API endpoints
Server Components:
Useful for GET requests
Server Actions:
Useful for POST/PUT/DELETE requests
Image Optimization
Always use next/image instead of img, Provide width and height to prevent layout shift and Use priority for above-the-fold images
<Image
width={500}
height={300}
sizes="(max-width: 768px) 100vw, (max-width: 900px) 50vw, 33vw"
priority={true}
/>
Security Best Practices
Avoid NEXT_PUBLIC_ for sensitive vars, use "server-only" to prevent server code exposure, and add authentication to exposed Server Action endpoints
import "server-only"; // Prevent server code exposure
Data Sanitization
Use Zod for form validation and sanitization, define strict schemas for your data, and validate both client and server side
const schema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().min(18)
});
Server-side Redirects
Use redirect to navigate to a new path and place outside try-catch blocks for better performance
import { redirect } from "next/navigation";
try {
redirect('/new-path');
} catch (error) {
console.error('Error redirecting:', error);
}
Production Console Logs
Use "removeConsole" to exclude console logs in production while keeping specific console methods like errors
compiler: {
removeConsole: {
exclude: ["error"]
}
}
Caching
Check x-vercel-cache header to determine cache status: HIT (from cache), MISS (fresh request), or STALE (outdated). Next.js 14 caches by default
// Check x-vercel-cache header:
HIT: From cache
MISS: Fresh request
STALE: Outdated cache
// Next.js 14 caches by default
Server Actions Usage
Use form action for traditional form submissions or await serverAction() for programmatic calls with additional logic
<form action={serverAction}>
<button type="submit">Submit</button>
</form>
// Function call method:
await serverAction();
Instant Updates
Use 'use server' directive to mark server-only functions, implement update logic, and call revalidatePath to ensure consistent data
'use server';
async function updateCart() {
// Update cart logic
revalidatePath('/');
}
// Ensures consistent data