Full Breakdown: Building an Ad SaaS Platform with MERN + Generative AI

AdCampaignManager combines MERN with Socket.IO and Groq LLM, using a three-layer strategy to ensure reliable AI output.
AdCampaignManager is a full-stack ad campaign management platform for small agencies and freelancers. It uses the MERN architecture with a Socket.IO real-time layer and a Groq LLM AI layer, comprising 10 core modules: dashboard, authentication, campaign management, audience, analytics, subscriptions, reviews, team collaboration, support tickets, and AI insights—each with dedicated AI services. The article highlights five key engineering decisions: enforced JSON mode, cleanValue cleaning, Socket.IO room subscriptions, Node-Cron automation, and multi-role permissions with campaign lifecycle. The core conclusion: production-grade AI is not about calling an LLM, but about prompt engineering, error handling, and data cleaning—reliability over cleverness.
Existing ad campaign management tools are either too expensive or too complex. Many small agencies and freelancers still manage their campaigns with spreadsheets, and the market lacks a middle-ground option that balances functionality and ease of use. To address this, a developer built AdCampaignManager—a full-stack ad campaign management platform that combines real-time data with generative AI. This article breaks down its technical architecture and engineering decisions.

Tech Stack and Ten Core Modules
The project adopts the classic MERN architecture with additional real-time communication and AI layers. The frontend uses React + Vite + Tailwind CSS v4, the backend uses Node.js + Express.js, the database is MongoDB + Mongoose, the real-time layer relies on Socket.IO, and the AI layer calls Groq LLM's openai/gpt-oss-120b model. Image uploads are handled via Cloudinary + Multer, emails via Nodemailer, scheduled tasks via Node-Cron, and authentication is based on JWT + Bcrypt + OTP.
The platform includes 10 core modules: Dashboard (real-time display of impressions, clicks, conversions, revenue, CTR, CPC, ROI, CVR and other KPIs, all pulled in real time from MongoDB aggregation pipelines), Authentication (registration, login, email OTP verification, 2FA, password reset, session management), Campaign Management (full CRUD, status lifecycle from draft to scheduled to running to paused to completed to cancelled, with duplication and side-by-side comparison, and creative assets uploaded via Cloudinary), Audience Management (age ranges, gender, 50 countries, 50 cities, 50 interest tags, 50 languages, and device targeting, with audience overlap detection), Analytics & Insights (real-time KPIs, engagement heatmaps, traffic sources, funnel analysis, campaign leaderboards), Subscription Plans (12+ paid tiers, auto-renewal, enterprise packages, usage analytics), Reviews & Moderation (five-star ratings, sentiment badges, image uploads, admin approval workflow), Team Collaboration (Socket.IO real-time chat, kanban board, member roles, activity feed), Support Tickets (categories, priorities, reply threads, internal notes, knowledge base), AI Insights Dashboard (platform-level KPIs, anomaly alerts, AI narratives).

The MERN architecture refers to a full-stack JavaScript stack composed of four components: MongoDB, Express.js, React, and Node.js. MongoDB is a document-oriented NoSQL database that stores data in a JSON-like format, suitable for flexible business objects like campaigns and audiences; Express.js is a lightweight web framework running on Node.js that handles routing, middleware, and request processing; React handles component-based frontend rendering; Node.js provides the server-side runtime, allowing frontend and backend to share the same language.
In AdCampaignManager, a Socket.IO real-time communication layer and an AI layer calling Groq LLM are added on top of MERN, forming a hybrid architecture of "request-response + real-time push + intelligent generation." Socket.IO maintains persistent connections between client and server, ideal for chat and state synchronization; Groq LLM is invoked as an independent service by each module. This layering decouples business logic, real-time channels, and AI inference, which also explains how the platform can simultaneously support ten modules and ten AI services.
Ten Dedicated Generative AI Services
This is the key differentiator from ordinary ad management tools. Each module has its own AI service, all powered by Groq LLM.
Analytics AI handles narrative insights, anomaly detection, 30/60/90-day revenue forecasting, report generation, KPI recommendations, trend explanations, budget reallocation, and creative performance analysis. Campaign AI can write copy, suggest objectives, optimize budgets, generate names, perform quality checks, and recommend scheduling. Audience AI can recommend audiences, suggest interests, estimate reach, optimize demographics, build lookalike audiences, and resolve overlaps. Plan AI recommends packages, writes benefits, suggests upgrades, detects renewal risks, recommends pricing, and builds enterprise solutions. Review AI performs sentiment analysis, fake review detection, review summarization, drafts admin responses, moderation, and image highlight extraction. Insight AI narrates platform status, detects anomalies, forecasts revenue, generates reports, recommends KPIs, and explains trends. Support AI classifies tickets, drafts replies, detects duplicates, suggests FAQs, predicts resolution times, and auto-writes FAQs. Team AI summarizes chats, auto-assigns tasks, finds meeting times, provides productivity insights, suggests file tags, and recommends owners.

Five Key Engineering Decisions
JSON mode enforcement. Every AI prompt forces the LLM to return valid JSON. The author notes that without JSON mode enabled, the AI sometimes returns Markdown, causing the frontend parser to crash. This is the first line of defense for UI stability.
The cleanValue helper function. AI often returns placeholder values like N/A, dashes, or empty strings. This function cleans data before it reaches the frontend. Combined with array filtering after each AI response (removing invalid values), it forms a reliable "generate + clean" pattern. The author explicitly states that enforcing JSON mode first, then cleaning with cleanValue, and finally filtering arrays in post-processing—these three layers are the core approach to solving unreliable AI output.
Room-based real-time sync. Team chat uses Socket.IO room subscriptions, where each client only joins the rooms it needs, with names formatted as team:teamId, reducing bandwidth and ensuring instant updates. The author emphasizes that broadcasting to all clients would cripple performance, and room subscriptions are the right approach.
Scheduled automation. Node-Cron runs two tasks: simulating running campaigns every minute, generating realistic impressions, clicks, conversions, spend, and revenue data; and aggregating the previous day's analytics into a single snapshot document at midnight daily, enabling fast responses to 30/60/90-day queries.
Multi-role permissions and campaign lifecycle. Differentiated access between admins and regular users is implemented via owner field checks, an isAdmin boolean, and backend authorize middleware. The campaign system supports automatic status transitions from draft to scheduled to running to paused to completed to cancelled.
JSON Mode is a constraint mechanism provided by some large model APIs: when enabled, the model is forced to output only content that conforms to JSON syntax, without mixing in Markdown code blocks, explanatory text, or extra symbols. For frontends that need to programmatically parse AI results, this can significantly reduce parsing failures.
The article mentions that the author encountered AI returning Markdown that crashed the frontend parser—a typical symptom of missing this constraint. It should be noted that JSON mode only guarantees "syntactic validity," not that fields are complete or values are meaningful—the model may still fill in N/A, empty strings, or wrong types. Therefore, it must be used in conjunction with cleanValue cleaning and array filtering, forming a complete chain from "format reliability" to "data usability." This is also why the author calls it the "first line of defense" rather than a silver bullet.
Security Architecture and UI Design Philosophy
On the security side, there are ten measures: JWT access and refresh tokens, email 6-digit OTP verification (1-minute expiry), optional email 2FA, password reset with OTP plus short-lived JWT, global rate limiting at 500 requests/15 minutes and auth rate limiting at 50 requests/15 minutes, Helmet.js security headers, CORS with credentials, Cloudinary file type validation, Bcrypt 10-round salted hashing, and all secrets stored in environment variables.
The UI features glassmorphism (backdrop-blur-xl, border-2 border-white/10, rounded-3xl), a green gradient theme from black to #021d0f back to black, uppercase bold typography with tracking-[0.2em], animated arrow custom dropdowns, modal portals with background blur, color-coded toast notifications, corner bracket decorations on each card, floating icon animations, staggered fade-in table rows, and fully responsive design.

JWT (JSON Web Token) is a self-contained token format. After being issued by the server, it is stored by the client and sent with each request. The server verifies its authenticity via signature without querying a session table. AdCampaignManager uses both access tokens and refresh tokens: access tokens have short expiry for daily API calls; refresh tokens have long expiry for obtaining new tokens after the access token expires, balancing security and user experience.
OTP (One-Time Password) is a separate verification channel, typically sent as a 6-digit number to email with 1-minute expiry. It is used in three scenarios: email verification after registration, optional login two-factor authentication (2FA), and password reset. The password reset flow combines OTP with a short-lived JWT to ensure only the person who actually holds the email can complete the reset. Bcrypt stores passwords with 10-round salted hashing, making it difficult to recover plaintext even if the database is compromised. These three, together with rate limiting and Helmet.js security headers, form the platform's basic security boundary.
Six Major Challenges and Their Solutions
AI output reliability is solved with a three-layer approach (JSON mode, cleanValue cleaning, post-filtering). Real-time team chat is implemented with Socket.IO room subscriptions for refresh-free communication. Analytics collection bloat is handled with daily snapshot scheduled tasks that aggregate into a lightweight collection. Multi-role permissions use owner field plus isAdmin plus authorization middleware. Campaign lifecycle uses automatic status transitions. Image upload issues in serverless environments are solved with Cloudinary's streaming API—file buffers are pushed directly to the CDN, bypassing the failure of local disk storage in serverless deployments.
Serverless deployment runs applications in temporary containers managed by cloud providers. Instances can be created and destroyed at any time, and the local file system is usually read-only or disappears with the instance. This means the traditional approach of "storing uploaded files on the server disk and then serving them" fails under Serverless: files may be written successfully, but are lost when the instance is destroyed and cannot be read by other instances.
Cloudinary's streaming API is precisely the solution to this limitation. After Multer receives the file buffer in memory, it no longer writes to disk but directly pushes the buffer as a stream to Cloudinary's CDN, returning a publicly accessible URL stored in the database. This bypasses local disk, naturally gains CDN distribution and caching capabilities, and Cloudinary can also handle file type validation, connecting with the platform's security measures.
Future Roadmap
The author is developing a voice-based AI assistant, aiming to let users say commands like "create a new campaign for sneakers with a daily budget of 5000 rupees" and have the AI automatically fill in all fields. Other planned features include real-time collaboration with cursor tracking, a React Native mobile app, a public API for third-party developers, and an advanced predictive analytics dashboard.
Key Takeaways
Building this platform taught the author that production-grade AI is not just about calling an LLM. It's about prompt engineering, error handling, post-processing, and delivering clean data to users. The biggest lesson: reliability matters more than cleverness—simple JSON mode plus cleaning logic beats complex prompts that sometimes fail. The second lesson is that real-time features require careful architectural design; broadcasting to all clients kills performance, and room subscriptions are the way to go.
Related articles

Chain of Thought Isn't Just for AI: How Humans Can Use CoT to Improve Thinking Quality
Chain of Thought isn't just a prompt trick for large models. Starting from a Hacker News discussion, this article analyzes why CoT works for human thinking too, breaks down actionable ways to transfer it, and highlights the key differences between human CoT and machine CoT.
Cloudflare Teams Up with OpenAI: Closi…
Cloudflare Teams Up with OpenAI: Closing the Loop from Vulnerability Discovery to Defense with AI
Cloudflare uses OpenAI Daybreak to investigate security vulnerabilities and generate reviewable remediation plans, while developers use Codex to boost coding efficiency and quality.

Orca Multi-Agent Orchestration in Practice: A Guide to Parallel Collaboration with Claude and Codex
Orca is Stable AI's free open-source agent workbench supporting 34 agents like Claude Code and Codex in parallel. Learn its Git worktree isolation, multi-model orchestration, and mobile management.