10 Prompts for Node.js and Express: API, Middleware, Authentication

Introduction

Generating a Node.js/Express app from scratch usually means writing the same boilerplate: routes, middleware, error handling, and security headers. AI coding assistants like ChatGPT, GitHub Copilot, or Claude can do this for you — but only if you know the right prompts. This collection gives you 10 battle-tested prompts that cover REST APIs, authentication, WebSockets, security, performance, and testing. Use them to save hours of work and keep your code aligned with official Express and Node.js best practices.

All prompts are built around the official Express documentation and Node.js guides. Always review generated code and adapt it to your project’s architecture.

1. Generate a Production-Ready REST API Skeleton

What it does: Creates a complete Express project structure (controllers, routes, services, middlewares) with validation, async error handling, and environment-based configuration.

The prompt:

Create a modular Express.js REST API skeleton in the folder structure below:
- `/config` for environment variables
- `/controllers` for request handlers
- `/middlewares` for custom middleware
- `/routes` for route definitions
- `/utils` for helpers
Use Joi for body validation, implement a global error handler, wrap all async handlers with a `catchAsync` utility. Include a sample resource called `item` with CRUD routes.

Example of use: Paste this into an AI assistant, then provide fields for your resource (e.g., title, price). You’ll get a well-organized codebase with one working endpoint. Test it with a GET /api/items request.

Pro tip: Ask the AI to also scaffold a GET /api/health endpoint for load balancer checks and a .env.example file with DB credentials.

2. Create Reusable Custom Middleware for Logging and Error Handling

What it does: Gives you two pieces of middleware every Express app needs: a request logger and a centralized error handler.

The prompt:

Write Express middleware:
1. `logger.js` — logs the HTTP method, URL, status code, and response time (in ms).
2. `errorHandler.js` — a 4-argument error middleware that returns `{ success: false, message }` in JSON, logs the stack in development, and hides it in production.
Use `express-async-errors` so that errors from async routers are passed to the error handler automatically.

Example of use: With this prompt, you get a clean server.js that already uses app.use(logger) and app.use(errorHandler). It eliminates the repetitive try/catch blocks.

Pro tip: Reference the official Express error-handling guide to make sure your handler calls next(error) in all code paths.

3. Implement JWT Authentication with Refresh Tokens

What it does: Builds a secure token-based auth flow with access and refresh tokens, HTTP-only cookies, and bcrypt password hashing.

The prompt:

Design an Express authentication module for a typical web app:
- `POST /auth/signup` — create a user, hash password with bcrypt.
- `POST /auth/login` — verify password, return an access token (JWT) in an HTTP-only cookie, and store a refresh token in a separate cookie.
- `POST /auth/refresh` — check refresh token, issue a new access token.
- `POST /auth/logout` — clear cookies.
Use `access` token TTL = 15 minutes, `refresh` token TTL = 7 days. Include a sample `auth` middleware that verifies the JWT and sets `req.user`.

Example of use: You’ll get a full controller and route file that you can plug into app.js. Test signup with curl; verify cookies are set.

Pro tip: Always add app.set('trust proxy', 1) behind an HTTPS proxy and use sameSite: 'strict' on cookies to reduce CSRF risk.

4. Add Role-Based Access Control (RBAC) Middleware

What it does: Enables you to protect routes for specific user roles like admin or moderator.

The prompt:

Create an Express middleware called `authorize(...roles)` that works with the JWT payload. The payload has a user object: `{ id, role }`. If the current user’s role is not in the allowed roles array, return a 403 with `{ error: 'Insufficient permissions' }`. Write a usage example for a route that only admins can access.

Example of use: Place authorize('admin') on a DELETE /users/:id route. A non-admin user will receive 403.

Pro tip: Combine it with an authenticate middleware that checks JWT expiry. Keep role checks as a separate concern so they are easy to test.

5. Set Up WebSockets with Socket.IO and Express

What it does: Adds real-time communication to your Express server using Socket.IO, including JWT authentication on handshake and room-based messaging.

The prompt:

Integrate Socket.IO with an existing Express server. On connection, verify the JWT token from the handshake auth object. Create a `chat:message` event that emits to a room specified in the event payload. Save messages to an in-memory array and broadcast a `chat:history` event to a new room member. Show the server setup in `server.js` and a minimal client snippet using `io()`.

Example of use: You’ll have a working chat server where clients join a room, receive message history, and broadcast to other clients.

Pro tip: Use Redis as a Socket.IO adapter when running on multiple instances — otherwise messages won’t sync. The Socket.IO documentation covers this in detail.

6. Generate OpenAPI/Swagger Documentation Automatically

What it does: Produces interactive API documentation at /api-docs from JSDoc or comments.

The prompt:

Add OpenAPI 3.0 documentation to an Express API using `swagger-jsdoc` and `swagger-ui-express`. Write a base swagger definition with server URL `http://localhost:3000`, and add JSDoc annotations for a `GET /items` endpoint that returns an array of objects. Mount UI at `/api-docs`.

Example of use: After running, visiting http://localhost:3000/api-docs shows a Swagger UI page that allows testing endpoint calls directly from the browser.

Pro tip: Keep annotations in the route file next to the handler — it’s much easier to maintain than a separate spec file.

7. Harden Your Express App with Security Middleware

What it does: Applies standard security headers, request rate limiting, and sanitized input.

The prompt:

Write a `security.js` file that exports a function applying the following to an Express app:
- Helmet with default settings
- CORS enabled only for specific origins (use `CORS_ORIGIN` env)
- `express-rate-limit` with 100 requests per 15 minutes per IP
- `express-validator` to sanitize common input (e.g., trim and escape body fields)
Return an Express app that uses these.

Example of use: This prompt gives you a snippet with the proper app.use() order, making your app compliant with basic OWASP security recommendations.

Pro tip: When behind a proxy, set app.set('trust proxy', 'loopback') so the rate limiter uses the real client IP. Refer to the Express security best practices.

8. Integrate PostgreSQL with Prisma and Express

What it does: Sets up a typed database client with Prisma, including schema migration and CRUD routes.

The prompt:

Create a Prisma schema for a blog app: `User` (email, name, role), `Post` (title, content, authorId), and `Comment` (text, postId, authorId). Add relations and indexes. Then write Express routes for `GET /posts` that includes the author, and `POST /posts` that creates a post. Use `@prisma/client`. Include the installation and `prisma migrate` commands.

Example of use: With a generated client, you get a fully functional SQL API in minutes. The prompt also reminds you to set DATABASE_URL in .env.

Pro tip: Use prisma.$transaction when creating posts with multiple comments, and enable query logging in development to debug N+1 queries.

9. Write Unit and Integration Tests with Jest and Supertest

What it does: Generates a test harness for your API, with mocks for database calls.

The prompt:

Create a test suite for a simple Express API using Jest and Supertest. For the `POST /users` endpoint, mock the database with `jest-mock-extended`. Write:
- a unit test for the `validateUser` middleware (valid and invalid data)
- an integration test that starts the app (using `app` exported from `app.js`) and verifies the response code and body
- a test for the 404 handler
Include `npm test` scripts in `package.json`.

Example of use: Running npm test will show all passing tests, covering the happy path and error cases.

Pro tip: Mock process.env with jest.resetModules() before requiring app.js to isolate your tests. The Jest documentation and Supertest are your friends.

10. Optimize Express Performance: Compression, Caching, and Clustering

What it does: Implements performance boosters: gzip compression, static asset caching, and multi-process clustering.

The prompt:

Improve your Express app performance with:
- `compression` middleware for gzip
- `express.static` with `maxAge` of 1 day for `/public`
- Node.js `cluster` module to run one worker per CPU core
- `express.json({ limit: '1mb' })` to restrict request size
Explain why each change matters and provide a `cluster.js` file that starts the worker processes.

Example of use: You can copy cluster.js and use it as a replacement for node server.js. The app will spawn multiple workers and share port 3000.

Pro tip: Always benchmark before and after using tools like autocannon. The cluster module does not boost single-threaded CPU-bound tasks; combine it with caching layers for better gains.

Conclusion

These 10 prompts cover the most repetitive parts of Express development: auth, middleware, docs, security, and testing. With AI, you can turn days of boilerplate into a 10-minute session — but you still need to verify every piece of generated code.

Copy the prompts that fit your current task, run them in your favorite AI assistant, then adapt the output to your project’s conventions. For deeper information, keep the official Node.js and Express docs open in a tab.

If you found this list useful, share it with your team — and don’t forget to bookmark it for your next Node.js project.

← All posts

Comments