What is Middleware?
TL;DR
Edge functions that run before requests are processed, enabling authentication checks, redirects, and request modifications.
Middleware in Frontend Accelerator runs at the edge (on CDN nodes worldwide) before requests reach your application, providing ultra-fast authentication checks and request preprocessing.
Location:
// middleware.ts (root of project)
export { default } from 'next-auth/middleware';
export const config = {
matcher: ['/dashboard/:path*', '/api/protected/:path*']
};
Common Use Cases:
1. Authentication Protection:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('next-auth.session-token');
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
2. Role-Based Access:
- Check user roles before page access
- Redirect unauthorized users
- Add custom headers based on user permissions
3. Request Modifications:
- Rewrite URLs for A/B testing
- Add tracking headers
- Set custom cookies
Performance characteristics:
- Runs on edge nodes closest to users
- Sub-10ms execution time
- Doesn't block server rendering
- Automatic global deployment
AI-Friendly Design:
Middleware in Frontend Accelerator follows clear patterns:
- Single middleware.ts file at project root
- Explicit matcher configuration for protected routes
- Simple conditional logic for redirects
- Type-safe request/response objects
Limitations:
- Cannot access full Node.js APIs (edge runtime only)
- Limited to 1MB execution size
- No access to filesystem
Middleware can be used for authentication, but also for custom business logic that needs to run before request processing.