Next.js Middleware
الوسيط في Next.js (Middleware)
Definition
Code that runs before a request is completed in Next.js — used for auth guards, redirects, and A/B testing at the edge.
كود يعمل قبل اكتمال الطلب في Next.js — يُستخدم لحماية المصادقة وإعادة التوجيه واختبار A/B على الحافة.
Why It Matters
Route protection for /learning, /admin, and other authenticated pages can be handled in middleware — before the page even loads, saving one round-trip.
حماية المسارات لـ/learning و/admin وغيرها من الصفحات المصادق عليها يمكن معالجتها في الوسيط — قبل تحميل الصفحة حتى، مما يوفر رحلة ذهاب وإياب واحدة.
Full Definition
Example Usage
“// middleware.ts export function middleware(req: NextRequest) { if (!req.cookies.get('token') && req.nextUrl.pathname.startsWith('/admin')) { return NextResponse.redirect(new URL('/login', req.url)); } }”
“// middleware.ts export function middleware(req: NextRequest) { if (!req.cookies.get('token') && req.nextUrl.pathname.startsWith('/admin')) { return NextResponse.redirect(new URL('/login', req.url)); } }”
AI Builder Tips
Avoid these mistakes when using Next.js Middleware:
Using middleware for heavy Firestore queries — Edge Runtime is lightweight, run expensive work in API routes
Forgetting the `matcher` config — middleware runs on ALL routes including static files by default
Sign in to unlock guided AI explanations from AI Teacher.
Generate a Prompt
Copy this prompt and use it directly with any AI model — no setup needed.
Help me build a project using Next.js Middleware. Explain: 1. What is Next.js Middleware and why it matters 2. The core architecture and required tools 3. Step-by-step implementation plan 4. Common mistakes to avoid: Using middleware for heavy Firestore queries — Edge Runtime is lightweight, run expensive work in API routes, Forgetting the `matcher` config — middleware runs on ALL routes including static files by default 5. Best practices and production tips