Production-ready Express.js API patterns with middleware, validation, and error handling
# Node.js Express API Patterns for Google Antigravity
Build robust APIs with Express.js using Google Antigravity's Gemini 3 engine. This guide covers middleware patterns, request validation, error handling, and API organization.
## Express App Setup
```typescript
// src/app.ts
import express, { Express, Request, Response, NextFunction } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import { rateLimit } from 'express-rate-limit';
import { apiRouter } from './routes';
import { errorHandler, notFoundHandler } from './middleware/error';
import { requestId } from './middleware/requestId';
export function createApp(): Express {
const app = express();
// Security middleware
app.use(helmet());
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
credentials: true,
}));
// Rate limiting
app.use(rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later' },
}));
// Request processing
app.use(compression());
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true }));
// Logging and tracing
app.use(requestId);
app.use(morgan('combined'));
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});
// API routes
app.use('/api/v1', apiRouter);
// Error handling
app.use(notFoundHandler);
app.use(errorHandler);
return app;
}
// src/server.ts
import { createApp } from './app';
import { connectDatabase } from './database';
async function start() {
const app = createApp();
const port = process.env.PORT || 3000;
await connectDatabase();
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
}
start().catch(console.error);
```
## Router Organization
```typescript
// src/routes/index.ts
import { Router } from 'express';
import { usersRouter } from './users';
import { productsRouter } from './products';
import { ordersRouter } from './orders';
import { authRouter } from './auth';
import { authenticate } from '../middleware/auth';
export const apiRouter = Router();
// Public routes
apiRouter.use('/auth', authRouter);
// Protected routes
apiRouter.use('/users', authenticate, usersRouter);
apiRouter.use('/products', productsRouter);
apiRouter.use('/orders', authenticate, ordersRouter);
// src/routes/users.ts
import { Router } from 'express';
import { UsersController } from '../controllers/users';
import { validate } from '../middleware/validate';
import { createUserSchema, updateUserSchema } from '../schemas/user';
import { authorize } from '../middleware/auth';
export const usersRouter = Router();
const controller = new UsersController();
usersRouter.get('/', authorize('admin'), controller.list);
usersRouter.get('/:id', controller.getById);
usersRouter.post('/', authorize('admin'), validate(createUserSchema), controller.create);
usersRouter.put('/:id', validate(updateUserSchema), controller.update);
usersRouter.delete('/:id', authorize('admin'), controller.delete);
```
## Controller Pattern
```typescript
// src/controllers/users.ts
import { Request, Response, NextFunction } from 'express';
import { UserService } from '../services/user';
import { AppError } from '../utils/errors';
export class UsersController {
private userService: UserService;
constructor() {
this.userService = new UserService();
}
list = async (req: Request, res: Response, next: NextFunction) => {
try {
const { page = 1, limit = 20, search } = req.query;
const result = await this.userService.findAll({
page: Number(page),
limit: Number(limit),
search: search as string,
});
res.json({
data: result.users,
pagination: {
page: result.page,
limit: result.limit,
total: result.total,
pages: result.pages,
},
});
} catch (error) {
next(error);
}
};
getById = async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
const user = await this.userService.findById(id);
if (!user) {
throw new AppError('User not found', 404);
}
res.json({ data: user });
} catch (error) {
next(error);
}
};
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const user = await this.userService.create(req.body);
res.status(201).json({ data: user });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
// Check ownership or admin
if (req.user?.id !== id && req.user?.role !== 'admin') {
throw new AppError('Not authorized', 403);
}
const user = await this.userService.update(id, req.body);
res.json({ data: user });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
await this.userService.delete(id);
res.status(204).send();
} catch (error) {
next(error);
}
};
}
```
## Middleware Implementation
```typescript
// src/middleware/auth.ts
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { AppError } from '../utils/errors';
interface JwtPayload {
userId: string;
email: string;
role: string;
}
declare global {
namespace Express {
interface Request {
user?: JwtPayload;
}
}
}
export function authenticate(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return next(new AppError('Missing authorization header', 401));
}
const token = authHeader.substring(7);
try {
const payload = jwt.verify(
token,
process.env.JWT_SECRET!
) as JwtPayload;
req.user = payload;
next();
} catch (error) {
next(new AppError('Invalid or expired token', 401));
}
}
export function authorize(...roles: string[]) {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return next(new AppError('Not authenticated', 401));
}
if (!roles.includes(req.user.role)) {
return next(new AppError('Not authorized', 403));
}
next();
};
}
// src/middleware/validate.ts
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { AppError } from '../utils/errors';
export function validate(schema: z.ZodType) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse({
body: req.body,
query: req.query,
params: req.params,
});
if (!result.success) {
const errors = result.error.errors.map((e) => ({
path: e.path.join('.'),
message: e.message,
}));
return next(new AppError('Validation failed', 400, errors));
}
req.body = result.data.body;
next();
};
}
// src/middleware/error.ts
import { Request, Response, NextFunction } from 'express';
import { AppError } from '../utils/errors';
export function notFoundHandler(req: Request, res: Response) {
res.status(404).json({
error: 'Not Found',
message: `Cannot ${req.method} ${req.path}`,
});
}
export function errorHandler(
err: Error,
req: Request,
res: Response,
next: NextFunction
) {
console.error('Error:', err);
if (err instanceof AppError) {
return res.status(err.statusCode).json({
error: err.message,
...(err.details && { details: err.details }),
});
}
// Don't leak error details in production
const message = process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message;
res.status(500).json({ error: message });
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Express patterns: Use middleware for cross-cutting concerns. Implement centralized error handling. Validate requests with Zod schemas. Organize routes by resource domain. Use async/await with proper error handling.This Node.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their node.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Node.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.