Middleware (Server)

الوسيط في الخادم (Server Middleware)

Intermediatebackend1 min read
server middlewarerequest middlewareauth middlewarecors middlewaremiddleware function

Definition

Code that processes requests before they reach a route handler — for auth checks, rate limiting, and header injection.

كود يعالج الطلبات قبل وصولها إلى معالج المسار — لفحوصات المصادقة وتحديد المعدل وحقن الترويسات.

Why It Matters

verifyAdminRequest() in 404Fault IS middleware — it's called at the start of every admin API route to verify authentication and admin role before processing the actual request.

verifyAdminRequest() في 404Fault هو وسيط — يُستدعى في بداية كل مسار API للمدير للتحقق من المصادقة ودور المدير قبل معالجة الطلب الفعلي.

Full Definition

Server-side middleware runs between an HTTP request arriving and the route handler executing it. It can modify, redirect, or reject requests. In Express.js, this is literal middleware functions. In Next.js, the middleware.ts file handles this at the edge. In Next.js API routes, middleware patterns are implemented manually (e.g., calling `verifyAdminRequest()` at the top of every admin route).
الوسيط من جانب الخادم يعمل بين وصول طلب HTTP وتنفيذ معالج المسار له. يمكنه تعديل الطلبات أو إعادة توجيهها أو رفضها. في مسارات Next.js API، أنماط الوسيط تُنفَّذ يدويًا (مثل استدعاء `verifyAdminRequest()`).

Example Usage

// admin route pattern: export async function POST(req: Request) { const adminCheck = await verifyAdminRequest(req); if (!adminCheck.ok) return adminCheck.error; // proceed... }

// نمط مسار المدير: export async function POST(req: Request) { const adminCheck = await verifyAdminRequest(req); if (!adminCheck.ok) return adminCheck.error; // تابع... }

Knowledge Graph

Avoid these mistakes when using Middleware (Server):

1

Putting heavy database queries in middleware — keep it lightweight

2

Not applying middleware consistently to all related routes

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 Middleware (Server).

Explain:
1. What is Middleware (Server) and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Putting heavy database queries in middleware — keep it lightweight, Not applying middleware consistently to all related routes
5. Best practices and production tips

Official Resources