Back to homepage
Developer Boilerplate Tool

Interactive SaaS Boilerplate Customizer

Construct and customize your Next.js application core layer. Toggle Redis rate limiting, database adapters, cookie authentication guards, and streaming LLM chat endpoints in one place.

Interactive Developer Helper

Boilerplate Customizer & Code Generator

Select backend adapters, security layers, or API streaming, then grab the production-ready code.

Base Setup

Database Clients

Middleware & Security

AI & LLM Orchestrators

middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { NextResponse } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});

const ratelimit = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
});

export async function middleware(request) {
  // 1. Rate Limiting Check
  const ip = request.ip ?? '127.0.0.1';
  const { success } = await ratelimit.limit(ip);
  if (!success) {
    return new NextResponse('Too Many Requests', { status: 429 });
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

Deep-Dive Guides & Setup Documentation

Engineering Blueprint

Next.js App Router Architecture: Building a High-Concurrence Micro-SaaS

When bootstrapping an AI-powered SaaS application in 2026, architectural missteps in early boilerplate setup can lead to severe security vulnerabilities, cold-start latency spikes, and runaway database connection pooling bills. Below is an engineering breakdown of how each generated layer functions in production.

1. Edge Middleware & Distributed Rate Limiting

In the Next.js App Router, middleware.ts executes on the edge before any route handler, layout, or page rendering takes place. This makes it the first line of defense against scraping bots, DDoS attacks, and API key credential stuffing.

The Stateless Concurrency Problem: Traditional Node.js in-memory counters (express-rate-limit) fail completely in serverless deployments because Vercel and AWS Lambda spin up hundreds of isolated micro-containers. Without a centralized datastore, an attacker can distribute requests across distinct instances and bypass limits entirely.

The Upstash Redis Solution: By combining @upstash/ratelimit with Upstash Serverless Redis, the edge middleware executes sliding-window rate limit checks over lightweight HTTP/REST. Because Upstash communicates over HTTPS rather than persistent TCP sockets, it introduces zero connection overhead, adds less than 15ms of latency to edge execution, and safely drops throttled traffic with an HTTP 429 status code before reaching expensive downstream database compute.

2. Stateless Cookie Authentication via @supabase/ssr

Next.js 14 and 15 enforce strict separation between Server Components (read-only cookie access) and Server Actions / Route Handlers (mutable cookie access). The generated boilerplate uses the official @supabase/ssr package to guarantee seamless session hydration across all component tiers.

  • Middleware Token Refresh: The middleware inspects the JWT session cookie on every incoming request. If the access token has expired but the refresh token remains valid, Supabase refreshes the credentials and injects updated cookies into both the outgoing response and the forwarded request headers.
  • Avoiding the Waterfall Antipattern: Rather than calling supabase.auth.getUser() inside every nested server component, verify the user session once at the layout boundary and pass user metadata downstream, eliminating redundant network round-trips to the Supabase auth server.
  • Security Attributes: Cookies are automatically configured with HttpOnly, Secure, and SameSite=Lax to prevent cross-site scripting (XSS) extraction and mitigate cross-site request forgery (CSRF).

3. Database Connection Pooling with Prisma & Supavisor

PostgreSQL allocates a dedicated operating system process (consuming approximately 2MB to 10MB of RAM) for every active connection. When serverless functions scale rapidly under traffic surges, direct connections will immediately trigger FATAL: remaining connection slots are reserved for non-replication superuser connections.

Production Port Configuration:

  • Port 6543 (Pooled Transaction Mode): Use for all runtime serverless queries in production via Supavisor / PgBouncer. Append ?pgbouncer=true&connection_limit=1 to your DATABASE_URL.
  • Port 5432 (Direct Session Mode): Use solely for DIRECT_URL when running Prisma schema migrations (npx prisma migrate deploy), because prepared statements and DDL transactions require persistent session connections.

In development environments, Next.js Fast Refresh recompiles modules on every file save. The generated boilerplate caches the PrismaClient instance on globalThis.prisma to prevent exhausting your local PostgreSQL connection pool during local development.

4. LLM API Streaming & Token Optimization

Waiting 10 to 30 seconds for an LLM (like GPT-6 Sol or DeepSeek-V3) to produce a full multi-paragraph completion before sending an HTTP response ruins user experience and frequently triggers gateway timeouts on reverse proxies. The boilerplate generates a Web Streams API route handler that streams tokens chunk-by-chunk.

Handling Client Disconnections: If a user navigates away or closes their laptop mid-generation, standard fetch implementations continue pulling tokens from OpenAI or DeepSeek in the background, consuming billable API tokens for text no user will ever read. The generated handler wires req.signal directly to the model client, triggering an immediate abort signal to terminate generation at the exact moment the client disconnects.

Timeout Governance: On Vercel, the default Hobby tier execution timeout is 10 seconds, while Pro allows up to 300 seconds. Add export const maxDuration = 60; to your streaming route handler to prevent premature termination during complex chain-of-thought reasoning tasks.

Frequently Asked Architectural Questions

Is this boilerplate structure compatible with Next.js 15 and React 19?

Yes. The generated code uses standard Web APIs (Request, Response, ReadableStream, Headers) and modern async Request cookie handling compatible with Next.js 14, Next.js 15, and React 19 Server Components.

Why is distributed Redis rate limiting essential on Vercel Edge Runtime?

Serverless and edge runtimes are stateless; each incoming HTTP request may spin up a new container instance. In-memory maps (like new Map()) do not share state across lambdas, making in-memory rate limiting ineffective against distributed attacks. Upstash Redis provides HTTP-based REST calls that persist global request counts across all edge locations with sub-15ms round-trip latency.

How does @supabase/ssr differ from legacy @supabase/auth-helpers-nextjs?

@supabase/ssr is the official package designed specifically for the Next.js App Router. It completely replaces the deprecated auth-helpers library, offering unified cookie read/write adapter patterns across middleware.ts, Server Components, Route Handlers, and Client Components without desynchronized auth states.

How do I prevent Prisma connection exhaustion on serverless platforms?

Instantiate PrismaClient as a global singleton cached on globalThis in development. In production on serverless providers like Vercel or AWS Lambda, connect through a connection pooler such as Supabase Supavisor / PgBouncer using transaction mode on port 6543 with ?pgbouncer=true appended to your DATABASE_URL.

Does the AI streaming route support backpressure and client cancellation?

Yes. By leveraging standard Web Streams API and piping OpenAI or DeepSeek responses through a TransformStream, the server respects TCP backpressure. Attaching req.signal to the upstream fetch call immediately aborts the LLM token generation when the user closes their browser tab, preventing wasted API token charges.

Need to estimate your monthly infrastructure burn rate?

Compare compute, database, auth MAU scaling, and LLM API costs side-by-side.