Next.js Middleware

الوسيط في Next.js (Middleware)

Intermediatenextjs1 min read
middlewareedge middlewarenext middlewaremiddleware.ts

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

Next.js middleware runs on the Edge Runtime before a request is processed. Defined in `middleware.ts` at the project root. Uses `NextResponse.redirect()` or `NextResponse.rewrite()` to control routing. Common uses: redirecting unauthenticated users from protected routes, adding security headers, locale-based routing. Middleware executes on every matching request before any page or API route runs.
وسيط Next.js يعمل على Edge Runtime قبل معالجة الطلب. يُعرَّف في `middleware.ts` في جذر المشروع. يستخدم `NextResponse.redirect()` أو `NextResponse.rewrite()` للتحكم في التوجيه. الاستخدامات الشائعة: إعادة توجيه المستخدمين غير المصادق عليهم من المسارات المحمية.

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)); } }

Knowledge Graph

Avoid these mistakes when using Next.js Middleware:

1

Using middleware for heavy Firestore queries — Edge Runtime is lightweight, run expensive work in API routes

2

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.

Ready-to-Use Prompt
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

Official Resources