Cursor Rules for
Express.js

This rule explains Express.js conventions and best practices for Node.js backend development.
Back to rules
Type
Backend
Language(s)
JavaScript
TypeScript
Stats
793 views
107 copies
33 downloads
expressjs.mdc
---
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.

What this rule does

This rule serves as a comprehensive guide for Express.js development, covering essential aspects of building robust Node.js applications. It provides recommendations for:

  • Proper middleware configuration and ordering
  • Code organization and structure
  • Error handling patterns
  • Configuration management
  • Security best practices
  • HTTP response standards

These guidelines help ensure your Express applications are maintainable, secure, and follow established patterns used by experienced developers.

Key Express.js conventions

Middleware organization

The rule emphasizes proper middleware ordering, which is crucial for Express applications:

  1. Body parsers and request preprocessing
  2. Custom application middleware
  3. Route handlers
  4. Error handling middleware

Following this sequence ensures requests are properly processed before reaching route handlers, and any errors are captured by dedicated error middleware.

Route organization

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.

Modern async patterns

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
  }
});

Error handling

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 })
    }
  });
});

Other best practices

The rule also covers:

  • Using environment variables with a configuration module
  • Implementing request validation
  • Adding authentication middleware
  • Using appropriate HTTP status codes

Using Express.js in Cursor

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:

  • Setting up a new Express.js project
  • Refactoring existing Express code to follow best practices
  • Troubleshooting common Express.js issues
  • Implementing standard patterns like authentication or validation

Usage tips

  • Use this rule when generating Express route handlers to ensure they follow proper async/await patterns
  • Refer to it when organizing your middleware to ensure proper ordering
  • Let the rule guide your error handling strategy, especially for API development
  • When requesting code completion for Express-based features, ensure this rule is active for consistent results
  • Combine with other Node.js related rules for more comprehensive guidance when building backend applications
Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later