الـ Middleware ودورة حياة الـ request جُوّه Express
الـ middleware function بـ (req, res, next)، وإن Express بيمشي عليهم بالترتيب. next() و next(err)، وإن الـ middleware يا يرد يا ينادي next. request id و logger بـ res.on("finish")، و middleware factory بـ closure، و middleware على route واحد. الـ error middleware بأربع parameters، و ERR_HTTP_HEADERS_SENT لما ترد مرتين.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. Express في الحقيقة حاجة واحدة بس: سلسلة functions، الـ request بيعدّي عليهم واحدة واحدة. كل واحدة اسمها middleware، وبتاخد تلات حاجات: req و res و next. وقدامها اختيارين: يا ترد على الـ request وتخلص، يا تنادي next فيروح للي بعدها. هنحط logs بأرقام، علشان نشوف الترتيب بالزبط. نشغّل.
import express from "express";
const app = express();
app.use((req, res, next) => {
console.log("1 أول middleware");
next();
console.log("5 رجعنا بعد next (الـ response خلص)");
});
app.use((req, res, next) => {
console.log("2 تاني middleware");
next();
});
app.get("/hello", (req, res, next) => {
console.log("3 الـ route");
res.json({ ok: true });
console.log("4 بعد res.json");
});
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /hello
1 أول middleware
2 تاني middleware
3 الـ route
4 بعد res.json
5 رجعنا بعد next (الـ response خلص)
← 200 OK
{
"ok": true
}واحد، اتنين، تلاتة، أربعة، خمسة. واحد واتنين: الـ middlewares بالترتيب. تلاتة: الـ route رد. أربعة: السطر اللي بعد res dot json اشتغل عادي، لأن الرد مش return. وخمسة: لما next رجعت، كمّلنا في أول middleware. بس خد بالك: خمسة اتطبعت بعد ما الـ response اتبعت، وده مش مكان مضمون تسجّل فيه، خصوصًا مع async. الطريقة الصح نشوفها دلوقتي. تلات middlewares حقيقيين، بتلاقيهم في أي backend محترم. request id: كل request ليه رقم، وبنرجّعه في header، فلو مستخدم اشتكى، تدوّر بالرقم في الـ logs. logger: بيسجل الـ method والـ path والـ status والوقت، وبيستنى event اسمه finish، يعني الـ response خلص فعلًا. و requireRole: function بترجّع middleware، بإعدادات، ودي closure زي اللي اتعلمناها. وبنحطها على route واحد بس: admin stats.
نشغّل.
import express from "express";
import crypto from "node:crypto";
const app = express();
// 1) request id: كل request ليه رقم، يمشي معاه في كل الـ logs
app.use((req, res, next) => {
req.id = req.get("X-Request-Id") ?? crypto.randomUUID().slice(0, 8);
res.set("X-Request-Id", req.id);
next();
});
// 2) logger: بيسجل بعد ما الـ response يخلص فعلًا
app.use((req, res, next) => {
const start = process.hrtime.bigint();
res.on("finish", () => {
const ms = Number(process.hrtime.bigint() - start) / 1e6;
console.log(`[${req.id}] ${req.method} ${req.originalUrl} ${res.statusCode} ${ms < 50 ? "<50" : Math.round(ms)}ms`);
});
next();
});
// 3) factory: middleware بإعدادات (closure)
function requireRole(role) {
return (req, res, next) => {
if (req.get("X-Role") !== role) {
return res.status(403).json({ error: `محتاج ${role}` });
}
next();
};
}
app.get("/public", (req, res) => res.json({ ok: true }));
app.get("/admin/stats", requireRole("admin"), (req, res) => res.json({ users: 1200 }));
app.get("/slow", async (req, res) => {
await new Promise((r) => setTimeout(r, 120));
res.json({ done: true });
});
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /public
[883cdf0a] GET /public 200 <50ms
← 200 OK
{
"ok": true
}
→ GET /admin/stats
[21c38655] GET /admin/stats 403 <50ms
← 403 Forbidden
{
"error": "محتاج admin"
}
→ GET /admin/stats
[ff96f48f] GET /admin/stats 200 <50ms
← 200 OK
{
"users": 1200
}
→ GET /slow
[abc123] GET /slow 200 121ms
← 200 OK
{
"done": true
}كل request ليه سطر log برقمه والـ status. admin stats من غير role: four oh three، ومع admin: two hundred. والأخير: الـ request id اللي بعتناه رجع زي ما هو في الـ log، والوقت فوق المِيّة millisecond. الـ request id ده لو اتبعت لكل service تانية بتكلمها، تقدر تتبع الـ request في النزام كله، وده أساس الـ tracing اللي هنعمله بـ OpenTelemetry. الأخطاء. أول route: رد، وبعدين نادى next، والـ route التاني حاول يرد تاني. تاني route: next بـ error، ودي الطريقة اللي تبعت بيها error لـ Express. والـ error middleware: لازم يبقى بأربع parameters، أول واحد err، وإلا Express مش هيعرف إنه error handler. نشغّل.
import express from "express";
const app = express();
app.get("/twice", (req, res, next) => {
res.json({ first: true });
next(); // ❌ بعد ما الـ response اتبعت
});
app.get("/twice", (req, res) => {
res.json({ second: true });
});
app.get("/fail", (req, res, next) => {
next(new Error("حاجة وقعت"));
});
// error middleware: لازم 4 parameters
app.use((err, req, res, next) => {
console.log(`[error] ${err.message}`);
if (res.headersSent) return next(err);
res.status(500).json({ error: err.message });
});
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /twice
[error] Cannot set headers after they are sent to the client
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:642:11)
at ServerResponse.header (/home/you/my-backend/node_modules/express/lib/response.js:685:10)
at ServerResponse.send (/home/you/my-backend/node_modules/express/lib/response.js:141:14)
at ServerResponse.json (/home/you/my-backend/node_modules/express/lib/response.js:249:15)
at file:///home/you/my-backend/server.js:10:7
at Layer.handleRequest (/home/you/my-backend/node_modules/router/lib/layer.js:152:17)
at next (/home/you/my-backend/node_modules/router/lib/route.js:157:13)
at Route.dispatch (/home/you/my-backend/node_modules/router/lib/route.js:117:3)
at handle (/home/you/my-backend/node_modules/router/index.js:435:11)
at Layer.handleRequest (/home/you/my-backend/node_modules/router/lib/layer.js:152:17) {
code: 'ERR_HTTP_HEADERS_SENT'
}
← 200 OK
{
"first": true
}
→ GET /fail
[error] حاجة وقعت
← 500 Internal Server Error
{
"error": "حاجة وقعت"
}twice: الـ client استلم first بس، وفي الـ server: ERR HTTP HEADERS SENT، Cannot set headers after they are sent. يعني حاولنا نرد مرتين. ده bug مشهور جدًّا، بيحصل لما تنسى return قبل res dot json جُوّه if. fail: الـ error handler مسكه، ورد five hundred. وسطر headersSent في الـ handler: لو الرد بدأ يتبعت فعلًا، ما ينفعش نغيّره، فنسلّمه لـ Express يقفل الـ connection. التحدي: API key و quota. middleware بيقرا الـ API key ويتعرف على العميل. factory بتعدّ الـ requests لكل key، ولو عدّى الحد four twenty nine، ومعاها Retry-After. و headers فيها الحد والباقي. والـ health من غير أي حاجة. والترتيب هنا مهم جدًّا. ست حالات اختبار في الكومنت.
apiKey (401 لو مفيش أو غلط) و quota() (429 + Retry-After: 60، و X-RateLimit headers) على /v1/me بالترتيب، و /health من غير middleware.
الحل. apiKey: من غير key four oh one، key غلط four oh one، غير كده req dot client. quota: Map جُوّه الـ closure، نزوّد العداد، ولو عدّى: Retry-After و four twenty nine. وإلا الـ headers و next. والـ route: apiKey الأول، وبعدها quota. لو اتعكسوا، quota هتقرا req dot client وهي لسه undefined. نشغّل.
import express from "express";
const app = express();
const KEYS = new Map([
["key-free", { plan: "free", perMinute: 2 }],
["key-pro", { plan: "pro", perMinute: 100 }],
]);
function apiKey(req, res, next) {
const key = req.get("X-Api-Key");
if (!key) return res.status(401).json({ error: "مفيش API key" });
const client = KEYS.get(key);
if (!client) return res.status(401).json({ error: "key غلط" });
req.client = { key, ...client };
next();
}
function quota() {
const used = new Map();
return (req, res, next) => {
const { key, perMinute } = req.client;
const n = (used.get(key) ?? 0) + 1;
used.set(key, n);
if (n > perMinute) {
res.set("Retry-After", "60");
return res.status(429).json({ error: "عدّيت الحد" });
}
res.set({ "X-RateLimit-Limit": String(perMinute), "X-RateLimit-Remaining": String(perMinute - n) });
next();
};
}
app.get("/health", (req, res) => res.json({ ok: true }));
app.get("/v1/me", apiKey, quota(), (req, res) => res.json({ plan: req.client.plan }));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /health
← 200 OK
{
"ok": true
}
→ GET /v1/me
← 401 Unauthorized
{
"error": "مفيش API key"
}
→ GET /v1/me
← 401 Unauthorized
{
"error": "key غلط"
}
→ GET /v1/me
← 200 OK
connection: keep-alive
content-length: 15
content-type: application/json; charset=utf-8
etag: W/"f-PSELJELPsxpZ3o3sd/j/6T8aEkQ"
keep-alive: timeout=5
x-powered-by: Express
x-ratelimit-limit: 2
x-ratelimit-remaining: 1
{
"plan": "free"
}
→ GET /v1/me
← 200 OK
{
"plan": "free"
}
→ GET /v1/me
← 429 Too Many Requests
connection: keep-alive
content-length: 31
content-type: application/json; charset=utf-8
etag: W/"1f-LbQaNJP3G2lT0SW+d2CzVfzMSUA"
keep-alive: timeout=5
retry-after: 60
x-powered-by: Express
{
"error": "عدّيت الحد"
}health تمام. من غير key، وبـ key غلط: four oh one. key-free: two hundred، و remaining واحد. التانية: two hundred. التالتة: four twenty nine و retry-after ستين. العداد هنا في الـ memory، فلو عندك أكتر من server، كل واحد هيعدّ لوحده، ولو الـ server عمل restart العداد يتصفّر. الحل الصح بـ Redis، وليه درس كامل. الدرس الجاي: الـ validation للمدخلات بـ Zod.
03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Expressانت هنا
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem