10 Essential Prompts for Node.js and Express: APIs, Middleware & Authentication

Writing Node.js and Express code is rarely about syntax—it’s about architecture, edge cases, and making the right trade-offs under pressure. That’s where AI prompts shine. A well-crafted prompt can turn your LLM into a senior backend engineer that generates production-ready routes, middleware, auth flows, and WebSocket handlers in seconds. But as with any tool, garbage in, garbage out. The difference between a generic boilerplate and a robust API lies in the specificity of your instructions.

In this guide, I’ve curated ten battlefield-tested prompts for Express developers. Each one is designed to solve a real problem: designing a REST API, protecting routes with JWTs, writing error-handling middleware, or adding real-time features with Socket.IO. You’ll also learn how to feed the model the right context so it returns code that actually fits your project.

How to Write Prompts That Actually Work for Node.js

Before we jump into the prompts, let’s break down the anatomy of a great Node.js prompt. A vague prompt like "Create an API" will produce generic output. Instead, you need to include four ingredients:

  1. Role and context: Tell the model it is a senior Node.js developer working on an Express API.
  2. Task description: Specify what to build—routes, middleware, auth, etc.
  3. Constraints: Name your packages (e.g., express, zod, jsonwebtoken, socket.io), database, and coding style.
  4. Acceptance criteria: Define the behavior, error handling, and security requirements.

For example, compare "Write a login route" with "Write an Express route that validates the request body using zod, checks the password with bcrypt, and returns a signed JWT with a 7-day expiration." The second prompt produces code that is nearly production-ready.

Now, let’s get into the ten prompts. They are organized into four categories: REST APIs, middleware, authentication, and WebSockets.

REST API Prompts That Go Beyond CRUD

Prompt 1: Design a Complete REST API with Validation

Act as a senior Node.js developer. Build an Express REST API for a blog platform with the following resources: users, posts, and comments. Use Express 4, MongoDB with Mongoose, and Zod for request validation. The API should have standard CRUD routes, but also include:
- Pagination ?page=1&limit=10
- Sorting ?sortBy=createdAt&order=desc
- Field selection ?fields=title,content
- Proper HTTP status codes (200, 201, 400, 401, 404, 409)
- A centralized error handler that returns JSON in the format { "error": { "code": "...", "message": "..." } }

Generate the complete folder structure, route files, controllers, and schema definitions. Use ES6 modules and an async handler utility.

This prompt is your Swiss Army knife. It gives the model enough constraints to produce a solid foundation, and it forces the output to include real-world concerns like pagination and error formatting. When I use this prompt, I usually follow up with "Now add a search endpoint that uses MongoDB text indexes" to build on the generated base.

Usage example: Save the generated code into a project. Run npm install and confirm that hitting /api/posts?page=2 returns the correct page. If the model used a package you don’t like, simply ask it to "rewrite using Prisma instead of Mongoose."

Prompt 2: Pagination, Filtering, and Sorting Logic

Write a reusable Express middleware that parses query parameters and attaches a req.pagination object with page, limit, skip, sort, and filters. The middleware should:
- Default to page 1 and limit 20
- Cap limit at 100
- Support multiple filters like ?status=published&tags=nodejs
- Return a 400 error for invalid page or sort fields

Provide the complete middleware code and an example of how to use it in a route. Also show how to generate a nextPage and totalPages value in the response.

This prompt is great for keeping your codebase DRY. Instead of copying the same pagination logic into every controller, this middleware handles it all. The key is to ask for both the middleware and a usage example, so you can see how it plugs into your existing routes.

Prompt 3: Centralized Error Handler

Create an Express error-handling middleware that catches any error thrown in async routes without wrapping everything in try/catch. The middleware should:
- Detect known error types (ZodError, Mongoose ValidationError, CastError, JsonWebTokenError)
- Return 400 for validation errors, 401 for invalid tokens, and 500 for internal errors
- Log the stack trace in development and hide it in production
- Support both app.use and express.Router usage

Include a custom AppError class with a statusCode and isOperational flag, and show how to call next(new AppError(404, 'Post not found')) from a route.

Error handling is the most underrated part of Express. This prompt produces the backbone of a robust API. The more detail you give—specific error classes, logging behavior—the more tailored the code will be. After generating, ask the model to "add a global error handler for unhandled promise rejections" to cover the last edge case.

Authentication and Authorization Prompts

Prompt 4: JWT Authentication Flow

Implement a JWT-based authentication flow in Express using jsonwebtoken and bcrypt. The flow should include:
- POST /api/auth/register — hash password, create user, return a signed JWT
- POST /api/auth/login — verify email and password, return JWT and user profile
- GET /api/auth/me — protected route that returns the current user from the token
- POST /api/auth/logout — blacklist the token (use an in-memory Set or Redis)

Use environment variables for JWT_SECRET and JWT_EXPIRES_IN. Create a protect middleware that verifies the Authorization: Bearer <token> header and sets req.user. Provide a complete file-by-file breakdown.

This is the gold standard for an auth prompt. It covers registration, login, protected routes, and logout. To make it even better, specify "add refresh token rotation" as a follow-up.

Usage example: After pasting the prompt, the model will likely output several files. Combine them into an auth/ folder and modify the User.model.js to match your database schema. Don’t forget to set the environment variables in your .env file.

Prompt 5: Role-Based Access Control (RBAC)

Extend the Express auth flow with role-based access control. Create a restrictTo(...roles) middleware that works alongside the protect middleware. The middleware should:
- Accept roles like 'admin', 'editor', 'user'
- Return 403 if the authenticated user’s role is not allowed
- Be chainable: router.post('/posts', protect, restrictTo('admin', 'editor'), createPost)

Assume the user model has a role field. Show an example of using restrictTo in a real route and explain how to seed an admin user.

RBAC is a common requirement for SaaS apps. The secret to a good response is telling the model exactly how to chain the middlewares. This prompt does that. If your user model uses enum values for roles, include them in the prompt to get a perfect match.

Prompt 6: OAuth2 with Passport.js

Build a Google OAuth2 login flow in Express using Passport.js and the passport-google-oauth20 strategy. The flow should:
- Redirect to Google’s consent screen
- Handle the callback and find-or-create a user in MongoDB
- Sign a JWT and redirect to the frontend with a temporary token
- Include a minimal frontend route that exchanges the token

Provide the Passport configuration, the auth routes, and a note on how to set up the Google Cloud console credentials.

This prompt is perfect for apps that need "Login with Google." Because OAuth flows are tricky, the model’s step-by-step configuration is invaluable. Follow it with "Now add a GitHub strategy" to get a multi-provider setup.

WebSocket and Real-Time Prompts

Prompt 7: Socket.IO Authentication Middleware

Create a Socket.IO server integrated with Express that requires JWT authentication. Implement a middleware that verifies the token from a token key in the handshake auth object. On success, attach the user payload to socket.data.user. On failure, emit an auth_error event and disconnect the socket.

Show how to configure the Socket.IO server with CORS and how to use the same protect middleware logic on the client side. Provide both server and client examples.

Real-time features are a different beast. This prompt combines WebSockets with the auth flow you likely already have. The key is to ask for handshake authentication—that’s how production apps secure their sockets.

Prompt 8: Real-Time Notifications with Rooms

Design a real-time notification system using Socket.IO in Express. When a user creates a new post, a notification should be sent to all users who follow that user. Requirements:
- Store follower relationships in MongoDB
- On post creation, emit a new_post event to each follower’s personal room
- Use socket.join(userId) when a user connects
- Provide a REST endpoint GET /api/notifications to fetch missed notifications after reconnect

Explain how to scale this horizontally with Redis as a Socket.IO adapter. Give a high-level architecture and example code.

This prompt is excellent for learning the "push to room" pattern. The request for Redis shows the model you care about production scaling. The generated code will include Redis pub/sub, making your real-time infrastructure ready for multiple server instances.

Advanced Workflow Prompts

Prompt 9: Build a Full App from a Specification

You are a principal Node.js architect. Build a complete Express app for a "Task Manager" with user registration, login, and task CRUD. Use the following stack: Express 4 + MongoDB + Mongoose + Zod + JWT + Jest (for a few unit tests). The app must:
- Follow the MVC pattern with a services layer alongside controllers
- Have index.js (entry point), app.js (Express setup), config/ (DB and env config), routes/, controllers/, services/, models/, middlewares/, and tests/
- Include a Postman collection or OpenAPI 3.0 spec

Generate the entire project. Include package.json with dependency versions and a short README explaining how to run the tests.

This is the "mega prompt" that can scaffold an entire project. Use it when starting a new MVP. The model will generate dozens of files, but don’t paste them all at once. Ask for a file tree first, then request each file one by one. This keeps the output manageable and lets you review the architecture.

Prompt 10: Prompt Workflow: Convert an API Description to Production Code

Here is the API description for a simple e-commerce backend:

  • POST /api/orders — create an order with items and shipping address
  • GET /api/orders/:id — fetch an order
  • PATCH /api/orders/:id/status — update order status
  • DELETE /api/orders/:id — cancel an order

Implement these endpoints using Express and a transactional database schema. Use Prisma as the ORM. For each endpoint, include:
- Zod validation schemas
- Service classes that handle business logic
- Error mapping (e.g., "order not found" → 404)
- Proper HTTP verbs and status codes

Also include a seed script to create sample products. Provide the Prisma schema definitions.

This prompt works brilliantly because it turns a simple description into a production-ready implementation. The power is in the details: transactional schema, service classes, and error mapping. Whenever you have a REST API spec, wrap it in this prompt template.

Best Practices for Prompt-Driven Node.js Development

Using prompts effectively is a skill. Here are a few rules I’ve learned from months of pairing with LLMs on Express projects:

Practice Why It Matters
Always specify your exact stack (Express 4 vs 5, Mongo vs Postgres) Different versions require different code; avoid hallucinated APIs
Request a file tree before asking for whole files Keeps the project organized and prevents a wall of code
Use follow-up prompts to iterate ("Now add refresh tokens") Breaks the work into reviewable chunks
Ask the model to explain trade-offs You learn why it chose pattern X over Y
Run npm install and test immediately Catch integration issues while your context is fresh

The more you treat the model as a junior developer who needs clear specifications, the better the results. But always review the code—AI can be confident and wrong. Use unit tests and your own linting rules as guardrails.

Real-World Example: Combining the Prompts

Let’s say you’re building a SaaS with a public API and real-time updates. Here’s a workflow using the prompts above:

  1. Start with Prompt 1 to scaffold the REST API and folder structure.
  2. Apply Prompt 3 to add centralized error handling.
  3. Add Prompt 4 and Prompt 5 for JWT auth and RBAC.
  4. Integrate Prompt 8 for real-time notifications.
  5. Use Prompt 10 to refine the endpoints with Prisma.

Each prompt builds on the previous one. This is the real superpower of prompt-based development: you can combine modular prompts to create a full system in an afternoon, then spend the rest of your week refining business logic instead of writing boilerplate.

If you need a starting point, copy the prompt that matches your current task and customize the stack. The key is to give the model explicit constraints. And if the output isn’t perfect on the first try, don’t rewrite everything—ask the model to "fix the error handler" or "make the routes more DRY."

Now it’s your turn. Which of these prompts will you try first in your next Express project? I’d love to hear about your favorite prompt for Node.js in the comments below. Happy coding — and let the prompts do the heavy lifting.

← All posts

Comments