Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
الـ async errors بقت بتوصل للـ error handler لوحدها. صيغة الـ paths الجديدة (path-to-regexp 8): :id? بقت {/:id}، و * بقت *name، والـ regex اتشالت. التغييرات الساكتة اللي ما بترميش error: res.json(201, x) و res.send(404) و redirect("back") و req.body بقت undefined من غير body parser، و req.query بالـ parser البسيط. وخطة نقل عملية.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. Express خمسة نزلت بعد عشر سنين من أربعة، وأغلب الـ tutorials والـ projects اللي هتقابلها لسه مكتوبة لأربعة. فلازم تعرف الفروق، لأن بعضها بيرمي error وقت التشغيل، وده سهل، وبعضها ساكت: الـ code بيشتغل بس بيعمل حاجة غلط، وده الخطر. نبدأ بالـ paths: code مكتوب لأربعة: id اختياري بـ question mark، و star لكل حاجة. نشغّل.
import express from "express";
const app = express();
// code مكتوب لـ Express 4
app.get("/users/:id?", (req, res) => res.json({ id: req.params.id ?? "all" }));
app.get("*", (req, res) => res.status(404).json({ error: "مش موجود" }));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:130
throw new PathError(`Unexpected ${value} at index ${index - 1}`, str);
^
PathError [TypeError]: Unexpected ? at index 10: /users/:id?; visit https://git.new/pathToRegexpError for info
at consumeUntil (/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:130:23)
at parse (/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:140:26)
at process (/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:263:56)
at pathToRegexp (/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:274:5)
at Object.match (/home/you/my-backend/node_modules/path-to-regexp/dist/index.js:225:30)
at matcher (/home/you/my-backend/node_modules/router/lib/layer.js:86:23)
at new Layer (/home/you/my-backend/node_modules/router/lib/layer.js:93:62)
at router.route (/home/you/my-backend/node_modules/router/index.js:428:17)
at app.route (/home/you/my-backend/node_modules/express/lib/application.js:257:22)
at app.<computed> [as get] (/home/you/my-backend/node_modules/express/lib/application.js:478:22) {
originalPath: '/us
…الـ server ما قامش أصلًا: TypeError: Unexpected question mark. Express خمسة بتستخدم path-to-regexp إصدار تمانية، واتشال منها: علامة الاستفهام للاختياري. الـ star من غير اسم. والـ regex جُوّه الـ path. والسبب أمني: الـ regex دي كانت بتعمل مشكلة اسمها ReDoS، path معمول مخصوص يخلي الـ server يلف في الـ regex لدقايق. نفس الـ routes بالصيغة الجديدة. نشغّل.
import express from "express";
const app = express();
// Express 5: الاختياري بـ {} والـ wildcard ليه اسم
app.get("/users{/:id}", (req, res) => res.json({ id: req.params.id ?? "all" }));
app.get("/*splat", (req, res) => res.status(404).json({ error: "مش موجود" }));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /users
← 200 OK
{
"id": "all"
}
→ GET /users/7
← 200 OK
{
"id": "7"
}
→ GET /anything/else
← 404 Not Found
{
"error": "مش موجود"
}اشتغلت: all، وسبعة، والـ four oh four. دلوقتي الأخطر: التغييرات الساكتة. كل سطر هنا كان صح في Express أربعة: res dot json بـ status في الأول. res dot send برقم. redirect لـ back. قراية req dot body من غير express dot json. والـ query فيها nested و array. نشغّل.
import express from "express";
const app = express();
// كل سطر هنا كان شغال صح في Express 4
app.post("/orders", (req, res) => res.json(201, { id: 7 }));
app.get("/gone", (req, res) => res.send(404));
app.get("/back", (req, res) => res.redirect("back"));
app.post("/echo", (req, res) => res.json({ name: req.body.name }));
app.get("/search", (req, res) => res.json(req.query));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ POST /orders
← 200 OK
201
→ GET /gone
← 200 OK
404
→ GET /back
← 302 Found
connection: keep-alive
content-length: 26
content-type: text/plain; charset=utf-8
keep-alive: timeout=5
location: back
vary: Accept
x-powered-by: Express
Found. Redirecting to back
→ POST /echo
{"name":"مُنى"}
TypeError: Cannot read properties of undefined (reading 'name')
at file:///home/you/my-backend/server.js:9:59
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)
at /home/you/my-backend/node_modules/router/index.js:295:15
at processParams (/home/you/my-backend/node_modules/router/index.js:582:12)
at next (/home/you/my-backend/node_modules/router/index.js:291:5)
at router.handle (/home/you/my-backend/node_modules/router/index.js:186:3)
← 500 Internal Server Error
<!DOCTY
…orders: two hundred، والـ body هو الرقم two oh one! مش الـ object. gone: two hundred، والـ body four oh four كنص. back: redirect لـ location اسمها back حرفيًا، يعني المتصفح هيروح على slash back. echo: five hundred، لأن req dot body بقت undefined من غير parser، وقرينا name منها. و search: filter role ما اتحوّلتش object زي زمان، فضلت key بالـ brackets، والـ tag بقت array. ولا واحد فيهم رمى error وقت ما الـ server قام. ودي اللي بتتسرب للإنتاج. التصليح، وزودنا الميزة الأهم في Express خمسة: async function رمت error؟ بيوصل للـ error handler لوحده. في أربعة كان لازم try و catch و next في كل route، أو مكتبة زي express-async-errors، وإلا الـ server يقع أو الـ request يعلّق. نشغّل.
import express from "express";
const app = express();
app.use(express.json());
app.post("/orders", (req, res) => res.status(201).json({ id: 7 }));
app.get("/gone", (req, res) => res.sendStatus(404));
app.get("/back", (req, res) => res.redirect(req.get("Referer") || "/"));
app.post("/echo", (req, res) => res.json({ name: req.body?.name ?? null }));
app.get("/search", (req, res) => res.json(req.query));
// async errors بتوصل للـ error handler لوحدها في Express 5
app.get("/crash", async () => {
throw new Error("الـ database مش بترد");
});
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ POST /orders
← 201 Created
{
"id": 7
}
→ GET /gone
← 404 Not Found
Not Found
→ POST /echo
{"name":"مُنى"}
← 200 OK
{
"name": "مُنى"
}
→ GET /crash
← 500 Internal Server Error
{
"error": "الـ database مش بترد"
}two oh one بالـ object. four oh four، والـ body Not Found. مُنى. والـ crash: five hundred من الـ error handler، والـ server لسه شغال. خطة النقل في أي مشروع: نزّل Express خمسة في branch. نشغّل الـ server: أي path غلط هيرمي فورًا، صلّحه. دوّر بالـ search على res dot json بـ comma بعد رقم، و res dot send برقم، و back، و req dot param. نشغّل الـ tests كلها. وشيل express-async-errors لو موجودة. التحدي: انقل الملف القديم. هلزقلك server مكتوب لـ Express أربعة، فيه خمس مشاكل: path اختياري قديم، و send برقم، و json بـ status، و POST بيقع لو مفيش title، و redirect لـ back، و star. صلّحهم كلهم على خمسة. سبع حالات اختبار في الكومنت.
صلّح server.js لـ Express 5: {/:id}، و 404 بـ JSON، و status(201).json، و 400 لو مفيش title، و redirect(301, "/posts")، و 404 في الآخر بـ app.use.
الحل. curly braces للـ id. status four oh four بـ json. title بـ optional chaining، ولو مش موجود four hundred. status two oh one. redirect three oh one لـ slash posts. و app dot use في الآخر بدل الـ star. نشغّل.
import express from "express";
const app = express();
app.use(express.json());
const posts = [{ id: 1, title: "أول بوست" }];
app.get("/posts{/:id}", (req, res) => {
if (!req.params.id) return res.json(posts);
const post = posts.find((p) => p.id === Number(req.params.id));
if (!post) return res.status(404).json({ error: "مش موجود" });
res.json(post);
});
app.post("/posts", (req, res) => {
const title = req.body?.title;
if (!title) return res.status(400).json({ error: "title مطلوب" });
const post = { id: posts.length + 1, title };
posts.push(post);
res.status(201).json(post);
});
app.get("/old-feed", (req, res) => res.redirect(301, "/posts"));
app.use((req, res) => res.status(404).json({ error: "مش موجود" }));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /posts
← 200 OK
[
{
"id": 1,
"title": "أول بوست"
}
]
→ GET /posts/1
← 200 OK
{
"id": 1,
"title": "أول بوست"
}
→ GET /posts/9
← 404 Not Found
{
"error": "مش موجود"
}
→ POST /posts
{"title":"تاني"}
← 201 Created
{
"id": 2,
"title": "تاني"
}
→ POST /posts
{}
← 400 Bad Request
{
"error": "title مطلوب"
}
→ GET /old-feed
← 301 Moved Permanently
connection: keep-alive
content-length: 40
content-type: text/plain; charset=utf-8
keep-alive: timeout=5
location: /posts
vary: Accept
x-powered-by: Express
Moved Permanently. Redirecting to /posts
→ GET /nope
← 404 Not Found
{
"error": "مش موجود"
}السبعة زي الاختبار، والـ redirect رجّع three oh one و location slash posts. الدرس الجاي: الـ middleware بالتفصيل، ودورة حياة الـ request جُوّه Express.
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