Next.js

Next.js App Router patterns including server actions, middleware, and API route handlers.

100 snippets

Showing 100 of 100 snippets

typescriptintermediate

Type-Safe API Route Handler

Next.js App Router route handler with input validation, typed responses, and proper error handling.

Best for: CRUD API endpoints

#api#route-handler
typescriptintermediate

Authentication Middleware Guard

Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.

Best for: Dashboard access control

#middleware#authentication
typescriptintermediate

Server Action with Form Validation

Next.js Server Action handling form submissions with validation, error messages, and redirect on success.

Best for: Blog post creation

#server-actions#forms
typescriptadvanced

Dynamic OG Image Generation

Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.

Best for: Social media sharing

#og-image#seo
typescriptintermediate

Edge Middleware Geolocation

Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.

Best for: GDPR consent flows

#edge#geolocation
typescriptadvanced

On-Demand ISR Revalidation

Trigger incremental static regeneration via API route with secret token validation for instant cache purge.

Best for: CMS content updates

#isr#revalidation
typescriptbeginner

Protected Page with Server Redirect

Server Component that checks auth status and redirects unauthenticated users before rendering any content.

Best for: Dashboard pages

#auth#redirect
typescriptbeginner

Reusable Metadata Factory

Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.

Best for: Consistent page SEO

#seo#metadata
typescriptadvanced

Streaming API Response

Stream long-running API responses using ReadableStream and TransformStream for real-time data delivery.

Best for: AI response streaming

#streaming#api
typescriptadvanced

Parallel Routes Layout

Next.js parallel routes pattern to render multiple page slots simultaneously in a shared layout.

Best for: Dashboard multi-panel layouts

#parallel-routes#layout
typescriptadvanced

Edge Middleware Rate Limiter

Rate limit API requests at the edge using a sliding window counter with configurable thresholds.

Best for: API abuse prevention

#middleware#rate-limiting
typescriptbeginner

Cached Fetch with Revalidation

Fetch external data in Server Components with time-based revalidation and error boundaries.

Best for: CMS content fetching

#fetch#caching
typescriptintermediate

NextAuth Session Check Pattern

Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.

Best for: Protected pages

#authentication#nextauth
typescriptbeginner

Next.js Image Optimization Patterns

Use next/image with responsive sizes, blur placeholders, and priority loading for optimal Core Web Vitals.

Best for: Hero images

#images#optimization
typescriptbeginner

Environment Variable Validation

Validate required environment variables at build time with type-safe access and descriptive errors.

Best for: App startup checks

#environment#validation
typescriptbeginner

Redirect Matrix in next.config

Define URL redirect rules in next.config.ts for SEO migration, vanity URLs, and path normalization.

Best for: URL migration after redesign

#redirects#seo
typescriptadvanced

Partial Prerendering with Suspense

Combine static shells with streamed dynamic content using React Suspense for instant page loads.

Best for: E-commerce product pages

#ppr#suspense
typescriptintermediate

Server Action with Revalidation

Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.

Best for: Form submissions

#server-actions#revalidation
typescriptadvanced

Intercepting Routes Modal

Show content in a modal on soft navigation while preserving the full page on hard navigation.

Best for: Photo gallery modals

#routing#modals
typescriptadvanced

Multi-Zone Application Setup

Compose multiple Next.js apps under one domain using rewrites for micro-frontend architecture.

Best for: Team-owned sub-apps

#multi-zone#micro-frontends
typescriptadvanced

Next.js Parallel Routes Layout

Use parallel routes with named slots to render multiple pages simultaneously in a layout.

Best for: Dashboard layouts with independent loading states

#nextjs#routing
typescriptadvanced

Next.js Intercepting Routes for Modals

Implement modal patterns with intercepting routes that work with both soft and hard navigation.

Best for: Image gallery modals with shareable URLs

#nextjs#routing
typescriptintermediate

Next.js Server Actions with Forms

Use Server Actions for form handling with validation, optimistic updates, and error handling.

Best for: Form submissions without API routes

#nextjs#server-actions
typescriptintermediate

Next.js Streaming with Suspense

Stream server components with Suspense boundaries for progressive page loading and better TTFB.

Best for: Progressive loading for data-heavy dashboards

#nextjs#streaming
typescriptbeginner

Next.js Image Optimization Patterns

Advanced next/image usage with responsive sizes, blur placeholders, and custom loaders.

Best for: Optimizing Core Web Vitals with proper image loading

#nextjs#image
typescriptintermediate

Next.js Error Handling Patterns

Implement error.tsx, not-found.tsx, and global-error.tsx for comprehensive error handling.

Best for: Graceful error recovery in nested layouts

#nextjs#error-handling
typescriptintermediate

Next.js Route Handlers (API Routes)

Build RESTful API endpoints using Next.js App Router route handlers with typed responses.

Best for: Building REST APIs within a Next.js application

#nextjs#api
typescriptadvanced

Next.js Dynamic OG Image Generation

Generate dynamic Open Graph images at build time using next/og for social media sharing.

Best for: Dynamic social media preview images

#nextjs#og-image
typescriptadvanced

Next.js Middleware for Authentication

Protect routes with Next.js middleware using token verification and role-based redirects.

Best for: Protecting authenticated routes at the edge

#nextjs#middleware
typescriptintermediate

Next.js ISR & On-Demand Revalidation

Configure Incremental Static Regeneration with time-based and on-demand revalidation strategies.

Best for: Caching CMS content with periodic refresh

#nextjs#isr
typescriptbeginner

Loading UI with Skeleton Screens

Create loading.tsx skeleton screens for instant navigation feedback with Next.js App Router.

Best for: Route transition loading states

#nextjs#loading
typescriptbeginner

Custom Not Found Page

Create a custom not-found.tsx with search suggestions, popular links, and a return home button.

Best for: Custom 404 error pages

#nextjs#error
typescriptintermediate

Global Error Boundary Page

Handle uncaught errors gracefully with global-error.tsx including error logging and recovery.

Best for: Production error recovery

#nextjs#error
typescriptintermediate

Route Groups for Layout Organization

Use route groups to share layouts across routes without affecting URL structure.

Best for: Marketing vs. dashboard layouts

#nextjs#routing
typescriptadvanced

Caching Strategies in Next.js

Master Next.js caching with fetch cache, unstable_cache, revalidatePath, and revalidateTag patterns.

Best for: ISR page caching

#nextjs#caching
typescriptadvanced

Middleware Chain Pattern

Compose multiple middleware functions for auth, rate limiting, and geolocation in Next.js middleware.

Best for: Auth guard middleware

#nextjs#middleware
typescriptintermediate

SEO Metadata Patterns

Generate dynamic SEO metadata with Open Graph, Twitter cards, JSON-LD, and canonical URLs.

Best for: Dynamic page SEO

#nextjs#seo
typescriptintermediate

API Route Rate Limiting

Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.

Best for: API abuse prevention

#nextjs#api
typescriptintermediate

Dynamic Sitemap Generation

Generate dynamic XML sitemaps from data sources with priority, changefreq, and sitemap index support.

Best for: Automated sitemap generation

#nextjs#sitemap
typescriptadvanced

Server/Client Component Patterns

Correctly compose server and client components with data fetching, interactivity, and composition patterns.

Best for: RSC architecture planning

#nextjs#rsc
typescriptintermediate

Dynamic Import and Code Splitting

Use next/dynamic for lazy loading components with custom loading states, SSR control, and named exports.

Best for: Reducing initial bundle size

#nextjs#dynamic-import
typescriptadvanced

Form with Server Action Validation

Build forms using Next.js server actions with server-side validation, error handling, and useActionState.

Best for: Contact form submissions

#nextjs#forms
typescriptintermediate

Parallel Data Fetching in Server Components

Fetch multiple data sources in parallel using Promise.all in Next.js server components for faster page loads.

Best for: dashboard pages

#nextjs#data-fetching
typescriptbeginner

Redirect After Server Action

Use redirect() inside a server action to navigate after form submission in Next.js App Router.

Best for: form submissions

#nextjs#server-actions
typescriptintermediate

generateStaticParams for Dynamic Routes

Pre-render dynamic routes at build time using generateStaticParams with fallback handling.

Best for: blog pages

#nextjs#static-generation
typescriptadvanced

Middleware Geo-based Redirect

Redirect users based on their geographic location using Next.js edge middleware.

Best for: internationalization

#nextjs#middleware
typescriptintermediate

Streaming with Loading UI and Suspense

Use loading.tsx and React Suspense to stream UI progressively in Next.js App Router.

Best for: dashboards

#nextjs#streaming
typescriptintermediate

Catch-All and Optional Catch-All Routes

Handle dynamic nested routes with catch-all [...slug] and optional [[...slug]] segments.

Best for: documentation sites

#nextjs#routing
typescriptbeginner

Font Optimization with next/font

Use next/font for automatic self-hosted font optimization with zero layout shift.

Best for: custom typography

#nextjs#fonts
typescriptbeginner

Route Handler Response Helpers

Common response patterns for Next.js route handlers with proper status codes and headers.

Best for: API route handlers

#nextjs#api
typescriptintermediate

URL Rewrite Proxy Pattern

Use next.config.js rewrites to proxy API calls and avoid CORS issues in development and production.

Best for: API proxying

#nextjs#rewrite
typescriptbeginner

Server-Only Utility Functions

Ensure utility functions only run on the server using the server-only package to prevent client leakage.

Best for: protecting secrets

#nextjs#server-only
typescriptbeginner

useFormStatus for Pending UI States

Use useFormStatus hook to show loading states during server action form submissions.

Best for: form submission UX

#nextjs#forms
typescriptintermediate

useOptimistic for Instant UI Updates

Use useOptimistic hook for instant UI feedback while server actions process in the background.

Best for: todo lists

#nextjs#useOptimistic
typescriptintermediate

Dynamic Metadata with generateMetadata

Generate dynamic SEO metadata based on page params using generateMetadata in Next.js App Router.

Best for: blog SEO

#nextjs#metadata
typescriptintermediate

Next Image Responsive Patterns

Use next/image with responsive sizes, blur placeholders, and priority loading for optimal image delivery.

Best for: responsive images

#nextjs#image
typescriptintermediate

Error Handling with error.tsx and not-found.tsx

Handle errors gracefully with error.tsx boundaries and not-found.tsx pages in App Router.

Best for: error boundaries

#nextjs#error-handling
typescriptintermediate

Template vs Layout for Re-rendering

Use template.tsx instead of layout.tsx when you need fresh state on every navigation.

Best for: page transitions

#nextjs#template
typescriptintermediate

Search Params in Server and Client Components

Handle URL search params in both server and client components with type-safe parsing.

Best for: product filters

#nextjs#search-params
typescriptintermediate

Cookies and Headers in Server Components

Read and set cookies and headers in Next.js server components and route handlers.

Best for: theme preferences

#nextjs#cookies
typescriptadvanced

Cache Tags and On-Demand Revalidation

Tag cached data with identifiers and revalidate specific cache entries on demand.

Best for: CMS webhooks

#nextjs#caching
typescriptadvanced

Data Caching with unstable_cache

Cache database queries and expensive computations with unstable_cache for server-side memoization.

Best for: database query caching

#nextjs#cache
typescriptadvanced

Authentication Middleware with Session Check

Protect routes with middleware that validates session tokens and redirects unauthenticated users.

Best for: route protection

#nextjs#auth
typescriptadvanced

Streaming Response from Route Handler

Stream large responses from Next.js route handlers using ReadableStream for real-time data.

Best for: real-time updates

#nextjs#streaming
typescriptintermediate

Server Action Validation with Zod

Validate form data in server actions using Zod schemas with type-safe error handling.

Best for: contact forms

#nextjs#zod
typescriptadvanced

Parallel Routes for Modal Pattern

Implement modal dialogs using parallel routes and route interception for shareable modal URLs.

Best for: photo galleries

#nextjs#parallel-routes
typescriptintermediate

File Upload with Server Action

Handle file uploads using server actions with validation, size limits, and storage.

Best for: image uploads

#nextjs#file-upload
typescriptadvanced

Internationalization (i18n) Routing

Implement locale-based routing with middleware detection and dictionary loading.

Best for: multi-language websites

#nextjs#i18n
typescriptadvanced

Rate Limiter for Edge Functions

Implement sliding window rate limiting in Next.js middleware using in-memory or KV store.

Best for: API protection

#nextjs#rate-limiting
typescriptintermediate

Infinite Scroll with Server Actions

Implement infinite scroll using server actions with cursor-based pagination.

Best for: social feeds

#nextjs#infinite-scroll
typescriptbeginner

Active Navigation Link Component

Build a navigation component that highlights the active route using usePathname.

Best for: navigation menus

#nextjs#navigation
typescriptadvanced

Draft Mode for CMS Preview

Enable draft mode to preview unpublished CMS content in production with cookie-based toggling.

Best for: CMS preview

#nextjs#draft-mode
typescriptadvanced

Multi-Tenant App with Subdomains

Build a multi-tenant application using middleware to resolve tenant from subdomain.

Best for: SaaS platforms

#nextjs#multi-tenant
typescriptbeginner

Script Component Loading Strategies

Load third-party scripts efficiently with next/script using different loading strategies.

Best for: analytics

#nextjs#script
typescriptintermediate

Environment Variable Validation with Zod

Validate environment variables at build time using Zod to catch misconfigurations early.

Best for: build-time validation

#nextjs#env
typescriptbeginner

Link Prefetching Strategies

Control route prefetching behavior with next/link for optimal navigation performance.

Best for: navigation optimization

#nextjs#link
typescriptadvanced

Content Security Policy Headers

Configure strict CSP and security headers in Next.js for production-grade security.

Best for: production security

#nextjs#csp
typescriptadvanced

OG Image Generation at the Edge

Generate dynamic Open Graph images using @vercel/og with custom layouts and fonts.

Best for: social media cards

#nextjs#og-image
typescriptbeginner

Server to Client Component Data Passing

Pass data from server components to client components using props and serialization patterns.

Best for: data hydration

#nextjs#server-components
typescriptintermediate

Route Handler with CORS Support

Add CORS headers to Next.js route handlers for cross-origin API access.

Best for: external API consumers

#nextjs#cors
typescriptadvanced

Testing Server Components

Test Next.js server components and server actions using testing-library and mocks.

Best for: unit testing

#nextjs#testing
typescriptintermediate

Server Component Composition Patterns

Compose server and client components effectively with the donut pattern and children pass-through.

Best for: interactive layouts

#nextjs#rsc
typescriptintermediate

MDX Blog with Next.js

Set up MDX support for a blog with custom components, frontmatter, and syntax highlighting.

Best for: technical blogs

#nextjs#mdx
typescriptintermediate

Dynamic Sitemap Generation

Generate a comprehensive sitemap.xml from dynamic routes and database content.

Best for: SEO optimization

#nextjs#sitemap
typescriptadvanced

Webhook Handler with Signature Verification

Handle incoming webhooks with signature verification and idempotent processing.

Best for: payment webhooks

#nextjs#webhooks
typescriptintermediate

Static Export Configuration

Configure Next.js for static export with output: 'export' for deployment to static hosts.

Best for: Cloudflare Pages

#nextjs#static-export
typescriptbeginner

NextJS Technique 37

Advanced NextJS pattern 37

Best for: performance

#nextjs#advanced
typescriptintermediate

NextJS Technique 38

Advanced NextJS pattern 38

Best for: performance

#nextjs#advanced
typescriptadvanced

NextJS Technique 39

Advanced NextJS pattern 39

Best for: performance

#nextjs#advanced
typescriptbeginner

NextJS Technique 40

Advanced NextJS pattern 40

Best for: performance

#nextjs#advanced
typescriptintermediate

NextJS Technique 41

Advanced NextJS pattern 41

Best for: performance

#nextjs#advanced
typescriptadvanced

NextJS Technique 42

Advanced NextJS pattern 42

Best for: performance

#nextjs#advanced
typescriptbeginner

NextJS Technique 43

Advanced NextJS pattern 43

Best for: performance

#nextjs#advanced
typescriptintermediate

NextJS Technique 44

Advanced NextJS pattern 44

Best for: performance

#nextjs#advanced
typescriptadvanced

NextJS Technique 45

Advanced NextJS pattern 45

Best for: performance

#nextjs#advanced
typescriptbeginner

NextJS Technique 46

Advanced NextJS pattern 46

Best for: performance

#nextjs#advanced
typescriptintermediate

NextJS Technique 47

Advanced NextJS pattern 47

Best for: performance

#nextjs#advanced
typescriptadvanced

NextJS Technique 48

Advanced NextJS pattern 48

Best for: performance

#nextjs#advanced
typescriptbeginner

NextJS Technique 49

Advanced NextJS pattern 49

Best for: performance

#nextjs#advanced
typescriptintermediate

NextJS Technique 50

Advanced NextJS pattern 50

Best for: performance

#nextjs#advanced