Full-Stack Movie & TV Show Discovery Platform with AI-Powered Search
A streaming-style trailer browser and discovery platform built with modern web technologies, featuring user authentication, AI-powered smart search, custom collections, community rankings, personalized recommendations, and child safety controls.
Live at https://net-trailers.n8builds.dev.
| Frontend | Backend | Database | APIs | Styling | State Management | Monitoring | Testing |
|---|---|---|---|---|---|---|---|
| โฒ Next.js 16 | ๐๏ธ Turso (libSQL) | ๐ฟ Drizzle ORM | ๐ฌ TMDB | ๐จ Tailwind CSS | ๐ป Zustand | ๐ก๏ธ Sentry | ๐งช Jest |
| TS TypeScript | ๐ Auth.js (magic link) | ๐ง CF Email | ๐ค Gemini AI | ๐ญ Material-UI | ๐ GA4 | ๐งช RTL | |
| โ๏ธ React 19 | ๐ฆธ Heroicons | ๐ Vercel Analytics |
- Auth.js (NextAuth v5) Authentication
- Sign in with GitHub (optional, shown only when the OAuth App is configured); a verified GitHub email links to the account with that email
- Passwordless email magic-link sign-in (delivered through Cloudflare Email Service)
- Database sessions with secure, cookie-based session management
- Guest mode for demo access (no registration required)
- Seamless user switching between authenticated and guest accounts
- Public user profiles with customizable username, avatar, and bio
- Public profiles display user's public rankings (collections remain private)
-
Movies & TV Shows
- Browse trending, top-rated, and genre-specific content
- Unified content type system supporting both movies and TV shows
- Dedicated pages for Movies (
/movies) and TV Shows (/tv) - Genre browsing with dynamic filtering
- High-quality trailer playback with YouTube integration
- "Surprise Me" random content discovery
-
Advanced Search
- Real-time search with 300ms debounce
- Search suggestions dropdown with autocomplete
- Advanced filters (genre, year, rating, content type, popularity, vote count)
- Cast and crew filtering
- URL synchronization for shareable search results
- Minimum 2-character query with race condition prevention
-
Smart Search (AI-Powered) ๐ค
- Natural language query understanding powered by Google Gemini AI
- Voice input with live transcription (Web Speech API)
- Semantic concept recognition ("rainy day vibes", "mind-bending thrillers")
- Auto-detection of media type preferences
- Save AI search results as custom collections
- Live result count preview
-
Custom Collections (up to 20 for authenticated users, 3 for guests)
- Three Collection Types:
- Manual: Hand-picked content with drag-and-drop reordering
- TMDB Genre-Based: Auto-updating collections based on genre filters
- AI-Generated: Created from natural language queries
- Advanced filters (year range, rating, cast, director, popularity)
- Auto-updating collections with daily cron jobs
- Custom colors and emoji icons for personalization
- Display as rows on home/movies/tv pages
- Duplicate collections for variations
- Three Collection Types:
-
Default Lists
- Watchlist (primary collection)
- Liked content with dedicated
/likedpage - Hidden content with
/hiddenpage management
-
Collection Sharing
- Generate unique shareable links with public view pages
- Open Graph meta tags for rich social media previews
- View analytics (view count, timestamp)
- Revocable share links (toggle active/inactive)
- Manage all share links in one interface
- Link-only sharing: Collections are private by default, shareable only via explicit links
- No public collection browsing or discovery
-
Create Rankings
- Drag-and-drop ranking creation with custom scores
- Support for movies, TV shows, or mixed content
- Public or private visibility controls
- Custom titles, descriptions, and cover images
- Edit existing rankings anytime
- Note: Rankings support public/private visibility; collections use link-only sharing
-
Community Page (
/community)- Browse public rankings from all users
- Sort by recent, popular, most-liked, most-viewed
- Filter by media type
- Search rankings by title/description
- Tabbed interface: Rankings, Discussions, Polls
-
Engagement Features
- Like rankings (one per user)
- View count tracking
- Threaded comment system with nested replies
- Comment likes and engagement
- Delete comments (owner or ranking author)
- Public profile pages showing user's public rankings (collections are private)
-
Discussion Threads
- Create threads with rich text and image uploads
- Categorized discussions (General, Movies, TV Shows, Recommendations, Rankings, Announcements)
- Reply to threads with nested conversation support
- Thread author can delete any replies for moderation
- Like/unlike threads and replies
- View counts and engagement metrics
-
Detail pages at
/community/thread/[id] -
Polls & Voting
- Create polls with multiple choice options (2-10 options)
- Single or multiple-choice voting modes
- Optional expiration dates for time-limited polls
- Real-time vote counting with percentages
- Visual progress bars showing vote distribution
- One vote per user per poll (tracked in Turso)
- Vote tracking prevents duplicate votes
- Detail pages at
/community/polls/[id]
-
Image Upload Support
- Upload images to threads and forum posts
- Vercel Blob integration for image hosting (uploads scoped per user)
- Image preview and optimization
- Automatic image resizing for performance
-
Moderation & Safety
- Report inappropriate content (threads, replies, polls)
- Thread owners can delete replies
- Authentication required for all forum features
- Server-side ownership checks on all mutations (session-derived user id)
-
Search & Discovery
- Global search across threads and polls
- Filter by category and media type
- Sort by recent, popular, most replied, most voted
- Pagination for better performance
-
Content Filtering
- MPAA ratings for movies (G, PG, PG-13, R, NC-17)
- TV ratings (TV-Y, TV-Y7, TV-G, TV-PG, TV-14, TV-MA)
- Configurable rating threshold in settings
- Server-side filtering across all API routes
- Cache invalidation when mode changes
-
PIN Protection
- 4-digit numeric PIN requirement
- Encrypted storage with bcrypt-style hashing
- Session-based verification
- PIN setup/change/remove in settings
- Visual "PIN Protected" badge
- Required to disable child safety mode
- Guest users cannot set PINs
-
Interaction Tracking (10 types)
- View modal, add/remove from watchlist, like/unlike
- Play trailer, hide/unhide content, search, voice search
- 90-day data retention with auto-cleanup
-
Weighted Scoring Algorithm
- Like (+5), Add to Watchlist (+3), Play Trailer (+2), View (+1)
- Hide Content (-5), Remove from Watchlist (-1)
- Genre preference calculation from weighted interactions
- Minimum 10 interactions for accurate recommendations
-
"Recommended For You" Row
- Personalized based on top 3 preferred genres
- Hybrid algorithm (genre + TMDB similar content)
- Minimum rating 7.0, sorted by popularity
- Excludes already-seen content
- 6-hour cache with smart refresh
- Opt-out via privacy controls
-
In-App Notifications
- Bell icon in header with unread badge
- Dropdown panel with recent notifications
- Polling
/api/notificationsevery 30s for updates
-
Notification Types
- Collection updates (new content added via auto-update)
- New releases (watchlist items released)
- System announcements
- Collection shares
- Ranking comments and likes
-
Features
- Mark as read (individual or bulk)
- Auto-dismiss after 30 days
- Click actions (navigate to content/collection)
- Future: Email digests through Cloudflare Email Service
-
Interface & Design
- Responsive design for all devices (mobile, tablet, desktop)
- Streaming-style UI/UX with smooth animations and cinematic styling
- Consistent atmospheric hero sections across major pages with theme-specific gradients:
- Notifications (red/rose), Ratings (purple/violet), Rankings (red)
- Collections (blue/cyan), Settings (gray/slate), Security (green), Changelog (blue)
- Glowing icons with drop-shadow effects and animated gradient backgrounds
- Backdrop blur effects and rounded-2xl design language throughout
- Keyboard shortcuts for power users (press
?to view) - Dark mode optimized interface
- Lazy-loaded content rows for optimal performance
- Portfolio banner (toggleable in settings)
-
Smart Features
- Interactive tutorial for new users
- Real-time data synchronization
- Comprehensive error handling with user-friendly messages
- Toast notification system (6 types: success, error, watchlist operations, content visibility)
- Watch history tracking
- Analytics integration (GA4, Vercel Analytics)
-
Admin Dashboard (
/admin) - Portfolio management center- Real-time statistics overview (accounts, signups, activity, system health)
- Account usage visualization with limit tracking
- Demo reset controls for portfolio presentations
- Trending notification system controls (production/demo modes)
- Active users monitoring (top 10 most active)
- System logs viewer
- Email Composer - Send announcement and custom HTML emails to users
-
Admin Pages
/admin/accounts- User management with filtering, search, and CSV export/admin/signups- Signup timeline with weekly/monthly views/admin/activity- Activity analytics with login and page view tracking/admin/trending-stats- Trending notification statistics
-
Email System (Cloudflare Email Service, behind one capped email gate)
- Announcement Emails - Send plain text announcements with subject and message
- Custom HTML Emails - Rich text editor with TipTap for formatted content
- User Filtering - Send to all users, authenticated only, or guest users only
- Email Preview - Preview emails before sending with live rendering
- Rate Limiting - 100 emails/hour per admin, 3 emails/day per recipient
- XSS Protection -
sanitize-htmlsanitization on all custom HTML content - HTTPS-Only Links - Security enforced on all email links
- CAN-SPAM Compliance - Automatic unsubscribe token generation
- Email History - Track sent emails with counts and metadata (PII minimized)
-
Security
- Dual-layer authentication (client routing + server-side Auth.js session validation)
- Admin identified by sign-in email (
ADMIN_EMAILS, server-side only, not exposed to client) - Rate limiting on public endpoints (30 requests/minute per IP)
- Email rate limiting (100/hour admin, 3/day recipient)
- Input validation and sanitization
- CSRF protection via authenticatedFetch
- Server-side ownership checks on all admin API routes
-
Analytics Tracking
- Automatic page view tracking (excludes admin routes)
- Login activity monitoring
- User engagement metrics
- Activity filtering by user, type, and timeframe
- Timeline visualization grouped by day
-
Account and signup stats
- Total accounts and signups this week and month (no cap on accounts; the email limits guard costs, see
docs/costs-and-limits.md) - Signup velocity monitoring (daily/weekly/monthly)
- Total accounts and signups this week and month (no cap on accounts; the email limits guard costs, see
-
Code Quality
- TypeScript 5.9 for type safety across the entire codebase
- ESLint 9 with automatic fixes on commit (lint-staged + Husky)
- Prettier 3 for consistent code formatting
- Comprehensive Jest 30 test suite with React Testing Library 16
- Test coverage reporting
-
Architecture
- 18 Focused Zustand Stores: Migrated from monolithic "god store" to granular stores
- appStore, authStore, guestStore, sessionStore, cacheStore
- searchStore, loadingStore, uiStore, childSafetyStore
- customRowsStore, smartSearchStore, modalStore, toastStore
- watchHistoryStore, rankingStore, notificationStore, profileStore
- forumStore
- Next.js 16 with React 19 and App Router patterns
- Turso (libSQL/SQLite) via Drizzle ORM, accessed server-side through API routes
- 49 API routes organized by feature
- Sentry error monitoring (client & server-side)
- Google Analytics 4 integration
- Vercel Analytics for performance insights
- Bundle analyzer for optimization
- 18 Focused Zustand Stores: Migrated from monolithic "god store" to granular stores
Experience all features or continue as guest to explore the platform
- Node.js 18.x or higher
- npm (project migrated from pnpm to npm)
- Turso database (free tier available)
- Nothing for email: it goes through the Worker's Cloudflare Email Service binding (no key)
- TMDB API key (free from themoviedb.org)
- Google Gemini API key (free from ai.google.dev)
-
Clone the repository
git clone https://github.com/yourusername/net_trailers.git cd net_trailers -
Install dependencies
npm install
-
Environment Variables
Create a
.env.localfile in the root directory with the following variables:# Turso Database (Required) # Create a database with the Turso CLI: `turso db create nettrailer` # Then: `turso db show --url nettrailer` and `turso db tokens create nettrailer` TURSO_DATABASE_URL=libsql://your-database.turso.io TURSO_AUTH_TOKEN=your_turso_auth_token # Auth.js / NextAuth v5 (Required) # AUTH_SECRET: generate with `npx auth secret` (or `openssl rand -base64 32`) AUTH_SECRET=your_auth_secret # GitHub sign-in (Optional; the button appears only when both are set) # AUTH_GITHUB_ID=your_oauth_app_client_id # AUTH_GITHUB_SECRET=your_oauth_app_client_secret # TMDB API (Required) # Get your free API key from: https://www.themoviedb.org/settings/api TMDB_API_KEY=your_tmdb_api_key # Google Gemini AI (Required for Smart Search) # Get your free API key from: https://ai.google.dev/ GEMINI_API_KEY=your_gemini_api_key # Admin Portal (Required for admin access - SERVER-SIDE ONLY) # Sign-in emails of the admin accounts, comma-separated. A signed-in user # whose email is listed gets `session.user.isAdmin` (lib/admin.ts). # IMPORTANT: This is intentionally NOT prefixed with NEXT_PUBLIC_ to keep it server-side only. ADMIN_EMAILS=you@example.com # Email needs no key: the Worker sends through its Cloudflare Email Service # binding (wrangler.jsonc). Locally there is no binding and nothing is sent. # Cron Job Security (Required for auto-updating collections) CRON_SECRET=your_random_secret_string # Vercel Blob (Required for forum/thread image uploads) # Create a Blob store in your Vercel project; token is provided automatically there. BLOB_READ_WRITE_TOKEN=your_blob_read_write_token # App Configuration (Optional) NEXT_PUBLIC_APP_NAME=NetTrailers NEXT_PUBLIC_APP_URL=http://localhost:3000 NODE_ENV=development # Sentry Error Monitoring (Optional but recommended for production) # Get these from: https://sentry.io/ NEXT_PUBLIC_SENTRY_DSN=your_sentry_dsn SENTRY_ORG=your_sentry_org SENTRY_PROJECT=your_sentry_project # Google Analytics 4 (Optional) # Get from: https://analytics.google.com/ NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
-
Database & Auth Setup
a. Create a Turso database and apply the schema:
# Create the database and grab its URL + auth token turso db create nettrailer turso db show --url nettrailer # โ TURSO_DATABASE_URL turso db tokens create nettrailer # โ TURSO_AUTH_TOKEN # Apply the Drizzle schema (migrations live in db/migrations) npm run db:migrate # or `npm run db:push` for quick dev sync
Inspect the database any time with
npm run db:studio.b. Sign-in: by emailed link (Auth.js email provider), plus optional GitHub sign-in when
AUTH_GITHUB_IDandAUTH_GITHUB_SECRETare set (OAuth App callback/api/auth/callback/github). Locally there is no email binding, so run withAPP_ENV=testand afile:database to have sign-in links written toE2E_MAGIC_LINK_DIRinstead (seeplaywright.config.ts).c. Email: nothing to set up locally. The deployed Worker sends every email through Cloudflare Email Service from
net-trailers@n8builds.dev(DEPLOYMENT.md).There is no Firebase project, Firestore rules deploy, or Firebase Admin SDK service account to configure - all data access is server-mediated through Next.js API routes with server-side ownership checks.
-
Admin Portal Setup (Required for admin access)
a. Set your admin email:
- Add your sign-in email to
.env.localasADMIN_EMAILS(server-side only, not exposed to the client) - When you sign in with that address, the session is granted
session.user.isAdminand/adminbecomes accessible
b. Access the admin dashboard:
- Start the dev server:
npm run dev - Sign in with your admin email
- Navigate to
/adminin your browser - You should see the admin dashboard with statistics
Admin Features:
- Account management and limits
- User activity tracking
- Signup timeline and statistics
- Trending notification controls
- Demo reset for portfolio presentations
- Add your sign-in email to
-
Cron jobs (optional locally)
The deployed Worker runs three Cron Triggers (
worker/crons.ts,wrangler.jsonc), each calling its/api/cron/*route withCRON_SECRET: trending on Monday, the collection cache on Sunday and the social digest on Wednesday, all at 02:00 UTC. They can also be run from the admin dashboard; DEPLOYMENT.md shows how to try them locally. -
Run the development server
npm run dev
The server will start on port 3000 by default
-
Open your browser
Navigate to http://localhost:3000
npm run dev # Start development server (safe start with port checking)
npm run dev:next # Start Next.js dev server with polling (for WSL/Docker)
npm run dev:turbo # Start with Turbopack (experimental, faster builds)npm run build # Build for production
npm run start # Start production server
npm run analyze # Analyze bundle size with webpack analyzernpm run lint # Run ESLint
npm run lint:fix # Fix ESLint issues automatically
npm run type-check # Run TypeScript type checking (no emit)npm test # Run Jest tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
npm run test:ci # Run tests in CI mode (for GitHub Actions)npm run db:generate # Generate a migration from db/schema.ts
npm run db:migrate # Apply migrations to Turso
npm run db:push # Push schema directly to Turso (dev)
npm run db:seed # Seed the database with sample data
npm run db:studio # Open Drizzle Studio to inspect the databasenpm run prepare # Install Husky git hooksNote: The project uses lint-staged with Husky to automatically lint and format code on commit.
net_trailers/
โโโ app/ # Next.js 16 App Router
โ โโโ page.tsx # Home page with trending content
โ โโโ movies/ # Movies-only page
โ โโโ tv/ # TV shows-only page
โ โโโ search/ # Search results page
โ โโโ smart-search/ # AI-powered smart search page
โ โโโ rankings/ # Rankings management
โ โ โโโ page.tsx # User rankings dashboard
โ โ โโโ new/ # Create new ranking
โ โ โโโ [id]/ # View/edit ranking
โ โโโ community/ # Community hub with rankings, threads, polls
โ โ โโโ page.tsx # Main community page with tabs
โ โ โโโ threads/[id]/ # Thread detail pages
โ โ โโโ polls/[id]/ # Poll detail pages
โ โโโ collections/ # Collection management
โ โโโ watchlists/ # Custom watchlists
โ โโโ liked/ # Liked content page
โ โโโ hidden/ # Hidden content page
โ โโโ settings/ # User settings
โ โโโ users/[userId]/ # Public user profiles
โ โโโ share/[shareId]/ # Shared collection view
โ โโโ genres/ # Genre browsing pages
โ โ โโโ [type]/[id]/ # Dynamic genre pages
โ โโโ api/ # API routes (30+ endpoints)
โ โโโ movies/ # Movie-related endpoints
โ โโโ tv/ # TV show-related endpoints
โ โโโ search/ # Search endpoint
โ โโโ gemini/ # Gemini AI endpoints
โ โโโ smart-search/ # AI search endpoints
โ โโโ recommendations/ # Personalized recommendations
โ โโโ collections/ # Collection management
โ โโโ shares/ # Sharing endpoints
โ โโโ forum/ # Forum threads, polls, replies endpoints
โ โโโ cron/ # Cron job endpoints
โ โโโ ...
โ
โโโ components/ # 100+ React components (35,682 lines)
โ โโโ auth/ # AuthModal, AccountManagement
โ โโโ collections/ # CollectionRowLoader, CollectionEditorModal
โ โโโ common/ # Toast, LoadingSpinner, EmptyState, ErrorBoundary
โ โโโ content/ # VideoPlayer, WatchLaterButton, MyListsDropdown
โ โโโ customRows/ # CustomRowWizard, SortableCustomRowCard
โ โ โโโ smart/ # SmartRowBuilder, SmartInput, SmartStep3Preview
โ โโโ debug/ # DebugControls, WebVitalsHUD
โ โโโ layout/ # PortfolioBanner, Footer, Header, ClientLayout
โ โโโ modal/ # MoreLikeThisSection
โ โโโ modals/ # InfoModal, AuthModal, CollectionEditorModal
โ โ โโโ list-selection/ # ListSelectionModal components (17 files)
โ โ โโโ modal-sections/ # ModalVideoPlayer, VideoControls
โ โโโ forum/ # Forum components
โ โ โโโ CreateThreadModal.tsx # Thread creation modal
โ โ โโโ CreatePollModal.tsx # Poll creation modal
โ โ โโโ ThreadCard.tsx # Thread preview card
โ โ โโโ PollCard.tsx # Poll preview card
โ โ โโโ ImageUpload.tsx # Image upload component
โ โ โโโ ReportModal.tsx # Content reporting modal
โ โโโ notifications/ # NotificationPanel
โ โโโ pages/ # MoviesClient, TVClient, SmartSearchClient
โ โโโ rankings/ # RankingCreator, RankingDetail, RankingCard, CommentSection
โ โโโ recommendations/ # RecommendedForYouRow
โ โโโ search/ # SearchBar, SearchFilters, SearchSuggestionsDropdown
โ โโโ settings/ # ProfileSection, NotificationsSection, ChildSafetyPINModal
โ โโโ sharing/ # ShareModal, ManageSharesModal
โ โโโ smartSearch/ # SmartSearchOverlay, SmartSearchResults, SmartSearchInput
โ โโโ utility/ # Analytics, SessionSyncManager, KeyboardShortcuts
โ
โโโ stores/ # 18 Focused Zustand Stores
โ โโโ appStore.ts # Global UI state
โ โโโ authStore.ts # Authenticated user data (synced to Turso via API)
โ โโโ guestStore.ts # Guest user data (localStorage)
โ โโโ sessionStore.ts # Session management & user switching
โ โโโ cacheStore.ts # Client-side API response caching
โ โโโ searchStore.ts # Search state and filters
โ โโโ loadingStore.ts # Loading states across app
โ โโโ uiStore.ts # UI preferences and modal state
โ โโโ childSafetyStore.ts # Child safety PIN and settings
โ โโโ customRowsStore.ts # Custom collections
โ โโโ smartSearchStore.ts # AI search state and conversation
โ โโโ modalStore.ts # Content modal state and video player
โ โโโ toastStore.ts # Toast notification queue
โ โโโ watchHistoryStore.ts # Watch history tracking
โ โโโ rankingStore.ts # Rankings, comments, likes
โ โโโ forumStore.ts # Forum threads, polls, votes, replies
โ โโโ notificationStore.ts # In-app notifications
โ โโโ profileStore.ts # User profile data
โ
โโโ hooks/ # Custom React hooks
โ โโโ useAuth.tsx # Authentication hook
โ โโโ useUserData.ts # User data management
โ โโโ useSearch.ts # Search functionality
โ โโโ useToast.ts # Toast notifications
โ โโโ useVoiceInput.ts # Voice input for search
โ โโโ ...
โ
โโโ utils/ # Utility functions
โ โโโ tmdbApi.ts # TMDB API integration
โ โโโ tmdbFetch.ts # Secure TMDB fetch utilities
โ โโโ errorHandler.ts # Error handling utilities
โ โโโ contentFilter.ts # Content filtering logic
โ โโโ csvExport.ts # CSV export functionality
โ โโโ inputSanitization.ts # XSS protection
โ โโโ gemini/ # Gemini AI utilities
โ โ โโโ promptBuilder.ts # Construct semantic prompts
โ โ โโโ responseParser.ts # Parse AI responses
โ โโโ ...
โ
โโโ types/ # TypeScript type definitions
โ โโโ userLists.ts # User list and collection types
โ โโโ shared.ts # Shared state type definitions
โ โโโ rankings.ts # Ranking and comment types
โ โโโ forum.ts # Forum thread, poll, vote, reply types
โ โโโ ...
โ
โโโ typings.d.ts # Global TypeScript typings
โ # Includes: Content, Movie, TVShow, Genre types
โ # Type guards: isMovie(), isTVShow()
โ # Utils: getTitle(), getYear(), getRating(), etc.
โ
โโโ __tests__/ # Jest tests
โ โโโ components/ # Component tests
โ โโโ hooks/ # Hook tests
โ โโโ stores/ # Store tests
โ โโโ app/api/ # API route tests
โ
โโโ scripts/ # Development utility scripts
โ โโโ dev-safe.js # Safe dev server startup
โ โโโ create-test-user.ts
โ โโโ ...
โ
โโโ styles/ # Global styles
โ โโโ globals.css # Tailwind CSS imports
โ
โโโ public/ # Static assets
โ โโโ images/
โ โโโ ...
โ
โโโ docs/ # Documentation (55+ files)
โ โโโ features/ # Feature documentation
โ โโโ architecture/ # Architecture docs
โ โโโ ...
โ
โโโ db/ # Turso + Drizzle data layer
โ โโโ index.ts # libSQL/Drizzle client
โ โโโ schema.ts # Drizzle schema (tables, indexes)
โ โโโ migrations/ # drizzle-kit generated SQL migrations
โ โโโ queries/ # Typed query helpers (one module per domain)
โโโ auth.ts # Auth.js (NextAuth v5) config - email magic link
โโโ drizzle.config.ts # drizzle-kit configuration
โโโ instrumentation-client.ts # Sentry client config
โโโ instrumentation.ts # Sentry server config (Next.js 15+)
โโโ next.config.mjs # Next.js configuration
โโโ wrangler.jsonc # Cloudflare Worker config (bindings, crons, domain)
โโโ tailwind.config.ts # Tailwind CSS configuration
โโโ jest.config.js # Jest configuration
โโโ tsconfig.json # TypeScript configuration
The app uses 18 focused Zustand stores (migrated from monolithic "god store"):
- Store Factory Pattern:
createUserStore.ts- Shared factory for auth and guest stores - Storage Adapters:
ApiStorageAdapter- Persists authenticated user data to Turso via/api/user/preferencesLocalStorageAdapter- Browser localStorage for guest users
- Direct store access: Components use Zustand hooks (
useAppStore(),useSessionStore(), etc.) - No provider wrapper: Zustand works without root provider components
- Type-safe selectors: Optimized performance with granular subscriptions
- Optimistic updates: Updates with rollback on failure
Unified type system for movies and TV shows using discriminated unions:
// Base interface with shared properties
interface BaseContent { ... }
// Discriminated unions with media_type
interface Movie extends BaseContent { media_type: 'movie', title, release_date }
interface TVShow extends BaseContent { media_type: 'tv', name, first_air_date }
type Content = Movie | TVShow
// Type guards for runtime checking
isMovie(content): content is Movie
isTVShow(content): content is TVShow
// Utility functions for consistent access
getTitle(content) // Works for both movies and TV shows
getYear(content)
getContentType(content)
getRating(content)
getReleaseDate(content)- Critical: User ID validation before all state updates prevents data mixing
- Storage: Turso (via API routes) for authenticated users, localStorage for guests
- Session persistence: Auth.js session cookie (validated server-side) maintains auth state across refreshes
- User isolation: API routes derive the user id from the session (
withAuth/currentUserId()), never from the request body - Auto-save:
useSessionDatavalidates user ID match before persisting - Race condition prevention: Stores cleared when switching users
All data lives in Turso (libSQL/SQLite), accessed through Drizzle ORM. The
schema is defined in db/schema.ts, typed queries in db/queries/*, and the client
in db/index.ts. The browser never talks to Turso directly - every read/write goes
through a Next.js API route with server-side ownership checks (the session-derived
user id), which replace the old Firestore security rules.
Auth.js adapter: user, account, session, verificationToken
User data: user_preferences (the per-user blob as one JSON column),
profiles, interactions, interaction_summary, notifications,
watch_history, child_safety_pins
Rankings: rankings, ranking_comments, ranking_likes, comment_likes
Forum: threads, thread_replies, thread_likes, reply_likes, polls, poll_votes
Social & misc: shares (collection snapshots), user_activity, user_badges,
user_follows, content_reports, admin_emails (counts only), signup_log
- Nested arrays/objects (
Content[],rankedItems, polloptions,advancedFilters) are stored as JSON text columns; timestamps are epoch-ms integers. - Interactions are retained ~90 days; notifications auto-dismiss after 30 days.
- Migrations are managed with drizzle-kit (
npm run db:generateโnpm run db:migrate); inspect the database withnpm run db:studio.
- 30+ API routes organized by feature
- Internal routes proxy TMDB API calls (API key hidden server-side)
- TMDB API v3: Uses query parameter authentication (
?api_key=...) - Error handling via
utils/errorHandler.tswith user-friendly messages - Rate limiting: Respects TMDB's 40 requests/second limit
- Input sanitization: XSS protection on all Gemini AI routes
- Caching: Client-side cache store + server-side caching for improved performance
Smart Search Flow:
- User enters natural language query ("movies like Inception with time travel")
- Query sent to
/api/gemini/analyzewith semantic prompt - Gemini extracts:
- Genres (sci-fi, thriller)
- Concepts (time travel, mind-bending)
- Media type (auto-detected: movies)
- Cast/crew if mentioned
- Results fetched from TMDB Discover API with extracted parameters
- Live preview shows result count as user types
- User can save results as custom collection
Other AI Features:
- Collection name generation
- Row name suggestions
- Style-based recommendations
- Surprise query generation
Cron Job Flow (Daily at 2 AM UTC):
1. Vercel cron triggers /api/cron/update-collections
2. Verify CRON_SECRET for security
3. Query Turso for collections with autoUpdateEnabled: true
4. For each collection:
- Fetch TMDB Discover with collection filters
- Filter to releases after lastCheckedAt
- Append new content to collection.items
- Update lastUpdateCount, lastCheckedAt
- Create notification for user
5. Persist updates to Turso
Visual Indicators:
- "Auto" badge on collection cards
- "+5" badge showing new items count
- "Updated 2 hours ago" timestamp
The project includes a comprehensive test suite using Jest and React Testing Library:
- Components: UI component tests with user interaction simulation
- Hooks: Custom hook tests with mock providers
- Stores: Zustand store tests with state management validation
- API Routes: API endpoint tests
- Integration: End-to-end user flow testing
npm test # Run all tests
npm run test:watch # Watch mode for development
npm run test:coverage # Generate coverage report
npm run test:ci # CI mode (used in GitHub Actions)- Environment: jsdom for browser simulation
- Setup files: Automatic React Testing Library configuration
- Mocking: TMDB API responses, Turso/Drizzle queries (
db/queries/*or in-memory libSQL), Gemini AI - Coverage thresholds: Configured in
jest.config.js
- Client-side: Configured via
instrumentation-client.ts - Server-side: Configured via
instrumentation.ts(Next.js 15+ standard) - Features:
- Automatic error capture and stack traces
- User session replay
- Performance monitoring
- Breadcrumb tracking
- Privacy protection (PII filtering)
- Ignores common browser errors
- Integration: the n8builds.dev GA4 property, loaded by the consent bootstrap in
lib/consent.ts(the same rules as n8builds.dev) - Events tracked: GA4's default page views and enhanced measurement; the app sends no custom events
- Consent: visitors in European and Quebec time zones are asked first; Global Privacy Control counts as a decline; "Cookie settings" in the footer changes the choice, which is the shared
n8-consentcookie on.n8builds.dev
- Performance metrics: Core Web Vitals tracking
- Real user monitoring: Actual user experience data
- Integration: Automatic with Vercel deployment
Unified notification system with 6 toast types:
- โ Success - Green checkmark for successful operations
- โ Error - Red X mark for error messages (auto-integrated with ErrorHandler)
- โ Watchlist Add - Blue plus icon
- โ Watchlist Remove - Orange minus icon
- ๐๏ธโ๐จ๏ธ Content Hidden - Red eye-slash
- ๐๏ธ Content Shown - Green eye
Usage:
const { showSuccess, showError, showWatchlistAdd } = useToast()
showSuccess('Operation completed', 'Optional description')Components: Toast.tsx (5s auto-dismiss), ToastContainer.tsx (positioning), ToastManager.tsx (state bridge), useToast.ts (hook API)
- Lazy Loading: Content rows and images load on demand (Intersection Observer)
- Image Optimization: Next.js Image component with TMDB CDN
- Code Splitting: Dynamic imports for modals and heavy components
- Caching Strategy:
- Client-side cache for API responses (10-minute TTL)
- Recommendation cache (6-hour refresh)
- Interaction summary cache (24-hour)
- Bundle Analysis:
npm run analyzeto inspect bundle size - React 19 Features: Automatic batching, concurrent rendering
- Debounced Search: 300ms debounce prevents excessive API calls
- Zustand Granular Selectors: Minimal re-renders
Performance Metrics:
- Component files: 35,682 lines
- Build time: ~45s (Next.js 16 with caching)
- API response time: <200ms (cached)
- First Contentful Paint: <1.5s
- Time to Interactive: <3s
# Install Vercel CLI
npm i -g vercel
# Deploy
vercel
# Production deployment
vercel --prodConfiguration:
- Set environment variables in Vercel dashboard
- Enable Vercel Analytics automatically
- Configure custom domain in project settings
The app is a standard Next.js application and can be deployed to:
- Netlify: Use Next.js build plugin
- AWS Amplify: Configure build settings for Next.js
- Docker: Dockerfile can be created for containerization
- Self-hosted: Build with
npm run buildand start withnpm start
NetTrailers implements comprehensive security measures. See the full Security Documentation for details.
Key Security Features:
- Authentication: Auth.js (NextAuth v5) database sessions, validated server-side via the session cookie (no bearer tokens)
- CSRF Protection: Global CSRF protection on all state-changing API requests (POST/PUT/DELETE/PATCH)
- Input Sanitization:
sanitize-html(admin emails) andutils/inputSanitization.ts(Gemini routes), control character removal, length validation - Rate Limiting: Per-user limits on AI requests; admin email rate limits (100/hour admin, 3/day recipient)
- Data Protection: Server-side ownership checks on every API route (session-derived user id), user data isolation
- Child Safety: PIN-protected content filtering with bcrypt encryption
- API Security: Timing-safe secret comparison, request size limits
Security Headers (configured in next.config.mjs):
- X-Frame-Options: DENY
- X-Content-Type-Options: nosniff
- Referrer-Policy: strict-origin-when-cross-origin
- X-XSS-Protection: 1; mode=block
- Permissions-Policy (camera, microphone, geolocation)
- Content-Security-Policy (strict directives with base-uri, form-action)
- Strict-Transport-Security (HSTS)
- Set all required environment variables
- Create the Turso database and apply migrations (
npm run db:migrate) - Add the production host to the Turnstile widget's hostnames
- Email: the
send_emailbinding inwrangler.jsonc(domain onboarded for Cloudflare Email Service) - Set
ADMIN_EMAILSfor admin access - Create a Vercel Blob store and set
BLOB_READ_WRITE_TOKEN(for image uploads) - Enable Sentry error monitoring
- Configure Google Analytics (optional)
- Set CRON_SECRET for auto-updating collections
- Test guest mode functionality
- Verify TMDB API key and rate limits
- Test smart search with Gemini API
- Update CORS settings if needed
Codebase Size:
- Total component lines: 35,682
- Total commits: 1,240+
- Features completed: 13 major feature sets
- Documentation pages: 55+ markdown files
- API routes: 49+
- Zustand stores: 18 focused stores
- Components created: 100+ components
- Lines of code: ~50,000+ (estimated)
- Security documentation: 450+ lines
- Pages with cinematic styling: 8 (Nov 2025)
Development Time:
- Approximately 3 months of active development
- Continuous improvements and polish
From roadmap and TODO.md:
- User-facing email digests (admin email system already shipped via Cloudflare Email Service)
- PWA implementation (offline support)
- Analytics dashboard (user-facing)
- Advanced search facets and sorting
- Social features (follow users, activity feed)
- Content reviews (user-written reviews and ratings)
- Multi-language support (i18n)
- Dark/light mode toggle
- Export rankings as images (social media sharing)
- Mobile app (React Native)
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- TMDB for the comprehensive movie database API
- Google Gemini AI for natural language processing
- Turso and Drizzle ORM for the database layer
- Auth.js for authentication
- Next.js for the React framework
- Tailwind CSS for utility-first styling
- Zustand for state management
Built with โค๏ธ using modern web technologies
๐ Portfolio โข ๐ผ LinkedIn โข ๐ฆ Twitter