Backend Dev Guidelines

Streamline Node.js backend development with proven patterns and standards

✨ The solution you've been looking for

Verified
Tested and verified by our team
20553 Stars

Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, tenant isolation patterns, or async patterns. Covers layered architecture (tRPC procedures → services, queue processors → services), dual database system (PostgreSQL + ClickHouse), projectId filtering for multi-tenant isolation, traceException error handling, observability patterns, and testing strategies (Jest for web, vitest for worker).

backend-development nodejs express typescript microservices api-development architecture best-practices
Repository

See It In Action

Interactive preview & real-world examples

Live Demo
Skill Demo Animation

AI Conversation Simulator

See how users interact with this skill

User Prompt

Help me create a new user management microservice with authentication endpoints using the established patterns

Skill Processing

Analyzing request...

Agent Response

Complete microservice setup with routes, controllers, services, repositories, validation, and Sentry integration following the layered architecture

Quick Start (3 Steps)

Get up and running in minutes

1

Install

claude-code skill install backend-dev-guidelines

claude-code skill install backend-dev-guidelines
2

Config

3

First Trigger

@backend-dev-guidelines help

Commands

CommandDescriptionRequired Args
@backend-dev-guidelines building-a-new-microserviceCreate a well-structured microservice following layered architecture principles with proper error handling and monitoringNone
@backend-dev-guidelines refactoring-legacy-codeTransform existing backend code to follow modern patterns with proper separation of concernsNone
@backend-dev-guidelines api-endpoint-developmentCreate robust REST API endpoints with comprehensive validation, error tracking, and testingNone

Typical Use Cases

Building a New Microservice

Create a well-structured microservice following layered architecture principles with proper error handling and monitoring

Refactoring Legacy Code

Transform existing backend code to follow modern patterns with proper separation of concerns

API Endpoint Development

Create robust REST API endpoints with comprehensive validation, error tracking, and testing

Overview

Backend Development Guidelines

Purpose

Establish consistency and best practices across backend microservices (blog-api, auth-service, notifications-service) using modern Node.js/Express/TypeScript patterns.

When to Use This Skill

Automatically activates when working on:

  • Creating or modifying routes, endpoints, APIs
  • Building controllers, services, repositories
  • Implementing middleware (auth, validation, error handling)
  • Database operations with Prisma
  • Error tracking with Sentry
  • Input validation with Zod
  • Configuration management
  • Backend testing and refactoring

Quick Start

New Backend Feature Checklist

  • Route: Clean definition, delegate to controller
  • Controller: Extend BaseController
  • Service: Business logic with DI
  • Repository: Database access (if complex)
  • Validation: Zod schema
  • Sentry: Error tracking
  • Tests: Unit + integration tests
  • Config: Use unifiedConfig

New Microservice Checklist

  • Directory structure (see architecture-overview.md)
  • instrument.ts for Sentry
  • unifiedConfig setup
  • BaseController class
  • Middleware stack
  • Error boundary
  • Testing framework

Architecture Overview

Layered Architecture

HTTP Request
    ↓
Routes (routing only)
    ↓
Controllers (request handling)
    ↓
Services (business logic)
    ↓
Repositories (data access)
    ↓
Database (Prisma)

Key Principle: Each layer has ONE responsibility.

See architecture-overview.md for complete details.


Directory Structure

service/src/
├── config/              # UnifiedConfig
├── controllers/         # Request handlers
├── services/            # Business logic
├── repositories/        # Data access
├── routes/              # Route definitions
├── middleware/          # Express middleware
├── types/               # TypeScript types
├── validators/          # Zod schemas
├── utils/               # Utilities
├── tests/               # Tests
├── instrument.ts        # Sentry (FIRST IMPORT)
├── app.ts               # Express setup
└── server.ts            # HTTP server

Naming Conventions:

  • Controllers: PascalCase - UserController.ts
  • Services: camelCase - userService.ts
  • Routes: camelCase + Routes - userRoutes.ts
  • Repositories: PascalCase + Repository - UserRepository.ts

Core Principles (7 Key Rules)

1. Routes Only Route, Controllers Control

1// ❌ NEVER: Business logic in routes
2router.post('/submit', async (req, res) => {
3    // 200 lines of logic
4});
5
6// ✅ ALWAYS: Delegate to controller
7router.post('/submit', (req, res) => controller.submit(req, res));

2. All Controllers Extend BaseController

 1export class UserController extends BaseController {
 2    async getUser(req: Request, res: Response): Promise<void> {
 3        try {
 4            const user = await this.userService.findById(req.params.id);
 5            this.handleSuccess(res, user);
 6        } catch (error) {
 7            this.handleError(error, res, 'getUser');
 8        }
 9    }
10}

3. All Errors to Sentry

1try {
2    await operation();
3} catch (error) {
4    Sentry.captureException(error);
5    throw error;
6}

4. Use unifiedConfig, NEVER process.env

1// ❌ NEVER
2const timeout = process.env.TIMEOUT_MS;
3
4// ✅ ALWAYS
5import { config } from './config/unifiedConfig';
6const timeout = config.timeouts.default;

5. Validate All Input with Zod

1const schema = z.object({ email: z.string().email() });
2const validated = schema.parse(req.body);

6. Use Repository Pattern for Data Access

1// Service → Repository → Database
2const users = await userRepository.findActive();

7. Comprehensive Testing Required

1describe('UserService', () => {
2    it('should create user', async () => {
3        expect(user).toBeDefined();
4    });
5});

Common Imports

 1// Express
 2import express, { Request, Response, NextFunction, Router } from 'express';
 3
 4// Validation
 5import { z } from 'zod';
 6
 7// Database
 8import { PrismaClient } from '@prisma/client';
 9import type { Prisma } from '@prisma/client';
10
11// Sentry
12import * as Sentry from '@sentry/node';
13
14// Config
15import { config } from './config/unifiedConfig';
16
17// Middleware
18import { SSOMiddlewareClient } from './middleware/SSOMiddleware';
19import { asyncErrorWrapper } from './middleware/errorBoundary';

Quick Reference

HTTP Status Codes

CodeUse Case
200Success
201Created
400Bad Request
401Unauthorized
403Forbidden
404Not Found
500Server Error

Service Templates

Blog API (✅ Mature) - Use as template for REST APIs Auth Service (✅ Mature) - Use as template for authentication patterns


Anti-Patterns to Avoid

❌ Business logic in routes ❌ Direct process.env usage ❌ Missing error handling ❌ No input validation ❌ Direct Prisma everywhere ❌ console.log instead of Sentry


Need to…Read this
Understand architecturearchitecture-overview.md
Create routes/controllersrouting-and-controllers.md
Organize business logicservices-and-repositories.md
Validate inputvalidation-patterns.md
Add error trackingsentry-and-monitoring.md
Create middlewaremiddleware-guide.md
Database accessdatabase-patterns.md
Manage configconfiguration.md
Handle async/errorsasync-and-errors.md
Write teststesting-guide.md
See examplescomplete-examples.md

Resource Files

architecture-overview.md

Layered architecture, request lifecycle, separation of concerns

routing-and-controllers.md

Route definitions, BaseController, error handling, examples

services-and-repositories.md

Service patterns, DI, repository pattern, caching

validation-patterns.md

Zod schemas, validation, DTO pattern

sentry-and-monitoring.md

Sentry init, error capture, performance monitoring

middleware-guide.md

Auth, audit, error boundaries, AsyncLocalStorage

database-patterns.md

PrismaService, repositories, transactions, optimization

configuration.md

UnifiedConfig, environment configs, secrets

async-and-errors.md

Async patterns, custom errors, asyncErrorWrapper

testing-guide.md

Unit/integration tests, mocking, coverage

complete-examples.md

Full examples, refactoring guide


  • database-verification - Verify column names and schema consistency
  • error-tracking - Sentry integration patterns
  • skill-developer - Meta-skill for creating and managing skills

Skill Status: COMPLETE ✅ Line Count: < 500 ✅ Progressive Disclosure: 11 resource files ✅

What Users Are Saying

Real feedback from the community

Environment Matrix

Dependencies

Node.js 16+
TypeScript 4.5+
Express.js
Prisma ORM
Zod v4+
@sentry/node

Framework Support

Express.js ✓ (recommended) Next.js 14 ✓ tRPC ✓ Prisma ORM ✓ Jest ✓ Vitest ✓

Context Window

Token Usage ~3K-8K tokens depending on microservice complexity

Security & Privacy

Information

Author
langfuse
Updated
2026-01-30
Category
full-stack