nextjs-middleware
Complete Next.js Middleware system (Next.js 15.5/16). PROACTIVELY activate for: (1) Creating middleware.ts (Edge) or proxy.ts (Node.js), (2) Matcher configuration, (3) Authentication protection, (4) Role-based access control, (5) Redirects and rewrites, (6) Internationalization (i18n), (7) Security headers (CSP, CORS), (8) Geolocation routing, (9) Bot detection, (10) Rate limiting patterns, (11) Node.js Middleware with proxy.ts (Next.js 16). Provides: Edge middleware patterns, Node.js proxy patterns, matcher syntax, auth guards, header manipulation, cookie handling, database access in proxy.ts. Ensures optimized request handling with proper security.
What this skill does
## Quick Reference
| Response Type | Code | Purpose |
|---------------|------|---------|
| Continue | `NextResponse.next()` | Pass through |
| Redirect | `NextResponse.redirect(url)` | 307/308 redirect |
| Rewrite | `NextResponse.rewrite(url)` | URL rewrite (no redirect) |
| JSON | `NextResponse.json(data)` | Return JSON response |
| Matcher Pattern | Matches |
|-----------------|---------|
| `'/about'` | Exact path |
| `'/dashboard/:path*'` | Dashboard and all sub-paths |
| `'/((?!api\|_next).*)` | All except api and _next |
| Request Data | Access |
|--------------|--------|
| Path | `request.nextUrl.pathname` |
| Search params | `request.nextUrl.searchParams` |
| Cookies | `request.cookies.get('name')` |
| Headers | `request.headers.get('name')` |
| Geo | `request.geo?.country` |
| IP | `request.ip` |
## When to Use This Skill
Use for **Edge request handling**:
- Protecting routes with authentication
- Implementing role-based access control
- Setting security headers (CSP, CORS)
- Internationalization and locale detection
- A/B testing with rewrites
- Geolocation-based routing
**Related skills:**
- For authentication: see `nextjs-authentication`
- For routing: see `nextjs-routing-advanced`
- For deployment: see `nextjs-deployment`
---
# Next.js Middleware
## Basic Middleware
### Creating Middleware
```tsx
// middleware.ts (in project root)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Add custom header
const response = NextResponse.next();
response.headers.set('x-custom-header', 'my-value');
return response;
}
// Configure which paths middleware runs on
export const config = {
matcher: '/api/:path*',
};
```
### Matcher Configuration
```tsx
// Single path
export const config = {
matcher: '/about',
};
// Multiple paths
export const config = {
matcher: ['/about', '/dashboard/:path*'],
};
// Regex pattern
export const config = {
matcher: [
// Match all paths except static files and images
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};
// All paths except API and static
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
```
## Authentication
### Protecting Routes
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
const isAuthPage =
request.nextUrl.pathname.startsWith('/login') ||
request.nextUrl.pathname.startsWith('/register');
if (isAuthPage) {
if (token) {
// Redirect to dashboard if already logged in
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
if (!token) {
// Redirect to login if not authenticated
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('callbackUrl', request.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*', '/login', '/register'],
};
```
### Role-Based Access
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
const roleBasedRoutes: Record<string, string[]> = {
'/admin': ['admin'],
'/dashboard': ['admin', 'user'],
'/settings': ['admin', 'user'],
};
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
const { pathname } = request.nextUrl;
// Check role-based access
for (const [route, allowedRoles] of Object.entries(roleBasedRoutes)) {
if (pathname.startsWith(route)) {
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
const userRole = token.role as string;
if (!allowedRoles.includes(userRole)) {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
}
}
return NextResponse.next();
}
```
## Redirects
### Simple Redirects
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const redirects: Record<string, string> = {
'/old-page': '/new-page',
'/blog/old-post': '/articles/new-post',
'/legacy': 'https://legacy.example.com',
};
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (redirects[pathname]) {
const destination = redirects[pathname];
// External redirect
if (destination.startsWith('http')) {
return NextResponse.redirect(destination);
}
// Internal redirect
return NextResponse.redirect(new URL(destination, request.url));
}
return NextResponse.next();
}
```
### Conditional Redirects
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname, searchParams } = request.nextUrl;
// Redirect old search format
if (pathname === '/search' && searchParams.has('query')) {
const query = searchParams.get('query');
return NextResponse.redirect(new URL(`/search/${query}`, request.url));
}
// Redirect trailing slashes
if (pathname !== '/' && pathname.endsWith('/')) {
return NextResponse.redirect(
new URL(pathname.slice(0, -1), request.url)
);
}
return NextResponse.next();
}
```
## Rewrites
### URL Rewrites
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Rewrite /api to external API
if (pathname.startsWith('/api/external')) {
return NextResponse.rewrite(
new URL(pathname.replace('/api/external', ''), 'https://api.example.com')
);
}
// A/B testing rewrite
const bucket = request.cookies.get('bucket')?.value || 'a';
if (pathname === '/landing') {
return NextResponse.rewrite(
new URL(`/landing-${bucket}`, request.url)
);
}
return NextResponse.next();
}
```
### Internationalization
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const locales = ['en', 'es', 'fr', 'de'];
const defaultLocale = 'en';
function getLocale(request: NextRequest): string {
// Check cookie
const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
if (cookieLocale && locales.includes(cookieLocale)) {
return cookieLocale;
}
// Check Accept-Language header
const acceptLanguage = request.headers.get('accept-language');
if (acceptLanguage) {
const preferredLocale = acceptLanguage
.split(',')
.map((lang) => lang.split(';')[0].trim().split('-')[0])
.find((lang) => locales.includes(lang));
if (preferredLocale) {
return preferredLocale;
}
}
return defaultLocale;
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if pathname has a locale
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) return NextResponse.next();
// Redirect to localized path
const locale = getLocale(request);
return NextResponse.redirect(
new URL(`/${locale}${pathname}`, request.url)
);
}
export const config = {
matcher: ['/((?!_next|api|favicon.ico).*)'],
};
```
## Headers
### Adding Headers
```tsx
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
/Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.