Why You Need These Prompts
Building robust Node.js and Express applications requires more than just writing code—it demands clear architectural decisions for API design, middleware management, and authentication. Whether you're creating a RESTful service, implementing JWT-based authorization, or adding real-time WebSocket capabilities, structured prompts can save hours of debugging and design iterations. This collection of 12 copy-paste-ready prompts covers the most common tasks: from generating boilerplate Express servers to securing routes with OAuth2 and integrating Socket.IO. Each prompt includes a specific task, explanation, and code example so you can drop them directly into your workflow.
12 Ready-to-Use Prompts for Node.js and Express
1. Generate an Express Server with Basic Routing
Task: Create a minimal Express server with two routes: GET / and GET /api/status.
Prompt: "Write an Express.js server that listens on port 3000, responds with 'Hello World' on GET /, and returns JSON { status: 'ok' } on GET /api/status."
Example:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.get('/api/status', (req, res) => res.json({ status: 'ok' }));
app.listen(3000, () => console.log('Server running on port 3000'));
2. Implement Custom Middleware for Logging
Task: Log each incoming request’s method and URL.
Prompt: "Create a middleware function that logs the HTTP method and URL of every request to the console, then passes control to the next middleware."
Example:
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
app.use(logger);
3. Build a REST API with CRUD for a Resource
Task: Set up GET, POST, PUT, DELETE endpoints for a "tasks" resource.
Prompt: "Create an Express router with endpoints: GET /tasks (list all tasks), POST /tasks (add new task), PUT /tasks/:id (update a task), DELETE /tasks/:id (delete a task). Use an in-memory array for storage."
Example:
const router = express.Router();
let tasks = [];
router.get('/', (req, res) => res.json(tasks));
router.post('/', (req, res) => {
const task = { id: Date.now(), ...req.body };
tasks.push(task);
res.status(201).json(task);
});
router.put('/:id', (req, res) => {
tasks = tasks.map(t => t.id == req.params.id ? { ...t, ...req.body } : t);
res.json(tasks.find(t => t.id == req.params.id));
});
router.delete('/:id', (req, res) => {
tasks = tasks.filter(t => t.id != req.params.id);
res.status(204).send();
});
app.use('/api/tasks', router);
4. Add JWT Authentication Middleware
Task: Protect routes with JSON Web Tokens.
Prompt: "Write middleware that extracts a Bearer token from the Authorization header, verifies it using jsonwebtoken with a secret key, and attaches decoded user to req.user. Return 401 if missing or invalid."
Example:
const jwt = require('jsonwebtoken');
const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};
app.get('/api/protected', authenticate, (req, res) => res.json({ user: req.user }));
5. Implement Role-Based Access Control (RBAC)
Task: Restrict endpoints based on user roles (e.g., admin, user).
Prompt: "Create a middleware function authorize(roles) that checks if req.user.role is included in the allowed roles array. Return 403 if not authorized."
Example:
const authorize = (...roles) => (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
app.delete('/api/users/:id', authenticate, authorize('admin'), (req, res) => {
// delete user logic
});
6. Set Up WebSocket with Socket.IO
Task: Add real-time bidirectional communication to Express.
Prompt: "Integrate Socket.IO with an Express server. On connection, log the socket ID. Create an event 'message' that receives data and broadcasts it to all connected clients."
Example:
const http = require('http');
const { Server } = require('socket.io');
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('message', (data) => io.emit('message', data));
});
server.listen(3000);
7. Validate Request Body with Joi
Task: Ensure incoming POST data matches a schema.
Prompt: "Use Joi to validate request body for a user registration endpoint: email (valid email), password (min 8 chars, uppercase, number). Return 400 with validation details on failure."
Example:
const Joi = require('joi');
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).pattern(/[A-Z]/).pattern(/[0-9]/).required()
});
app.post('/register', (req, res) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
// proceed with registration
});
8. Handle File Uploads with Multer
Task: Accept single file upload and save to disk.
Prompt: "Configure Multer to store uploaded images in 'uploads/' directory. Create a POST /upload endpoint that accepts a file field named 'avatar' and returns the file path."
Example:
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('avatar'), (req, res) => {
res.json({ path: req.file.path });
});
9. Add Rate Limiting with express-rate-limit
Task: Limit repeated requests to public API endpoints.
Prompt: "Apply rate limiting to all /api/ routes: maximum 100 requests per 15 minutes per IP. Return 429 with 'Too many requests' message when exceeded."
Example:
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests, please try again later.'
});
app.use('/api/', apiLimiter);
10. Integrate CORS for Cross-Origin Requests
Task: Allow requests from a specific frontend origin.
Prompt: "Enable CORS for all origins except a specific domain (e.g., https://myapp.com). Allow methods GET, POST, PUT, DELETE and credentials."
Example:
const cors = require('cors');
const corsOptions = {
origin: 'https://myapp.com',
methods: ['GET','POST','PUT','DELETE'],
credentials: true
};
app.use(cors(corsOptions));
11. Create a Centralized Error Handler
Task: Catch all errors and return consistent JSON responses.
Prompt: "Write a global error-handling middleware that catches errors thrown in routes, logs them, and returns a JSON response with status code (default 500) and error message."
Example:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status
|| 500).json({ error: err.message || 'Internal Server Error' });
});
12. Set Up Environment-Specific Configuration
Task: Use dotenv to manage secrets and config.
Prompt: "Load environment variables from a .env file. Use them to set the port, JWT secret, and database URL. Fall back to defaults if not defined."
Example:
require('dotenv').config();
const port = process.env.PORT || 3000;
const jwtSecret = process.env.JWT_SECRET || 'fallback_secret';
const dbUrl = process.env.DATABASE_URL || 'mongodb://localhost:27017/mydb';
app.listen(port);
Conclusion
These 12 prompts cover the essential building blocks of any Node.js and Express application: from initial server setup to real-time communication, authentication, and error handling. By adapting these code snippets to your project, you can accelerate development and reduce common mistakes. For deeper dives, refer to the official Express documentation (expressjs.com) and Node.js guides. Now, pick the prompt that matches your current task and start coding!
Comments