20 Prompts for Node.js and Express: API, Middleware, and Authorization

Introduction

Node.js has long been the backbone of server-side JavaScript, and Express remains the most popular web framework for building APIs. However, with the rise of AI-assisted development, many developers now rely on carefully crafted prompts to generate boilerplate, debug middleware, or design secure authorization flows. This article compiles 20 battle-tested prompts that I use daily in my own workflow for Node.js and Express projects. Each prompt comes with a real usage example, so you can copy-paste them directly into your AI assistant—whether it’s ChatGPT, Claude, or a local LLM.

Why Prompts Matter for Node.js Developers

When you’re building REST APIs, authentication systems, or WebSocket handlers, repetitive patterns emerge. Instead of writing every CRUD endpoint from scratch, you can generate them with a single prompt—saving hours and reducing human error. According to the 2024 Stack Overflow Developer Survey, 44% of developers now use AI tools for code generation, and Node.js developers are among the most active adopters. Prompts are not just shortcuts; they are structured templates that encode best practices like error handling, input validation, and consistent logging.

Prompts for REST API Endpoints

1. Generate a Full CRUD Router

Prompt: "Create an Express router for a 'Product' model with MongoDB (Mongoose) including validation, error handling, and pagination."

Usage example: I use this when starting a new microservice. The AI returns a router file with GET /products, POST /products, PUT /products/:id, DELETE /products/:id, and pagination via query params. I then customize the schema.

2. Add Input Validation with Joi

Prompt: "Write a validation middleware using Joi for a user registration endpoint. Require email, password (min 8 chars, one uppercase), and name. Return a 400 error with details if validation fails."

Usage example: Pasting this into my middleware folder gives me a reusable validate function that I attach to routes.

3. Implement Rate Limiting

Prompt: "Add rate limiting to an Express app using express-rate-limit. 100 requests per 15 minutes per IP. Return a 429 error with a 'Retry-After' header."

Usage example: I wrap this around my API routes to prevent abuse during load testing.

4. Generate API Documentation with Swagger

Prompt: "Write a Swagger (OpenAPI 3.0) YAML snippet for a POST /users endpoint that accepts JSON body with name and email, returns 201 with user object, and 400 for bad request."

Usage example: After generating the snippet, I integrate it with swagger-jsdoc and swagger-ui-express.

Prompts for Middleware

5. Error Handling Middleware

Prompt: "Create a global error handling middleware for Express. It should catch all errors, log them with winston, and return a JSON response with status code and message. Handle both custom AppError and generic errors."

Usage example: I place this middleware after all routes. It centralizes error logging, which is critical for debugging in production.

6. CORS Middleware Configuration

Prompt: "Write CORS middleware for Express that allows requests only from 'https://example.com' and 'https://app.example.com', supports credentials, and allows specific headers like Authorization and Content-Type."

Usage example: I use this to secure my API when the frontend is hosted on a different domain.

7. Logging Middleware with Morgan and Winston

Prompt: "Combine morgan for HTTP request logging and winston for structured logging in an Express app. Log to console and a file, with timestamps and request IDs."

Usage example: This prompt generates a logger.js file that I import in my app.js. It’s essential for auditing API calls.

8. Request ID Middleware

Prompt: "Write a middleware that generates a unique request ID (UUID v4) for each incoming HTTP request, attaches it to req.id, and adds it to the response header 'X-Request-Id'."

Usage example: I use this to trace requests across microservices. It’s a standard pattern in distributed systems.

Prompts for Authentication and Authorization

9. JWT Authentication Middleware

Prompt: "Create an Express middleware that verifies a JWT token from the Authorization header (Bearer scheme). Use jsonwebtoken library. If token is invalid or expired, return 401. Attach decoded payload to req.user."

Usage example: I protect all private routes with this middleware. It’s the foundation of my auth system.

10. Role-Based Access Control (RBAC)

Prompt: "Write a middleware function 'authorize' that takes allowed roles as arguments (e.g., 'admin', 'manager'). Check req.user.role against allowed roles. Return 403 if not authorized."

Usage example: I chain this after JWT middleware: router.delete('/users/:id', authenticate, authorize('admin'), deleteUser).

11. Refresh Token Flow

Prompt: "Implement a refresh token endpoint for Express. Use httpOnly cookies for refresh token. Validate refresh token from database, generate new access token and new refresh token, invalidate old refresh token."

Usage example: This is a full endpoint that I add to my auth routes. It prevents users from logging in repeatedly.

12. Password Hashing with bcrypt

Prompt: "Write a utility function that hashes a password using bcrypt with salt rounds 12, and another function that compares a plain text password with a hash."

Usage example: I use these in my user registration and login endpoints. Never store plain-text passwords.

Prompts for WebSocket Integration

13. WebSocket Server with Socket.IO and Express

Prompt: "Set up a Socket.IO server alongside an Express HTTP server. Include CORS configuration, connection logging, and a simple 'message' event handler that echoes back."

Usage example: I use this for real-time features like chat or notifications. The prompt generates both server and client boilerplate.

14. Authenticate WebSocket Connections with JWT

Prompt: "Write a Socket.IO middleware that verifies JWT token passed in the handshake query parameter 'token'. Disconnect if invalid. Attach decoded user to socket.user."

Usage example: This ensures only authenticated users can connect to WebSocket namespaces.

15. Room-Based Broadcasting

Prompt: "Create a Socket.IO event handler that allows a client to join a room (e.g., 'room:join'), send messages to all clients in that room (e.g., 'room:message'), and leave (e.g., 'room:leave'). Include error handling."

Usage example: I use this for multi-user collaboration features like shared whiteboards.

Prompts for Database and ORM

16. Mongoose Schema with Virtuals and Indexes

Prompt: "Define a Mongoose schema for 'Order' with fields: userId (ref to User), items (array of subdocuments with productId and quantity), totalPrice, status (enum: pending, shipped, delivered). Add a virtual for formatted date and a compound index on userId and status."

Usage example: This generates a complete schema file that I can drop into my models folder.

17. Aggregation Pipeline for Reports

Prompt: "Write a Mongoose aggregation pipeline that groups orders by status, calculates total revenue per status, and sorts by revenue descending. Return the result as JSON."

Usage example: I use this in an admin dashboard to generate real-time sales reports.

18. Prisma Schema and Query Example

Prompt: "Generate a Prisma schema for a blog with User, Post, and Comment models. Include relations: User has many Posts, Post has many Comments. Then write a Prisma query to fetch all posts with their author and comment count."

Usage example: I use this when switching from Mongoose to Prisma for type safety. The prompt gives me the complete schema and example query.

Prompts for Testing and Debugging

19. Unit Tests with Jest for Express Controller

Prompt: "Write a Jest test suite for a user registration controller. Mock the User model and bcrypt. Test successful registration (201), duplicate email (409), and missing fields (400). Use describe and it blocks."

Usage example: I paste this into my tests folder and run npm test. It catches regression bugs early.

20. Load Test Script with Artillery

Prompt: "Create an Artillery YAML script that simulates 50 concurrent users hitting a GET /api/users endpoint over 60 seconds. Use a random user ID from a CSV file. Report latency percentiles."

Usage example: I run this before deploying to production to ensure my API can handle expected traffic.

Summary and Best Practices

Prompts are only as good as the context you provide. Always include the library names, expected behavior, and edge cases. For example, specifying "return a 400 error with validation details" ensures the AI generates proper error handling, not just a console.log.

Category Number of Prompts Key Libraries Used
REST API 4 Mongoose, Joi, express-rate-limit, swagger-jsdoc
Middleware 4 winston, morgan, uuid
Auth 4 jsonwebtoken, bcrypt
WebSocket 3 socket.io
Database 3 Mongoose, Prisma
Testing 2 Jest, Artillery

Another critical practice is to keep prompts version-controlled. Store them in a .prompts folder alongside your code. When you upgrade a library (e.g., from Socket.IO v3 to v4), update the prompt and regenerate affected files.

Conclusion

These 20 prompts cover the most common tasks in Node.js and Express development: API endpoints, middleware, authentication, WebSockets, database operations, and testing. By using them, I’ve cut my initial scaffolding time by roughly 60%—from two hours to under 45 minutes for a typical REST API. The key is to treat prompts as living documentation. As your project evolves, refine the prompts to reflect new patterns. For example, if you start using TypeScript, add "Use TypeScript with interfaces" to each prompt.

If you’re working with external services like Telegram or Salesforce, ASI Biont supports connecting to these platforms via API—learn more at asibiont.com/courses. The same prompt-based approach can be extended to generate integration code for those APIs.

Start building your own prompt library today. Copy the ones above, adapt them to your stack, and watch your productivity soar.

← All posts

Comments