A production-shaped MERN movie catalog where anyone can browse, signed-in users post one honest review per film, and admins curate the library — with ratings computed in a single database aggregation.
| Overview | Features | Tech Stack |
| Architecture | Project Structure | Quick Start |
| Environment Variables | API Reference | Data Model |
| Security | Performance | CI/CD & Deployment |
| Design System | Roadmap | License |
-
Backend (Render) : https://movie-mafia-project.onrender.com/
-
Frontend (Vercel) : https://movie-mafia-project.vercel.app/
- Browse the full catalog with poster grid, star ratings and live review counts
- Debounced search (250 ms) across movie titles — no request storm while typing
- Sort by Newest, Top Rated or Title A–Z
- Five curated collections: All, Top Rated, New Releases, Classics, Undiscovered
- Full movie detail pages with the complete review thread
- Register and sign in with JWT-backed sessions that survive page refreshes
- Post a 1–5 star rating with a written review — one per film, editable any time
- Flag reviews as spoilers so other users can opt in before reading
- Delete your own reviews at any point
- Dedicated Admin Dashboard behind a role-guarded route
- Full CRUD on the movie catalog — add, edit and delete titles
- Cascading deletes: removing a movie cleans up all of its reviews in the same request
- Moderate and remove any user's review
|
Frontend
|
Backend
|
Infrastructure
|
┌──────────────────────────────────────────────────────────────────────┐
│ CLIENT · React 18 + Vite │
│ │
│ Pages Components State & Utilities │
│ ───── ────────── ───────────────── │
│ Home MovieGrid StarRating AuthContext (Provider) │
│ MovieDetails MovieCard ReviewCard api.js (fetch wrapper) │
│ Login/Register ReviewForm SearchBar auth.js (token store) │
│ AdminDashboard SortDropdown Modal validators.js │
│ Add/EditMovie Navbar Sidebar useReveal (hook) │
│ ProtectedRoute · AdminRoute │
└───────────────────────────────┬──────────────────────────────────────┘
│ HTTPS · JSON · Bearer <JWT>
▼
┌──────────────────────────────────────────────────────────────────────┐
│ SERVER · Express 5 REST API │
│ │
│ Helmet → CORS → JSON body parser (1 MB cap) │
│ │ │
│ ▼ │
│ Routes ──► protect (JWT) ──► adminOnly ──► rateLimit │
│ │ │
│ ▼ │
│ Validator middleware ──► Controllers ──► asyncHandler │
│ │ │
│ ▼ │
│ Centralized error middleware (11000 → 409) │
└───────────────────────────────┬──────────────────────────────────────┘
│ Mongoose ODM
▼
┌──────────────────────────────────────────────────────────────────────┐
│ DATABASE · MongoDB │
│ │
│ users movies reviews │
│ ───── ────── ─────── │
│ username (unique) title user_id ─┐ │
│ email (unique) synopsis movie_id ─┤ compound │
│ password (bcrypt) poster_url rating │ unique │
│ role: user | admin release_year body │ index │
│ created_by ──► users spoiler_flag │
└──────────────────────────────────────────────────────────────────────┘
Request lifecycle for a protected write:
POST /api/movies/:movieId/reviews
│
├─ 1. helmet() → security headers
├─ 2. cors() → origin allowlist check
├─ 3. express.json() → parse body, reject > 1 MB
├─ 4. protect → verify JWT, attach req.user → 401 on failure
├─ 5. reviewRateLimiter → 10 requests / minute / IP → 429 on failure
├─ 6. reviewValidator → rating 1–5, body length, types → 400 on failure
├─ 7. controller → upsert via findOneAndUpdate → 200
└─ 8. errorHandler → any throw lands here, mapped to a status code
CineRate/
│
├── client/ # React + Vite frontend
│ ├── src/
│ │ ├── api/api.js # Centralized fetch wrapper + auth header injection
│ │ ├── components/ # 13 reusable UI components
│ │ │ ├── AdminRoute.jsx # Role-guarded route wrapper
│ │ │ ├── ProtectedRoute.jsx # Auth-guarded route wrapper
│ │ │ ├── MovieCard.jsx # Poster tile with rating badge
│ │ │ ├── MovieGrid.jsx # Responsive grid + skeleton loaders
│ │ │ ├── ReviewCard.jsx # Review with spoiler blur + owner actions
│ │ │ ├── ReviewForm.jsx # Create / edit review with star picker
│ │ │ ├── StarRating.jsx # Accessible 1–5 star input & display
│ │ │ ├── SearchBar.jsx # Debounced title search
│ │ │ ├── SortDropdown.jsx # Newest / Top Rated / A–Z
│ │ │ ├── Sidebar.jsx # Collection filters with live counts
│ │ │ ├── Navbar.jsx # Responsive nav with auth state
│ │ │ ├── Modal.jsx # Confirmation dialog
│ │ │ └── Footer.jsx
│ │ ├── context/AuthContext.jsx# Global auth provider (user, login, logout, isAdmin)
│ │ ├── hooks/useReveal.jsx # IntersectionObserver scroll-reveal animations
│ │ ├── pages/ # 7 routed pages
│ │ ├── utils/ # auth.js · constants.js · validators.js
│ │ ├── index.css # 780-line tokenized design system
│ │ └── main.jsx
│ ├── index.html
│ └── vite.config.js
│
├── server/ # Express REST API
│ ├── config/db.js # Mongoose connection with fail-fast guard
│ ├── controllers/ # auth · movie · review business logic
│ ├── middleware/
│ │ ├── authMiddleware.js # JWT verification → req.user
│ │ ├── adminMiddleware.js # Role gate (403 for non-admins)
│ │ ├── rateLimit.js # 10 req/min on review writes
│ │ └── errorMiddleware.js # Centralized handler, duplicate-key → 409
│ ├── models/ # User · Movie · Review schemas + indexes
│ ├── routes/ # auth · movie · review routers
│ ├── validators/ # Per-domain input validation middleware
│ ├── utils/
│ │ ├── asyncHandler.js # Promise wrapper — no try/catch in controllers
│ │ ├── generateToken.js # Signs 7-day JWTs
│ │ ├── createAdmin.js # CLI: promote or create an admin account
│ │ └── seedCatalog.js # Idempotent 29-movie catalog seeder
│ ├── app.js # Express app composition
│ ├── server.js # Bootstrap: connect → seed → listen
│ └── Procfile
│
├── .github/workflows/ci.yml # Parallel frontend + backend CI jobs
├── .env.example
└── package.json # Root convenience scripts
| Requirement | Version |
|---|---|
| Node.js | 18 or newer (CI runs 24) |
| npm | 9 or newer |
| MongoDB | Local instance or a MongoDB Atlas cluster |
git clone https://github.com/yourusername/cinerate.git
cd cinerate
cp .env.example server/.envOpen server/.env and set a real MONGO_URI, a long random JWT_SECRET, and the admin credentials you want.
💡 Generate a strong secret:
node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
npm install --prefix server
npm install --prefix clientnpm run serverOn first boot against an empty database, the seeder inserts 29 starter movies automatically.
✅ MongoDB connected: cluster0.xxxxx.mongodb.net
Added 29 starter movies to the empty catalog.
🚀 CineRate API running on port 5000
In a second terminal:
npm run clientOpen http://localhost:5173.
npm run create-admin --prefix serverThis reads ADMIN_EMAIL / ADMIN_PASSWORD from server/.env (password must be at least 12 characters). If the email already exists, the user is promoted to admin and their password is preserved.
Sign in with those credentials and the Admin link appears in the navbar.
# client/.env
VITE_API_URL=https://your-api.example.com/apiAll server configuration lives in server/.env:
| Variable | Required | Description | Example |
|---|---|---|---|
PORT |
— | Port the API listens on | 5000 |
MONGO_URI |
✅ | MongoDB connection string — the server exits if missing | mongodb://127.0.0.1:27017/cinerate |
JWT_SECRET |
✅ | Signing key for access tokens — use 48+ random bytes | a3f9… |
CLIENT_URL |
— | Allowed CORS origin | http://localhost:5173 |
ADMIN_EMAIL |
✅* | Email for the create-admin script |
you@example.com |
ADMIN_PASSWORD |
✅* | Admin password, minimum 12 characters | … |
* Required only when running npm run create-admin.
Client configuration lives in client/.env:
| Variable | Default | Description |
|---|---|---|
VITE_API_URL |
http://localhost:5000/api |
Base URL of the CineRate API |
⚠️ .envfiles are gitignored. Never commit real secrets — only.env.example.
Base URL: http://localhost:5000/api
Authenticated routes expect: Authorization: Bearer <token>
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/api/health |
Public | Liveness probe — returns { status: "OK" } |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/api/auth/register |
Public | Create an account, returns a JWT |
POST |
/api/auth/login |
Public | Sign in, returns a JWT |
GET |
/api/auth/me |
🔒 User | Current user profile (password excluded) |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/api/movies |
Public | List movies with ratings. Query: ?search=, ?sort=newest|rating|title |
GET |
/api/movies/:id |
Public | Single movie with average rating and review count |
POST |
/api/movies |
🛡️ Admin | Create a movie |
PUT |
/api/movies/:id |
🛡️ Admin | Update a movie (partial updates supported) |
DELETE |
/api/movies/:id |
🛡️ Admin | Delete a movie and cascade-delete its reviews |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/api/movies/:movieId/reviews |
Public | All reviews for a movie, newest first |
POST |
/api/movies/:movieId/reviews |
🔒 User | Create or update your review (upsert) — rate limited |
DELETE |
/api/reviews/:id |
🔒 Owner / 🛡️ Admin | Delete a review |
📥 Example — Register
curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{ "username": "ayush", "email": "ayush@example.com", "password": "supersecret" }'{
"message": "Registration successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": { "id": "66f...", "username": "ayush", "email": "ayush@example.com", "role": "user" }
}📥 Example — List movies sorted by rating
curl "http://localhost:5000/api/movies?sort=rating&search=dark"{
"count": 1,
"movies": [
{
"_id": "66f...",
"title": "The Dark Knight",
"release_year": 2008,
"synopsis": "Batman faces a criminal mastermind who throws Gotham into chaos.",
"poster_url": "https://image.tmdb.org/t/p/w500/...",
"created_by": { "_id": "66f...", "username": "cinerate_catalog" },
"averageRating": 4.7,
"reviewCount": 12
}
]
}📥 Example — Post a review
curl -X POST http://localhost:5000/api/movies/66f.../reviews \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{ "rating": 5, "body": "A masterclass in tension.", "spoiler_flag": false }'Posting again against the same movie updates your existing review instead of creating a duplicate.
| Code | Meaning in CineRate |
|---|---|
200 |
Success |
201 |
Resource created |
400 |
Validation failure or malformed ObjectId |
401 |
Missing, malformed or expired token |
403 |
Authenticated but not permitted (non-admin, not the review owner) |
404 |
Movie, review or user not found |
409 |
Duplicate username, email, or review — mapped from MongoDB error 11000 |
429 |
Review rate limit exceeded |
500 |
Unhandled server error |
| Field | Type | Constraints |
|---|---|---|
username |
String | required, unique, 3–30 chars, trimmed |
email |
String | required, unique, lowercased, trimmed |
password |
String | required, bcrypt hash (12 salt rounds) |
role |
String | enum user | admin, default user |
createdAt / updatedAt |
Date | automatic timestamps |
| Field | Type | Constraints |
|---|---|---|
title |
String | required, max 200 chars, trimmed |
synopsis |
String | max 5000 chars |
poster_url |
String | optional |
release_year |
Number | 1888 – 2100 |
created_by |
ObjectId → users |
required |
| Field | Type | Constraints |
|---|---|---|
user_id |
ObjectId → users |
required |
movie_id |
ObjectId → movies |
required |
rating |
Number | required, integer 1–5 |
body |
String | required, max 5000 chars, trimmed |
spoiler_flag |
Boolean | default false |
Indexes
reviewSchema.index({ user_id: 1, movie_id: 1 }, { unique: true }); // one review per user per movie
reviewSchema.index({ movie_id: 1 }); // fast lookups + aggregation| Layer | Implementation |
|---|---|
| Password storage | bcryptjs with 12 salt rounds — plaintext passwords are never stored or logged |
| Session tokens | Stateless JWT signed with JWT_SECRET, 7-day expiry, carrying only sub and role |
| Startup guard | The token generator throws if JWT_SECRET is missing; the DB layer exits if MONGO_URI is missing |
| Authorization | protect middleware verifies the bearer token; adminOnly enforces the role gate with a 403 |
| Ownership checks | Review deletion verifies review.user_id === req.user.sub or role === "admin" |
| HTTP headers | helmet() sets CSP, HSTS, X-Frame-Options, nosniff and related defaults |
| CORS | Origin restricted to CLIENT_URL with credentials enabled — no wildcard origins |
| Rate limiting | express-rate-limit caps review writes at 10 requests / minute / IP, standard headers on |
| Payload limits | JSON bodies capped at 1 MB; synopsis and review bodies capped at 5000 chars |
| Input validation | Three layers: client-side validators.js, Express validator middleware, Mongoose schema constraints |
| Injection safety | All IDs validated with mongoose.Types.ObjectId.isValid() before any query |
| Enumeration resistance | Login returns a single generic "Invalid email or password" for both unknown emails and wrong passwords |
| Secret hygiene | .env, *.pem, *.key and *.cert are gitignored; only .env.example is tracked |
The naive approach computes each movie's average with its own query — 1 + N round-trips per catalog page. CineRate issues one aggregation for the whole catalog:
const ratingData = await Review.aggregate([
{ $match: { movie_id: { $in: movieIds } } },
{ $group: {
_id: "$movie_id",
averageRating: { $avg: "$rating" },
reviewCount: { $sum: 1 }
}}
]);| Approach | DB round-trips for a 29-movie catalog |
|---|---|
| Per-movie query (N+1) | 30 |
| CineRate single aggregation | 2 |
| Reduction | ≈ 93% |
Results are joined in memory through a Map for O(1) lookup per movie.
.lean()reads — list queries skip Mongoose document hydration and return plain objects- Compound + secondary indexes —
(user_id, movie_id)andmovie_idkeep review lookups index-backed - Atomic upserts —
findOneAndUpdate(..., { upsert: true })replaces a read-then-write round-trip and removes the race condition - Debounced search — 250 ms input debounce collapses a burst of keystrokes into one request
- Parallel data fetching —
Promise.all([loadMovie(), loadReviews()])on the detail page - Skeleton loaders — perceived-performance placeholders instead of layout-shifting spinners
- Cascading deletes in one request —
Review.deleteMany()runs server-side, not as N client calls
Every push and pull request to main triggers two parallel jobs (.github/workflows/ci.yml):
┌─────────────────────────┐ ┌─────────────────────────┐
│ Frontend Build │ │ Backend Validation │
├─────────────────────────┤ ├─────────────────────────┤
│ Checkout │ │ Checkout │
│ Setup Node 24 + cache │ │ Setup Node 24 + cache │
│ npm ci │ │ npm ci │
│ vite build │ │ node --check server.js │
└─────────────────────────┘ └─────────────────────────┘
Both jobs use actions/setup-node npm caching keyed on each workspace's package-lock.json, so dependency installs stay warm between runs.
The API ships to AWS using a Procfile-driven process definition:
web: npm startDeployment checklist
- Set
MONGO_URIto the MongoDB Atlas connection string - Set a fresh, high-entropy
JWT_SECRET(never reuse the local one) - Set
CLIENT_URLto the deployed frontend origin so CORS allows it - Build the client with
npm run build --prefix clientand hostclient/dist/as static assets - Set
VITE_API_URLat build time to the public API URL - Run
npm run create-admin --prefix serveronce against production - Point your uptime monitor at
GET /api/health
The interface is built on a hand-written 780-line CSS design system — no Tailwind, no component library.
| Aspect | Details |
|---|---|
| Theming | CSS custom properties: --bg, --surface, --text, --muted, --border, --violet, --cyan, --gold, --success, --danger |
| Typography | Inter for body copy, Space Grotesk for display headings, loaded via preconnected Google Fonts |
| Motion | 6 keyframe animations — fade, float, marquee, pulse, shimmer, spin |
| Scroll reveal | Custom useReveal hook built on IntersectionObserver — Framer-Motion-style entrances with zero dependencies, including staggered grid delays |
| Responsive | Four breakpoints: 1150 px, 900 px, 640 px, 430 px |
| Accessibility | prefers-reduced-motion support, aria-labels on icon-only controls, semantic landmarks, keyboard-navigable star rating |
| Loading states | Shimmer skeleton cards that match final layout dimensions — no cumulative layout shift |
- Test suite — Jest + Supertest for the API, React Testing Library for components (
tests/is scaffolded) - Pagination — cursor-based paging for catalogs beyond a few hundred titles
- Refresh tokens — short-lived access tokens with httpOnly refresh cookies
- Image uploads — S3-backed poster uploads replacing URL-only input
- Genres & tags — faceted filtering beyond the current five collections
- Review helpfulness — upvotes and a "most helpful" sort
- Full-text search — MongoDB text index across title and synopsis
- Dockerization —
docker-composefor one-command local setup
- Fork the repository
- Create a branch —
git checkout -b feature/your-feature - Commit your changes —
git commit -m "Add your feature" - Push —
git push origin feature/your-feature - Open a pull request (CI must pass on both jobs)
Ayush Choudhary
Released under the MIT License. See LICENSE for details.