---
description: This rule explains Express.js conventions and best practices for Node.js backend development.
globs: **/*.js,**/*.ts
alwaysApply: false
---
# Express.js rules
- Use proper middleware order: body parsers, custom middleware, routes, error handlers
- Organize routes using Express Router for modular code structure
- Use async/await with proper error handling and try/catch blocks
- Create a centralized error handler middleware as the last middleware
- Use environment variables for configuration with a config module
- Implement request validation using libraries like express-validator
- Use middleware for authentication and authorization
- Use appropriate HTTP status codes in responses
The Express.js rule provides guidance on best practices and conventions for Node.js backend development using the Express.js framework. This helps maintain consistent, well-structured code following industry standards when building web applications and APIs with Express.
This rule serves as a comprehensive guide for Express.js development, covering essential aspects of building robust Node.js applications. It provides recommendations for:
These guidelines help ensure your Express applications are maintainable, secure, and follow established patterns used by experienced developers.
The rule emphasizes proper middleware ordering, which is crucial for Express applications:
Following this sequence ensures requests are properly processed before reaching route handlers, and any errors are captured by dedicated error middleware.
Using Express Router for modular code structure is recommended:
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// Handle GET /users
});
router.post('/', (req, res) => {
// Handle POST /users
});
module.exports = router;
// app.js
app.use('/users', require('./routes/users'));
This approach keeps related routes together and makes your application more maintainable as it grows.
The rule encourages using async/await with proper error handling:
router.get('/users/:id', async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
res.json(user);
} catch (err) {
next(err); // Pass to error handler
}
});
Creating a centralized error handler as the last middleware helps standardize error responses:
// Last middleware in your app
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: {
message: err.message || 'Internal Server Error',
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
}
});
});
The rule also covers:
The Express.js rule (defined in expressjs.mdc
) is automatically activated when working with JavaScript or TypeScript files in your project, as specified by its glob pattern: **/*.js,**/*.ts
. This means whenever you open or edit any JavaScript or TypeScript file, this rule provides context to Cursor's AI features.
You can also manually invoke it by typing @expressjs
in the AI chat or Cmd-K dialog when you need Express.js-specific guidance.
This rule is particularly helpful when: