Snippets
Next.js logo

Next.js

Next.js App Router patterns I ship to production. Server Actions, proxy.ts, caching, metadata, and middleware-style request handling.

1

About these Next.js snippets

These are the App Router patterns I use across production Next.js apps, including this portfolio site. Every snippet targets Next.js 16+ with the App Router, TypeScript, and Server Components as the default. No Pages Router, no getServerSideProps, no legacy patterns.

The snippets focus on the parts of Next.js that are hardest to get right from the docs alone: caching strategies that actually invalidate when you need them to, metadata generation that produces valid OG tags across every page, and the new proxy.ts API for request-level logic that used to live in middleware.

What's inside

  • Metadata and SEO: a generateMetadata pattern that handles canonical URLs, OpenGraph tags, and Twitter cards dynamically from your data layer, plus a route handler that generates OG images on the fly using ImageResponse.
  • Caching: use cache with revalidateTag for on-demand cache invalidation, the pattern that replaced unstable_cache in Next.js 16.
  • Request handling with proxy.ts: auth-gated proxying that blocks unauthenticated requests before they reach your app, and geo-based redirects that route users by country at the edge.
  • Rate limiting: protect Route Handlers with Upstash Redis-backed sliding window rate limits, with proper 429 responses and Retry-After headers.
  • Streaming: Server Components with Suspense boundaries and skeleton loading states, so your pages feel instant even when the data is slow.

More patterns land here as Next.js evolves and I battle-test new APIs in production. The blog usually covers the deeper reasoning behind a pattern before the snippet version shows up here.

How to use them

Every snippet page shows the full source, the file path where it belongs in the App Router directory structure, and a working usage example. Copy the file into the right location and adapt the imports to your project. The code is TypeScript throughout and assumes you are using the src/app/ directory convention.

A few things I try to get right on every snippet:

  • Edge-safe by default: patterns that run at the edge (proxy.ts, middleware) never import Node.js-only modules.
  • Type safety: all route params, search params, and API responses are typed end to end with TypeScript generics.
  • Production headers: rate-limit responses include proper Retry-After, caching includes stale-while-revalidate, and metadata includes all the tags Google and social platforms actually read.

If you find a cleaner pattern or something that broke in a newer Next.js version, the code is open on GitHub. PRs and issues are welcome.