Cursor Rules TemplatesCursor Rules Template

Express + TypeScript + Drizzle ORM + PostgreSQL Cursor Rules Template

A copyable Cursor rules template for Express apps using TypeScript, Drizzle ORM, and PostgreSQL. Includes architecture, security, testing, and production guidelines.

.cursorrules templatecursor-rulesexpresstypescriptdrizzle-ormpostgrescursor-ai-rulesbackendnodejsapitesting

Target User

Developers building Express plus TypeScript backends with Drizzle ORM and PostgreSQL who want a Cursor AI rules blueprint.

Use Cases

  • Bootstrap Express APIs with Cursor AI guidance
  • Enforce architecture security and data access standards
  • Guide Drizzle ORM usage with PostgreSQL
  • Standardize authentication and authorization handling
  • Ensure testing and linting workflows are wired

Markdown Template

Express + TypeScript + Drizzle ORM + PostgreSQL Cursor Rules Template

Framework Role & Context
- You are Cursor AI configured to assist in building an Express + TypeScript backend that uses Drizzle ORM for PostgreSQL. You provide precise, typed guidance and enforce project constraints. Do not bypass types or safety rules.

Code Style and Style Guides
- Use ESLint with typescript plugin, Prettier, and a strict tsconfig. Enforce explicit types, no any, consistent naming.

Architecture & Directory Rules
- Entry point: src/server.ts. Routes in src/routes. Controllers in src/controllers. DB schema in db/drizzle/schema.ts. Migrations in db/drizzle/migrations.

Authentication & Security Rules
- Use HttpOnly cookies or Authorization header with JWT; never localStorage. Validate input via a schema, enable basic CSRF protection where applicable; Use helmet.

Database and ORM patterns
- Use Drizzle ORM models in db/drizzle/schema.ts; keep migrations in db/drizzle/migrations with semantic names. Use typed queries like select().where({ id })

Testing & Linting Workflows
- Unit tests for controllers and services; integration tests for routes with a test database. Include migrations in CI, ensure type safety across tests, and verify authentication flows. Use fixtures for deterministic tests.

Prohibited Actions and Anti-patterns for the AI
- Do not generate raw SQL strings with concatenated values. Do not bypass validation or typing layers. Do not introduce global mutable state or non deterministic behavior.

Overview

The Cursor rules configuration for Cursor AI is a stack specific blueprint that guides AI assisted development for an Express backend written in TypeScript that uses Drizzle ORM with PostgreSQL. This page delivers a copyable .cursorrules configuration and clear constraints so AI suggestions stay aligned with the Express TypeScript Postgres Drizzle stack.

When to Use These Cursor Rules

  • Use these rules when you want consistent Express route scaffolding with strong TypeScript typings.
  • Use these rules when Drizzle ORM is the only approved data access layer for PostgreSQL.
  • Use these rules when authentication, authorization, validation, and secure error handling must be applied by Cursor AI.
  • Use these rules when every generated change must pass repeatable linting, type checking, migration, and test workflows in CI.
  • Use these rules when AI-assisted code review must respect Express, TypeScript, Drizzle ORM, and PostgreSQL constraints.

Copyable .cursorrules Configuration

Framework Role & Context
- You are Cursor AI configured to assist in building an Express + TypeScript backend that uses Drizzle ORM for PostgreSQL. You provide precise, typed guidance and enforce project constraints. Do not bypass types or safety rules.

Code Style and Style Guides
- Use ESLint with typescript plugin, Prettier, and a strict tsconfig. Enforce explicit types, no any, consistent naming.

Architecture & Directory Rules
- Entry point: src/server.ts. Routes in src/routes. Controllers in src/controllers. DB schema in db/drizzle/schema.ts. Migrations in db/drizzle/migrations.

Authentication & Security Rules
- Use HttpOnly cookies or Authorization header with JWT; never localStorage. Validate input via a schema, enable basic CSRF protection where applicable; Use helmet.

Database and ORM patterns
- Use Drizzle ORM models in db/drizzle/schema.ts; keep migrations in db/drizzle/migrations with semantic names. Use typed queries like select().where({ id })

Testing & Linting Workflows
- Unit tests for controllers and services; integration tests for routes with a test database. Include migrations in CI, ensure type safety across tests, and verify authentication flows. Use fixtures for deterministic tests.

Prohibited Actions and Anti-patterns for the AI
- Do not generate raw SQL strings with concatenated values. Do not bypass validation or typing layers. Do not introduce global mutable state or non deterministic behavior.

Recommended Project Structure

ProjectRoot
├── src
│   ├── server.ts
│   ├── routes
│   │   └── index.ts
│   ├── controllers
│   └── middleware
├── db
│   └── drizzle
│       ├── schema.ts
│       └── migrations
│           └── 0001_init.ts
├── migrations
├── tests
├── drizzle.config.ts
├── tsconfig.json
├── package.json

Core Engineering Principles

  • Clear separation of concerns and explicit interfaces
  • Strict typing and predictable data contracts
  • Idempotent migrations and repeatable deployments
  • Security by default and defense in depth
  • Test driven guidance for AI assisted coding
  • Observability through structured logs and metrics
  • Documentation embedded in code and rules
  • Performance minded design for IO heavy endpoints

Code Construction Rules

  • Use TypeScript strict mode throughout the codebase, including noImplicitAny, strictNullChecks, and explicit return types for exported functions.
  • Keep HTTP concerns in Express route files, orchestration in controllers, reusable business logic in services, and database access in repositories or query modules.
  • All PostgreSQL access must go through Drizzle ORM schemas, typed query builders, and checked migrations. Do not concatenate raw SQL strings with user input.
  • Define Drizzle tables, relations, inferred insert/select types, and migration files together so generated code stays aligned with the database contract.
  • Validate every request body, query string, route parameter, and webhook payload at the boundary with Zod or an equivalent schema validator before calling services.
  • Use typed DTOs for API responses and never return raw database rows when the public contract needs filtering, renaming, or redaction.
  • Centralize environment parsing in one config module and fail fast when required variables such as DATABASE_URL, token secrets, or allowed origins are missing.
  • Use dependency injection for services, repositories, loggers, and external clients so tests can replace production dependencies cleanly.
  • Add unit tests for services, integration tests for Express routes, and migration checks whenever Cursor AI generates new endpoints, schema changes, or auth logic.

Security and Production Rules

  • Enable Helmet, strict CORS allowlists, secure cookies, request size limits, and HTTPS-only deployment settings for production Express servers.
  • Use HttpOnly, Secure, SameSite cookies or properly scoped Authorization headers for tokens. Do not store access or refresh tokens in browser localStorage.
  • Enforce authentication and authorization in middleware before controller logic, and make role checks explicit for every protected route.
  • Validate and sanitize all inputs before Drizzle queries, including route params, pagination values, filters, sorting fields, and webhook payloads.
  • Store secrets in a managed secret store or CI/CD environment variables. Never commit .env files, private keys, database URLs, or service tokens.
  • Use structured logging with request IDs, redact sensitive fields, and centralize error handling so production responses never leak stack traces, SQL details, or internal service names.
  • Apply rate limiting, abuse detection, audit logs, health checks, graceful shutdown, connection pooling, and migration discipline before deploying to production.
  • Run linting, type checks, tests, migration dry runs, and dependency vulnerability scans in CI before merging AI-generated backend changes.

Testing Checklist

  • Unit tests for controllers and services with deterministic fixtures
  • Integration tests for routes using a test database and seeded data
  • Migration tests to ensure schema compatibility across envs
  • Linter, type checks, and test suite run in CI with coverage reporting
  • End to end tests for critical user flows in a staging environment

Common Mistakes to Avoid

  • Skipping boundary validation because TypeScript types appear correct. Runtime inputs still need schema checks before they reach services or Drizzle queries.
  • Mixing Drizzle query builders with unsafe raw SQL, especially when filters, sort keys, IDs, or search terms come from users.
  • Putting business logic directly inside Express handlers, which makes authorization, testing, and reuse harder as the API grows.
  • Returning raw database records from controllers and accidentally exposing internal IDs, timestamps, soft-delete flags, password hashes, or tenant metadata.
  • Running ad hoc production database edits instead of versioned Drizzle migrations with rollback plans and test coverage.
  • Using one global database client or mutable singleton without lifecycle management, connection pooling, graceful shutdown, or test isolation.
  • Letting Cursor AI add packages, auth flows, or schema changes without updating tests, migrations, documentation, and deployment configuration.

Related implementation resources: AI Use Case for Veterinary Clinics Using WhatsApp To Let Pet Owners Send Images for Preliminary Urgency Triage and AI Skill Files and Templates: Speeding Up Production-Ready Development for New Developers.

FAQ

What is included in this Cursor Rules Template for Express + Drizzle + Postgres?

A tailored set of guidelines and a copyable .cursorrules block for an Express server written in TypeScript that uses Drizzle ORM for PostgreSQL. It enforces architectural boundaries, security practices, testing workflows, and production readiness to keep AI assisted coding aligned with your stack.

How do I apply the .cursorrules block in my project root?

Place the provided .cursorrules block at the repository root of your Express plus TypeScript and Drizzle project. The rules guide Cursor AI on scope architecture security and test patterns ensuring consistent AI assistance across routes services and database interactions.

Can I adapt this template to other ORMs?

Yes but you should reframe the ORM specific sections to match the target ORM API and typing. The core structure architecture security testing and production guidelines remain valid. Update the database patterns and migrations to reflect the new ORM conventions.

What tests should I add first?

Begin with unit tests for controllers and services and then add integration tests for routes using a test database. Include migrations in CI, verify type safety across tests, and cover authentication flows with realistic fixtures.

How do I run the Cursor AI checks locally?

Install dependencies, run TypeScript compile and linter, then execute the test suite and a local server. Use a subset of endpoints to validate Cursor AI guidance on architecture security and ORM usage and review the generated rules for completeness.