Complete AI prompt library for MERN stack developers. Production-ready prompts for MongoDB schema design, Express REST APIs, React components, authentication, testing, CI/CD, and performance — with good vs bad prompt examples and architecture guidance.
Why MERN Developers Using AI Prompts Ship Faster
The MERN stack powers millions of production applications in 2026. The engineers building fastest on this stack aren't writing less — they're prompting better. A vague request like "build me a login" produces generic, insecure boilerplate that needs hours of rework. A precisely engineered AI prompt produces a JWT rotation system with Redis session management, OWASP-compliant security headers, Zod validation, and full test coverage — ready to review and ship.
Every prompt in this guide follows the CRISP framework: assign a senior role, set the context, define exact requirements, specify the output format, and state the security constraints. These are the prompts senior MERN engineers use in real production workflows — not tutorial examples.
1. Architecture & Project Structure
Architecture decisions made on day one are the most expensive to undo. Use this prompt before writing the first line of application code.
You are a senior MERN stack architect who has built and scaled SaaS products to 1M+ users.
Design a production-grade monorepo structure for a multi-tenant MERN SaaS with:
- Express 5 + TypeScript API with REST and WebSocket support
- React 19 + Vite frontend, Zustand for global state
- MongoDB + Mongoose 8, multi-tenant with soft deletes and audit logging
- Redis for sessions, rate limiting, and Bull job queues
- Role-based access control: super_admin, org_admin, manager, member
Deliver:
1. Full directory tree (client/, server/, shared/ packages)
2. Module boundary decisions with one-sentence reasoning for each
3. Shared TypeScript types strategy (where they live, how they are imported)
4. .env.example with every required variable and a comment for each
5. The top 3 architectural trade-offs you considered and why you chose this pattern over the alternatives
Why it works: Asking for trade-offs forces the AI to justify choices rather than dump a tutorial structure. You get reasoning you can defend in a team architecture review.
2. MongoDB Schema Design with Indexing Strategy
Schema design determines query performance at scale. Get it right before you have 10 million documents to migrate.
You are a MongoDB expert who has designed schemas for applications with 50M+ documents and 10K+ requests per second.
Design Mongoose 8 TypeScript schemas for a project management app: Organization, User, Project, Task, Comment.
Requirements:
- Tenant isolation: tenantId indexed on every document
- Soft deletes: isDeleted (boolean) + deletedAt (Date) on all entities
- Audit trail: createdBy, updatedBy (ObjectId refs), createdAt, updatedAt (timestamps)
- Justify every reference vs embed decision with the query pattern that drove it
- Compound indexes for these access patterns:
* All tasks for a project sorted by dueDate (most frequent query)
* Overdue tasks for an organization filtered by assignee
* Full-text search on task title and description
* User activity feed (tasks created or updated in last 7 days)
- Virtuals: User.fullName, Task.isOverdue, Task.completionPercentage
Output: TypeScript Mongoose schemas, index definitions using index() chaining, and a two-sentence justification for each reference vs embed decision.
Why it works: Specifying exact access patterns forces index design around your real query load — not textbook examples. The justification requirement surfaces reasoning that would otherwise require a senior DBA review.
3. MongoDB Aggregation Pipeline
You are a MongoDB aggregation expert.
Write a Mongoose aggregate() pipeline for a real-time dashboard that computes for a given organizationId:
- Task completion rate per user for the last 30 days (top 10 by completion count)
- Average task completion time in hours per project
- Overdue task count grouped by priority (low / medium / high / critical)
- Week-over-week completion trend for the last 8 weeks (ISO week grouping)
Collection: tasks
Key fields: status (todo/in_progress/done/cancelled), assignedTo (ObjectId), completedAt (Date),
createdAt (Date), dueDate (Date), priority (String), projectId (ObjectId), organizationId (ObjectId)
Provide:
1. The complete aggregate() call with TypeScript result types using generics
2. A comment above each pipeline stage explaining what it does and why
3. Which indexes this pipeline requires to avoid COLLSCAN
4. Estimated memory usage if the pipeline processes 500,000 matching documents
4. Express REST API Controller
Without explicit constraints, AI produces middleware-light routes that fail under production load or fail a security audit.
You are a senior Express.js engineer building production APIs for high-scale SaaS products.
Generate a complete TypeScript Express 5 controller for a Task resource:
Endpoints: GET /tasks (paginated, filterable), GET /tasks/:id, POST /tasks, PUT /tasks/:id, DELETE /tasks/:id (soft delete)
Every endpoint must include:
- Zod validation schemas (request body, query params, route params)
- authenticate middleware: verify JWT, attach req.user with role and tenantId
- authorize middleware factory: requirePermission('tasks:write')
- Tenant-scoped queries: always filter by req.user.tenantId
- Optimistic concurrency on PUT: check version field, return 409 on conflict
- Structured responses: { success, data?, pagination?, message, code? }
- Async error propagation to global error handler (express-async-errors)
- Request ID propagation: read x-request-id header, attach to all log lines
- Response time logging: warn if endpoint exceeds 200ms
Output: router file, controller, Zod schemas, middleware references. TypeScript throughout.
5. Production Express Middleware Stack
You are a Node.js security engineer.
Build a production-grade Express 5 middleware stack in TypeScript. Implement in this exact order with explanation for why order matters:
1. Helmet: strict CSP, HSTS max-age=31536000, X-Frame-Options DENY
2. CORS: allowlist from CORS_ORIGINS env var (comma-separated), credentials: true
3. Rate limiting: 100 req/min per IP, Redis-backed (ioredis), return 429 with Retry-After header
4. Request ID: generate UUID v4, attach to req.id and set X-Request-ID response header
5. Structured logging: pino with JSON format, include request ID, method, path, status, duration
6. Body parser: JSON with 10kb size limit, reject oversized bodies with 413
7. Compression: gzip/brotli based on Accept-Encoding, threshold 1KB
8. JWT authentication: attach to specific route groups (not global), skip /health and /auth/login
9. Global error handler: log with request ID, return structured JSON, never leak stack trace in production
Output: app.ts setup file with all middleware. Add a comment on each line explaining the security or performance reason for its position in the stack.
Why it works: The "explain why order matters" constraint documents your security reasoning inline — the kind of documentation that normally only appears after an incident post-mortem.
6. JWT Authentication with Refresh Token Rotation
You are a security engineer specializing in stateless authentication for Node.js APIs.
Implement a complete JWT auth system for Express 5:
Access tokens:
- RS256 (asymmetric — private key signs, public key verifies; keys loaded from env)
- 15-minute expiry
- Payload: { sub: userId, role, tenantId, iat, exp }
Refresh tokens:
- Stored in Redis with key: refresh:{userId}:{tokenFamily}
- 7-day expiry, delivered via httpOnly + Secure + SameSite=Strict cookie
- Token family tracking: each refresh generates new family ID
- Reuse detection: if a used token is presented again, invalidate the entire family, log a security event
Endpoints:
- POST /auth/login: bcrypt compare (timing-safe), issue both tokens
- POST /auth/refresh: validate Redis entry, rotate token, issue new pair
- POST /auth/logout: delete Redis entry, clear cookie
- Rate limit: 5 auth attempts per 15 minutes per IP
Output: TypeScript auth router, JWT utilities, Redis token service, and auth middleware. Add a security comment explaining each design decision.
Why it works: Token family tracking and reuse detection prevent refresh token theft attacks that most auth implementations miss. Baking them into the prompt ensures you get them from the start, not after a breach.
7. Role-Based Access Control (RBAC) Middleware
You are an authorization systems architect.
Build a dynamic RBAC middleware system for Express with:
- Roles: super_admin, org_admin, manager, member, viewer
- Permission matrix: tasks:read, tasks:write, tasks:delete, projects:manage, org:manage, billing:manage
- Permission inheritance: super_admin inherits all; org_admin inherits manager's permissions; viewer is read-only
- Multi-tenant scoping: a user can be org_admin in Organization A but member in Organization B
- Middleware factory: requirePermission('tasks:write') — returns Express middleware
- Permission check utility: hasPermission(user, resource, action, tenantId): boolean
- Redis caching for permission lookups: TTL 5 minutes, auto-invalidate on role change
- Audit logging: log every permission denial with user ID, resource, action, tenantId, timestamp
TypeScript. Output: permission matrix object, middleware factory, Redis cache layer, and 5 usage examples showing different permission scenarios.
8. React Data Table with Virtual Scrolling
You are a senior React engineer specializing in performant, accessible UI components.
Build a DataTable<T extends Record<string, unknown>> React component with TypeScript generics for a MERN admin panel:
Required features:
- Virtual scrolling for 50,000+ rows using @tanstack/react-virtual
- Multi-column sorting with direction indicators (client-side and server-side modes via prop)
- Row selection: checkbox per row, shift+click range, select-all on current page
- Column resizing via drag handle
- Per-column filters (text, date range, enum select based on column type)
- Pagination: client-side and server-side modes
- Row action menu via renderRowActions prop (receives row data, returns ReactNode)
- States: loading skeleton (animated), empty state, error state with retry button
- WCAG 2.1 AA: keyboard navigation (arrow keys, Enter to select), ARIA grid role, screen reader announcements on sort/select
TypeScript interfaces required for: ColumnDef<T>, SortState, FilterState, PaginationState, SelectionState.
CSS Modules for styling. Zero external UI library dependencies.
9. Custom React Hook: useFetch with Cache
You are a React hooks architect.
Build a production-ready useFetch<T> hook:
interface UseFetchOptions {
deduplicate?: boolean; // prevent concurrent identical requests (default: true)
ttl?: number; // cache TTL in ms (default: 30000)
retries?: number; // automatic retry count (default: 3)
retryDelay?: number; // base delay for exponential backoff in ms (default: 1000)
onError?: (err: Error) => void;
}
Requirements:
- Request deduplication: same URL + body = single in-flight request (Map-based)
- SWR-style in-memory cache with TTL and stale-while-revalidate behaviour
- AbortController cancellation on component unmount or URL change
- Exponential backoff retry: 1s, 2s, 4s with jitter
- States: { data, loading, error, stale, refetch, mutate }
- mutate(): optimistic update + background revalidation on POST/PUT/DELETE
- TypeScript strict mode: no any types
Include: hook implementation, TypeScript types, and 4 usage examples (GET with pagination, POST with optimistic update, polling with interval, conditional fetch).
10. Zustand State Architecture
You are a React state management expert.
Design a Zustand store architecture for a MERN project management app. Create these stores:
authStore: user object, access token (in memory, never localStorage), auto-refresh logic (intercept 401, call /auth/refresh, retry original request), logout (clear all stores)
projectStore: CRUD operations, optimistic updates with rollback on failure, real-time sync via Socket.io events
taskStore: paginated task lists, active filters, sort state, bulk operations (assign, update status, delete)
uiStore: modal registry (open/close by ID), toast queue (max 5 visible), sidebar collapsed state, theme (light/dark)
Requirements:
- Persist authStore and uiStore to sessionStorage (not localStorage for auth tokens)
- Immer middleware for immutable state updates
- Redux DevTools middleware in development
- Selector hooks to prevent unnecessary re-renders: useTasksByProject(projectId)
- Action naming: verb + noun (fetchTasks, updateTask, clearFilters)
Output: full TypeScript store files, middleware configuration, and 3 selector hook examples.
11. Unit Tests with 100% Branch Coverage
You are a test engineering expert for Node.js MERN applications.
Write comprehensive Jest unit tests for this Express service function:
[PASTE SERVICE FUNCTION CODE HERE]
Cover every branch:
- Happy path for each operation
- Zod validation failures (missing fields, wrong types, business rule violations)
- Unauthorized access (missing JWT, expired JWT, wrong role)
- Tenant boundary violations (accessing another tenant's data)
- MongoDB errors: validation error, duplicate key (11000), connection timeout
- Redis errors: cache miss (handled gracefully), Redis connection failure (graceful degradation)
- Rate limit exceeded
Requirements:
- Mock all external dependencies: Mongoose models, ioredis, nodemailer, external APIs
- jest.spyOn for side effects: email sends, audit log writes, Socket.io emissions
- Assert on response shape, HTTP status code, and response headers
- AAA pattern: Arrange, Act, Assert with labeled comments
- Factory functions for test data (no hardcoded magic values)
- Target: 100% branch coverage — show coverage report format in a top comment
12. GitHub Actions CI/CD Pipeline
You are a DevOps engineer building CI/CD pipelines for MERN production applications.
Generate a complete GitHub Actions workflow for a MERN monorepo:
lint-and-test job (triggers on all PRs and main push):
- Node 22, pnpm with cache
- TypeScript compile check: tsc --noEmit on both client and server
- ESLint + Prettier check (fail on warnings)
- Server: Jest unit + integration tests, coverage gate 80%, upload to Codecov
- Client: Vitest unit tests + Playwright E2E against local server (docker-compose up)
security job (parallel to lint-and-test):
- npm audit --audit-level=high (fail build on high+ vulnerabilities)
- Trivy container scan on Dockerfile
- CodeQL analysis for JavaScript/TypeScript
docker job (main branch only, after lint-and-test passes):
- Multi-stage build: builder (tsc compile) + production (node:22-alpine, non-root user)
- Push to AWS ECR: tag with git SHA and 'latest'
- Image size check: fail if production image exceeds 200MB
deploy job (after docker job):
- Backend: AWS ECS rolling update via AWS CLI (zero-downtime)
- Frontend: Vercel CLI deploy
- Smoke test: curl /api/health, assert HTTP 200 and { status: 'ok' }
- Slack notification on success or failure with deploy URL
Include secrets management pattern and required GitHub repository secrets list.
13. MongoDB Query Performance Optimization
You are a MongoDB performance engineer who has optimized queries on collections with 100M+ documents.
This aggregation pipeline runs in 4,200ms on a collection with 8M documents. Here is the current pipeline and indexes:
[PASTE PIPELINE + INDEXES HERE]
Diagnose and fix:
1. Run an EXPLAIN — identify whether it is COLLSCAN or IXSCAN and why
2. Recommend the optimal compound index (specify field order and direction with reasoning)
3. Rewrite any pipeline stages that block before the $match (push $match as early as possible)
4. Identify stages that can use $lookup with pipeline to filter before joining
5. Assess whether this result should be pre-computed in a separate summary collection (materialized view pattern)
6. Estimate query time after optimization
Context: 70% read workload, this query runs 80,000 times per day during business hours.
14. Docker Multi-Stage Build for Node.js API
You are a DevOps engineer building production Docker images for Node.js APIs.
Write an optimized multi-stage Dockerfile for an Express 5 + TypeScript API:
Stage 1 (deps): install production + dev dependencies
Stage 2 (build): run tsc, output to dist/
Stage 3 (production):
- Base: node:22-alpine (not full Debian)
- Copy: dist/, node_modules (production only, re-installed from package.json)
- Non-root user: create 'appuser' (UID 1001), chown app directory, USER appuser
- EXPOSE the port from PORT env variable
- Health check: GET /health every 30s, 3 retries, 10s start period
- CMD: ["node", "dist/server.js"]
- No secrets, no .env files, no source code in final stage
After the Dockerfile:
1. A .dockerignore file
2. A docker-compose.yml for local development with MongoDB, Redis, and the API (volume mounts for hot-reload, depends_on with healthcheck conditions)
3. Three sentences explaining why multi-stage + non-root matters for production security
Good vs Bad MERN Stack Prompts
| Task | ❌ Bad Prompt (generic output) | ✅ Good Prompt (production output) |
|---|---|---|
| MongoDB schema | "Create a user model in MongoDB" | "Create a Mongoose 8 TypeScript User schema with: bcrypt-hashed password (never returned in queries), email unique + indexed, role enum, tenantId indexed, soft delete fields, OAuth provider linking array, and a compound index on [email, tenantId, isDeleted]." |
| Express route | "Build a login endpoint" | "Build POST /auth/login in Express 5 TypeScript: Zod validation, bcrypt timing-safe compare, RS256 JWT (15min), refresh token in Redis + httpOnly SameSite=Strict cookie (7 days), rate limit 5/15min, return 401 on any failure without revealing whether email or password was wrong." |
| React component | "Build a task form" | "Build a CreateTaskForm with React Hook Form + Zod, TypeScript generics, async multi-select user search with 300ms debounce, optimistic UI during submission, localStorage autosave every 30s, and useBlocker warning before navigating away with unsaved changes." |
| Debugging | "Why is my app slow?" | "My GET /api/tasks returns in 1,800ms. Here is the route code: [CODE]. My current Mongoose indexes: [INDEXES]. MongoDB EXPLAIN output: [EXPLAIN]. Identify the root cause, propose the optimal compound index with field order reasoning, and rewrite the query." |
| Testing | "Write tests for my service" | "Write Jest unit tests for this TaskService.create() function: [CODE]. Mock mongoose, ioredis, and nodemailer. Cover happy path, Zod validation failure, duplicate key error (11000), Redis cache miss, and email notification failure. Target 100% branch coverage." |
Generate a custom MERN stack prompt for your exact use case → Try PromptPrepare free
Found this helpful? Share it.