Next.js middleware patterns for request processing
View on GitHubplugins/aai-stack-nextjs/skills/nextjs-middleware/SKILL.md
February 1, 2026
Select agents to install to:
npx add-skill https://github.com/the-answerai/alphaagent-team/blob/main/plugins/aai-stack-nextjs/skills/nextjs-middleware/SKILL.md -a claude-code --skill nextjs-middlewareInstallation paths:
.claude/skills/nextjs-middleware/# Next.js Middleware Skill
Patterns for using Next.js middleware for request interception.
## Basic Middleware
### Simple Middleware
```typescript
// middleware.ts (in project root)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Clone the request headers
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-custom-header', 'custom-value')
// Return response with modified headers
return NextResponse.next({
request: {
headers: requestHeaders,
},
})
}
// Configure which paths middleware runs on
export const config = {
matcher: '/api/:path*',
}
```
### Route Matching
```typescript
export const config = {
matcher: [
// Match all paths except static files and images
'/((?!_next/static|_next/image|favicon.ico).*)',
// Match specific paths
'/api/:path*',
'/dashboard/:path*',
// Match with regex
'/blog/:slug*',
],
}
```
## Authentication
### Session Check
```typescript
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 })
if (!token) {
const signInUrl = new URL('/auth/signin', request.url)
signInUrl.searchParams.set('callbackUrl', request.url)
return NextResponse.redirect(signInUrl)
}
return NextResponse.next()
}
export const config = {
matcher: ['/dashboard/:path*', '/account/:path*'],
}
```
### JWT Verification
```typescript
import { jwtVerify } from 'jose'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
const SECRET = new TextEncoder().encode(process.env.JWT_SECRET)
export async function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value
if (!token) {
return NextResponse.redirect(new URL('/logi