Next.js Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
Next.js
- Add a Content Security Policy with nonces in Next.jsMitigate XSS by allowing only scripts that Next.js itself renders.
- Add dark mode to Next.js without a flashSupport system/light/dark themes in a server-rendered Next.js app without hydration warnings or flashes.
- Add SEO metadata, Open Graph and sitemapsGive every page correct titles, descriptions, social previews and a sitemap for search engines.
- Avoid data-fetching waterfalls in Server ComponentsA dashboard page is slow because it awaits user, stats and notifications one after another.
- Build a validated JSON API with Route HandlersExpose a REST endpoint from a Next.js app for a mobile client, with auth and input validation.
- Create encrypted session cookies in Next.jsImplement login sessions without a session store, using a signed/encrypted cookie readable only on the server.
- Handle errors and 404s in the App RouterShow friendly error pages per section, recover with a retry, and return real 404s for missing records.
- Handle forms with Server Actions and validationCreate a contact form that validates on the server, shows field errors, and works without client-side JavaScript.
- Keep secrets and server code out of the client bundleMake sure API keys and database code never ship to the browser in a Next.js app.
- Optimistic UI with Server ActionsMake liking a post or adding a comment feel instant while the Server Action runs.
- Optimize images with next/imageServe responsive, lazy-loaded images in modern formats without layout shift, including from a CMS.
- Paginate and filter with searchParams in Server ComponentsBuild a searchable, paginated product list rendered on the server and shareable via URL.
- Pre-render dynamic pages with generateStaticParams and ISRServe thousands of blog/product pages as static HTML that refreshes periodically.
- Protect routes in the Next.js App RouterRedirect signed-out users away from /dashboard and make sure server code never serves private data to them.
- Rate limit Route Handlers and Server ActionsProtect login, signup and AI endpoints from abuse in a serverless deployment.
- Receive Stripe webhooks in a Next.js Route HandlerProcess payment events securely in a Next.js app deployed to serverless.
- Revalidate cached data with tags after a mutationShow fresh product data right after an admin edits it, while keeping pages fast and cached.
- Stream slow sections with SuspenseRender the page shell instantly while slow data (recommendations, analytics) loads.
- Test a Next.js app with Vitest and PlaywrightSet up fast component tests and a few end-to-end tests for critical flows in a Next.js project.
- Upload files with a Server ActionLet users upload an avatar through a form that works even before JavaScript loads.