Matjar (Arabic for "The Store") is an end-to-end, production-grade luxury e-commerce ecosystem. It couples a cross-platform mobile application built with Flutter 3 and Riverpod with an enterprise-grade RESTful API powered by Node.js (ESM), Express 5, and Prisma 7 on PostgreSQL.
Engineered with high standards for software craftsmanship, Matjar showcases clean domain-driven architecture, resilient mobile networking with automated JWT lifecycle management, ACID-compliant transactional checkout, strict order lifecycle state machines, and real-time operational analytics for store administrators.
The app features a custom warm minimalist design system with editorial typography, skeleton shimmers, and micro-animations.
Matjar follows a decoupled, layered architectural pattern across both client and server to guarantee testability, maintainability, and scalability.
flowchart TB
subgraph Client["Flutter Mobile Client (matjar_app)"]
UI["UI Layer (Screens, Custom Design System, Shimmers)"]
State["State Layer (Riverpod Providers & Notifiers)"]
Nav["Router (GoRouter with RBAC Redirect Guards)"]
Net["Network Layer (Dio + Auto-Refresh JWT Interceptor)"]
Store["Secure Persistence (Flutter Secure Storage)"]
UI --> State
State --> Nav
State --> Net
Net <--> Store
end
subgraph Gateway["API Gateway & Security Layer"]
Rate["Express Rate Limiter"]
Sec["Helmet & CORS Policy"]
Logger["Morgan HTTP Logger"]
end
subgraph Backend["Express 5 REST API (src/)"]
Router["Modular Domain Routers (/api/v1/*)"]
Val["Zod Schema Validation Middleware"]
AuthM["JWT Auth & Role Guards (RBAC)"]
Ctrl["Controller Layer (HTTP Serialization)"]
Svc["Service Layer (Business Rules & Transactions)"]
Router --> Val --> AuthM --> Ctrl --> Svc
end
subgraph Persistence["Data & Infrastructure Layer"]
ORM["Prisma ORM 7 (@prisma/adapter-pg)"]
DB[(PostgreSQL Database)]
Static["Static File Server (/uploads)"]
Swagger["OpenAPI / Swagger Documentation (/api-docs)"]
Svc --> ORM
ORM <--> DB
end
Net <==>|"REST / JSON over HTTPS"| Gateway
Gateway --> Backend
Backend -.-> Static
Backend -.-> Swagger
- Atomic Checkout (
prisma.$transaction): Orders cannot enter an inconsistent state. When a customer initiates checkout, the backend runs a serialized database transaction that:- Validates address ownership and active cart items.
- Verifies stock availability and active status for every product.
- Creates immutable order records snapshotting product titles and prices at the moment of purchase.
- Atomically decrements warehouse inventory (
decrement: item.quantity). - Clears the customer's cart.
- Auto-Restocking Lifecycle: Cancelling a pending or paid order automatically increments stock levels back to the catalog and adjusts refund statuses.
- Safe Soft Deactivations: Products associated with past order histories are prevented from hard deletion; instead, they transition into soft-deactivated states to preserve financial auditing records.
- Customer Storefront:
- Editorial curation with smooth animations and skeleton shimmering.
- Multi-attribute catalog filtering (search query, category hierarchy, price range, sorting).
- Multi-address management with default flag selection.
- Verified Purchase Reviews: Customers can only review products they have purchased and received (
DELIVEREDstatus).
- Admin Atelier:
- High-level KPI metrics: gross revenue, total orders, product catalog count, and registered users.
- Real-time order fulfillment pipeline (
PENDINGโPAIDโSHIPPEDโDELIVERED). - Full product inventory management with multi-image uploads via
multer. - User role assignment and account deactivation controls.
- Access Tokens (15m) and Refresh Tokens (7d) signed via cryptographically secure secrets.
- Dio Interceptor Queue: The Flutter client intercepts
401 Unauthorizedresponses, buffers pending requests, exchanges the refresh token seamlessly in the background, and retries the original request with zero disruption to the user experience. - Passwords hashed using industry-standard bcrypt with salted work factors.
- Embeds Prisma 7 local database engine (
prisma devbacked by PGlite), eliminating the requirement of running a local PostgreSQL daemon or Docker container during development. - Single command bootstrapper (
npm run dev:all) that automatically starts the local database, monitors port readiness, and spawns the Express API with file-watch mode.
| Domain | Technology | Rationale & Responsibility |
|---|---|---|
| Mobile Client | Flutter 3.x & Dart | Cross-platform native compilation (Android, iOS, Web) with 60+ FPS performance. |
| State Management | Flutter Riverpod 3 | Compile-time safe, reactive dependency injection and decoupled business logic. |
| Mobile Routing | GoRouter | Declarative deep linking with asynchronous authentication and role guards. |
| Mobile HTTP | Dio 5 | Interceptor-driven networking, automatic token refresh, structured error mapping. |
| Secure Storage | flutter_secure_storage | Hardware-backed Keychain (iOS) and Keystore / EncryptedSharedPreferences (Android). |
| Backend Runtime | Node.js 24 (ESM) | Modern ECMAScript modules, top-level await, native performance. |
| Web Framework | Express 5.x | Modern routing, improved promise-based error handling, high throughput. |
| ORM & Database | Prisma 7 + PostgreSQL | Strict relational schema, automated migrations, type-safe queries via @prisma/adapter-pg. |
| Data Validation | Zod 4 | Strict request schema parsing, sanitization, and structured validation errors. |
| API Documentation | Swagger UI / OpenAPI 3 | Self-documenting interactive API playground accessible at /api-docs. |
| Security & Headers | Helmet, CORS, Rate-Limit | Protection against brute-force attacks, XSS, MIME sniffing, and clickjacking. |
The database schema is designed with strict relational constraints, foreign keys, and indexes for performant querying:
erDiagram
User ||--o{ Address : "registers"
User ||--o| Cart : "owns"
User ||--o{ Order : "places"
User ||--o{ Review : "writes"
Category ||--o{ Category : "parent/child"
Category ||--o{ Product : "classifies"
Product ||--o{ ProductImage : "contains"
Product ||--o{ CartItem : "referenced in"
Product ||--o{ OrderItem : "snapshotted in"
Product ||--o{ Review : "receives"
Cart ||--o{ CartItem : "contains"
Order ||--o{ OrderItem : "contains"
User {
string id PK
string email UK
string passwordHash
Role role "CUSTOMER | ADMIN"
string name
boolean isActive
}
Product {
string id PK
string title
string slug UK
decimal price
decimal compareAtPrice
string sku UK
int stockQty
boolean isActive
}
Order {
string id PK
string userId FK
OrderStatus status "PENDING | PAID | SHIPPED | DELIVERED | CANCELLED"
PaymentStatus paymentStatus "UNPAID | PAID | REFUNDED"
decimal subtotal
decimal total
json shippingAddress
}
OrderItem {
string id PK
string orderId FK
string productId FK
string titleSnapshot
decimal priceAtPurchase
int quantity
}
All endpoints are versioned under /api/v1. Responses adhere to a standardized contract:
- Success:
{ "success": true, "data": { ... }, "pagination": { ... } } - Error:
{ "success": false, "error": { "code": "STATUS_CODE", "message": "Details" } }
| Module | Method | Endpoint | Access Level | Description |
|---|---|---|---|---|
| Auth | POST |
/api/v1/auth/register |
Public | Register new customer account |
POST |
/api/v1/auth/login |
Public | Authenticate and obtain access + refresh tokens | |
POST |
/api/v1/auth/refresh |
Public | Refresh expired access token | |
POST |
/api/v1/auth/logout |
Authenticated | Invalidate active session | |
| Users | GET |
/api/v1/users/me |
Authenticated | Retrieve current user profile |
PUT |
/api/v1/users/me |
Authenticated | Update profile details | |
PUT |
/api/v1/users/me/password |
Authenticated | Change user password | |
| Products | GET |
/api/v1/products |
Public | Paginated product listing with filters and sorting |
GET |
/api/v1/products/:slug |
Public | Product details by slug | |
GET |
/api/v1/products/:id/reviews |
Public | Product customer reviews | |
POST |
/api/v1/products/:id/reviews |
Customer | Submit verified purchase review | |
| Cart | GET |
/api/v1/cart |
Customer | Fetch current shopping cart |
POST |
/api/v1/cart/items |
Customer | Add product to cart | |
PATCH |
/api/v1/cart/items/:id |
Customer | Update cart item quantity | |
DELETE |
/api/v1/cart/items/:id |
Customer | Remove item from cart | |
DELETE |
/api/v1/cart |
Customer | Clear cart | |
| Checkout | POST |
/api/v1/orders/checkout |
Customer | Atomic checkout with inventory reservation |
GET |
/api/v1/orders |
Customer | List customer order history | |
GET |
/api/v1/orders/:id |
Customer | Get order details | |
POST |
/api/v1/orders/:id/cancel |
Customer | Cancel order and restock items | |
| Addresses | GET / POST |
/api/v1/addresses |
Customer | List or create shipping addresses |
PUT / DELETE |
/api/v1/addresses/:id |
Customer | Update or delete address | |
| Admin | GET |
/api/v1/admin/dashboard |
Admin | Real-time sales, order counts, and user metrics |
GET / POST |
/api/v1/admin/products |
Admin | List or create catalog items | |
PUT / DELETE |
/api/v1/admin/products/:id |
Admin | Update or soft-delete product | |
POST |
/api/v1/admin/products/:id/images |
Admin | Upload product media (Multer) | |
GET |
/api/v1/admin/orders |
Admin | View all system orders across users | |
PATCH |
/api/v1/admin/orders/:id/status |
Admin | Progress order through state machine | |
GET / PATCH |
/api/v1/admin/users |
Admin | Manage user roles and activation states |
๐ Interactive Documentation: When running the server, explore the complete Swagger UI documentation at
http://localhost:4000/api-docsor importmatjar.postman_collection.json.
- Node.js: v20+ (v24 recommended) & npm
- Flutter SDK: v3.12+ and Dart
- Android Studio (for Android Emulator) or Xcode (for iOS Simulator on macOS)
-
Clone the repository:
git clone https://github.com/<your-username>/matjar.git cd matjar
-
Install dependencies:
npm install
-
Configure environment variables:
cp .env.example .env
(The default
.env.examplecomes pre-configured with local PGlite database ports and dev secrets). -
One-Command Bootstrapper:
npm run dev:all
This starts the embedded local PostgreSQL engine, initializes the database connection, runs migrations, and launches the Express server with live reload.
Alternatively, run step-by-step:
# Terminal 1: Start local database npm run db:dev # Terminal 2: Run migrations & seed data npm run prisma:migrate npm run prisma:seed # Terminal 2: Start API in watch mode npm run dev
-
Verify Backend Status:
- Health Endpoint:
http://localhost:4000/health - Swagger API Docs:
http://localhost:4000/api-docs - Default Seeded Admin:
admin@matjar.local/Admin123!
- Health Endpoint:
-
Navigate to the app directory:
cd matjar_app -
Install Flutter packages:
flutter pub get
-
Run on Target Device:
-
Android Emulator (defaults to
10.0.2.2:4000automatically):flutter run
-
iOS Simulator / Web / Desktop:
flutter run --dart-define=API_BASE_URL=http://localhost:4000
-
Physical Device (replace with your local machine's LAN IP):
flutter run --dart-define=API_BASE_URL=http://192.168.1.X:4000
-
matjar/
โโโ .env.example # Environment template
โโโ matjar.postman_collection.json # Postman API Collection
โโโ package.json # Backend scripts & dependencies
โโโ prisma/
โ โโโ schema.prisma # Prisma 7 schema & relational definitions
โ โโโ seed.js # Initial seed (Admin + luxury catalog dataset)
โโโ screenshots/ # App UI captures used across documentation
โ โโโ home.png
โ โโโ login.png
โ โโโ admin_dashbord.png
โโโ scripts/
โ โโโ dev.js # Automated zero-config DB + API orchestrator
โโโ src/ # Backend Application Source
โ โโโ app.js # Express configuration & middleware pipeline
โ โโโ server.js # HTTP server entrypoint
โ โโโ config/ # Environment configuration loader
โ โโโ docs/ # Swagger / OpenAPI specification
โ โโโ lib/ # Prisma client instance & helpers
โ โโโ middlewares/ # Auth, RBAC, error handlers, rate-limiters
โ โโโ modules/ # Domain-Driven Modules
โ โ โโโ addresses/ # Shipping address operations
โ โ โโโ admin/ # Admin KPIs & store analytics
โ โ โโโ auth/ # Registration, login, JWT refresh
โ โ โโโ cart/ # Cart item state & manipulation
โ โ โโโ categories/ # Catalog taxonomy
โ โ โโโ orders/ # Checkout transactions & state machine
โ โ โโโ products/ # Product catalog & Multer image uploads
โ โ โโโ reviews/ # Verified review submission & scoring
โ โ โโโ users/ # User profile & administration
โ โโโ utils/ # ApiError, pagination, response formatters
โโโ matjar_app/ # Cross-Platform Flutter Mobile Client
โโโ pubspec.yaml # Flutter dependencies & assets
โโโ lib/
โโโ main.dart # App initialization
โโโ core/ # Shared Infrastructure
โ โโโ config.dart # Dynamic API endpoint resolution
โ โโโ models.dart # Immutable data models & serializers
โ โโโ network.dart # Dio HTTP client & token refresh interceptor
โ โโโ router.dart # GoRouter definitions with auth guards
โ โโโ storage.dart # Secure token storage wrapper
โ โโโ theme.dart # Luxury color palette & typography
โ โโโ widgets.dart # Reusable buttons, inputs, loading skeletons
โโโ features/ # Feature-First Architecture
โโโ admin/ # Atelier dashboard, product & order management
โโโ auth/ # Sign in, registration, session management
โโโ catalog/ # Search, filter chips, product details
โโโ home/ # Hero banner, category carousels, curated arrivals
โโโ profile/ # Order history, addresses, settings
โโโ shop/ # Cart, multi-step checkout, order confirmation
- Principle of Least Privilege: Customer accounts cannot elevate roles; role changes and user suspensions are restricted exclusively to administrators.
- Defensive Input Validation: Strict validation via Zod on incoming payloads ensures bad or malicious data never reaches controllers or database transactions.
- SQL Injection Immunity: All database interactions are prepared and parametrized through Prisma ORM.
- Protection Against Bruteforce & Denial of Service: Authentication endpoints are rate-limited (
express-rate-limit), with HTTP headers hardened viahelmet. - Client-Side Storage: Sensitive JWT credentials are encrypted using platform keystores via
flutter_secure_storage.
- Payment Gateway Integration: Stripe & Apple Pay / Google Pay webhooks.
- Push Notifications: Firebase Cloud Messaging (FCM) for live order status updates.
- Real-Time Analytics: WebSockets / Server-Sent Events (SSE) for live admin dashboard counters.
- Full-Text Search Engine: Algolia or PostgreSQL Full-Text Search for fuzzy matching.
Crafted with passion for clean code and modern full-stack mobile architecture.
- Portfolio: Portfolio
- GitHub: @ModatherAli
- LinkedIn: LinkedIn Profile
- Email:
modather0ali@gmail.com


