Why These Prompts Matter for Node.js Developers
If you build backend systems with Node.js and Express, you know the struggle: writing REST endpoints, wiring middleware, handling auth, debugging WebSockets. AI can cut that time by 70%—if you ask the right questions. Based on official Express docs (expressjs.com) and Node.js v22 LTS (nodejs.org/en/learn), here are 10 battle-tested prompts I use daily. Each includes a real problem, the prompt, and the resulting code.
1. Generate a REST API with CRUD
Problem: You need a product API with create, read, update, delete endpoints, plus validation and error handling.
Prompt: "Generate Express.js REST API for a Product resource with MongoDB using Mongoose. Include: GET /products (with pagination, search by name), GET /products/:id, POST /products (validation: name required, price > 0), PUT /products/:id, DELETE /products/:id. Use async error middleware and return proper HTTP status codes."
Result: A complete router with validation using Joi, pagination logic (page, limit), and a 404 handler for missing IDs.
2. Build JWT Authentication Middleware
Problem: Protect routes so only authenticated users can access them.
Prompt: "Write Express middleware that verifies JWT from Authorization header (Bearer token). Use jsonwebtoken library. The middleware should: extract token, verify with secret from env, attach decoded user to req.user, return 401 if missing/invalid. Also create a login route that issues a token with user ID and role."
Result: A reusable authMiddleware.js and a /api/login endpoint that returns { token, user }.
3. Role-Based Access Control (RBAC)
Problem: Some endpoints should be available only to admins.
Prompt: "Extend the JWT middleware to support role-based access. Create a function authorize(...roles) that returns middleware. Example: router.delete('/products/:id', authorize('admin'), deleteProduct). Token payload must include role field. Return 403 if role not allowed."
Result: authorize('admin', 'manager') middleware that checks req.user.role.
4. Centralized Error Handler
Problem: Repetitive try-catch blocks clutter controllers.
Prompt: "Create Express global error handler middleware that: catches all errors, logs to console in development, returns JSON with message and status code. Also create an AppError class with statusCode and isOperational flag. Use it like throw new AppError('Product not found', 404)."
Result: A errorHandler.js and a custom AppError class, reducing boilerplate by 80%.
5. Request Validation with Joi
Problem: Manual field checks are error-prone and verbose.
Prompt: "Write Express middleware that validates request body/params/query using Joi schemas. Example usage: router.post('/products', validate(productSchema), createProduct). The middleware returns 400 with all validation errors if schema fails."
Result: A reusable validate(schema) function that checks req.body against a Joi schema.
6. Logging with Morgan and Winston
Problem: Need structured logs for debugging and monitoring.
Prompt: "Set up logging in Express: use morgan for HTTP request logging (combined format in production, dev in development), and Winston for application logs. Winston should write errors to 'error.log', combined logs to 'combined.log', and console in development."
Result: A logger config that outputs both HTTP-level and app-level logs.
7. Rate Limiting to Prevent Abuse
Problem: API endpoints are vulnerable to brute-force attacks.
Prompt: "Add rate limiting to Express app using express-rate-limit. Create a limiter: 100 requests per 15 minutes per IP. Apply globally except for /health. For auth endpoints, stricter limiter: 5 attempts per 15 minutes."
Result: Two limiters—general and auth-specific—with proper error response (429 Too Many Requests).
8. WebSocket Integration with Socket.IO
Problem: Need real-time updates (e.g., new orders).
Prompt: "Set up Socket.IO on the same HTTP server as Express. Create a namespace '/orders'. On connection, authenticate via token sent in handshake. Emit 'newOrder' event when order is created. Include example of client connecting and listening."
Result: A WebSocket server integrated with Express, with token-based auth and event emission.
9. Database Connection with Retry Logic
Problem: Database might be unavailable at startup.
Prompt: "Write a function to connect to MongoDB with Mongoose that retries 5 times with exponential backoff (starting at 1 second). Use mongoose.connect with connection string from env. Log success and failure. Exit process after max retries."
Result: A resilient connectDB() function that handles transient failures.
10. Environment Configuration Management
Problem: Hardcoded config values are a security risk.
Prompt: "Create a config module that loads .env using dotenv. Export an object with: port, dbUri, jwtSecret, jwtExpiry, nodeEnv. Validate that all required variables exist on startup. Use defaults for optional ones."
Result: A config/index.js that centralizes all environment variables with validation.
Conclusion
These 10 prompts cover the core of any Express backend: API design, security, validation, logging, real-time features, and configuration. Copy them, adapt to your project, and watch your productivity double. For deeper dives, check the official Express error handling guide (expressjs.com/en/guide/error-handling.html) and Node.js best practices (nodejs.org/en/learn/getting-started/nodejs-best-practices). Start with prompt #1 and #2—they'll give you a working API in minutes.
Comments