Node.js Express
Category: backend October 19, 2025
Agent instructions for Express.js backend API development
nodejsexpressbackendapitypescript
# Express.js API Development
## Setup Commands
- Install dependencies: `npm install` or `pnpm install`
- Start dev server: `npm run dev` (with nodemon)
- Build: `npm run build` (TypeScript compilation)
- Start production: `npm start`
- Run tests: `npm test`
## Code Style
- Use TypeScript for type safety
- Use async/await instead of callbacks
- Follow REST API conventions
- Use middleware for cross-cutting concerns
- Keep route handlers thin - delegate to service layer
## Project Structure
src/ ├── server.ts # App entry point ├── routes/ # Route definitions ├── controllers/ # Request handlers ├── services/ # Business logic ├── middleware/ # Custom middleware ├── models/ # Data models ├── utils/ # Helper functions └── types/ # TypeScript type definitions
## Routing Patterns
- Use Express Router for modular routes
- Group related endpoints under versioned prefixes (`/api/v1`)
- Use route parameters for resource IDs: `/users/:id`
- Implement proper HTTP status codes
## Middleware Usage
- Request logging (morgan or winston)
- Error handling middleware (always last)
- Authentication middleware (JWT verification)
- Request validation (express-validator or Joi)
- CORS configuration for cross-origin requests
## Error Handling
- Create custom error classes extending Error
- Use centralized error handling middleware
- Always catch async errors with try-catch or express-async-errors
- Return consistent error response format
- Log errors appropriately based on severity
## Database Integration
- Use Prisma, TypeORM, or Sequelize for SQL databases
- Use Mongoose for MongoDB
- Implement connection pooling
- Close connections gracefully on shutdown
## Testing Instructions
- Unit tests with Jest or Vitest
- Integration tests with supertest
- Mock external services
- Test all API endpoints
- Run `npm test` before committing
## Security Best Practices
- Use helmet middleware for security headers
- Implement rate limiting (express-rate-limit)
- Validate and sanitize all inputs
- Use environment variables for secrets
- Enable CORS only for trusted origins
## Environment Variables
- Use `.env` file for local development
- Never commit `.env` to version control
- Document all required env vars in `.env.example`
- Use dotenv package to load environment variables
## PR Instructions
- Run linter: `npm run lint`
- Run tests: `npm test`
- Ensure TypeScript compiles: `npm run build`
- Update API documentation if endpoints changed
- Check for security vulnerabilities: `npm audit`