SkilVaultSign inStart free

Catalogue / node-backend-patterns

node-backend-patterns

Older skill: source not recordedSignedStructures Node.js, Express and Next.js server code with repository, service and middleware layers, tuned database access, cache-aside strategies, centralized error handling, JWT auth with role checks, rate limiting, job queues and structured logs. Use when the user asks to "design a REST API", "fix…
---
name: node-backend-patterns
description: >-
  Structures Node.js, Express and Next.js server code with repository, service
  and middleware layers, tuned database access, cache-aside strategies,
  centralized error handling, JWT auth with role checks, rate limiting, job
  queues and structured logs. Use when the user asks to "design a REST API",
  "fix N+1 queries", "add caching", "set up auth middleware", or "add
  background jobs" in a Node backend. Not for frontend UI work, GraphQL schema
  design specifics, or non-JavaScript backends.
---

Node Backend Patterns

Layered patterns for server-side JavaScript: keep HTTP handling, business rules, and data access in separate layers, then apply the data, cache, error, auth, and queue patterns below. Match the pattern's complexity to the problem — in-memory examples here teach the shape, and the caveats say when a durable mechanism is required.

Layer responsibilities

| Layer | Owns | Must not | |---|---|---| | Route/controller | HTTP shape, status codes | Business rules, SQL | | Service | Domain logic, orchestration | Direct query builders | | Repository | Data access, one interface per aggregate | HTTP concerns |

An implementation must provide every operation its interface declares — a consumer calling findByIds against a repository that never declared it is a design bug, not a runtime surprise to tolerate.

API surface

Resource-based URLs with verbs per operation, plus query parameters for filtering, sorting, and pagination:

GET    /api/tickets            # list
GET    /api/tickets/:id        # read one
POST   /api/tickets            # create
PUT    /api/tickets/:id        # replace
PATCH  /api/tickets/:id        # partial update
DELETE /api/tickets/:id        # remove

GET /api/tickets?status=open&sort=created_at&limit=20&offset=0

Bound page size and require stable ordering on list endpoints. Middleware wraps handlers for cross-cutting concerns; note that a Pages-router NextApiHandler and an App-router Request → Response handler are not interchangeable — pick wrappers that match the router in use.

Repository and service

interface TicketRepository {
  findAll(filters?: TicketFilters): Promise<Ticket[]>
  findById(id: string): Promise<Ticket | null>
  findByIds(ids: string[]): Promise<Ticket[]>
  create(data: NewTicket): Promise<Ticket>
}

class PostgresTicketRepository implements TicketRepository {
  async findAll(filters?: TicketFilters): Promise<Ticket[]> {
    let q = db.from("tickets").select("id,subject,status,priority")
    if (filters?.status) q = q.eq("status", filters.status)
    if (filters?.limit) q = q.limit(filters.limit)
    const { data, error } = await q
    if (error) throw new Error(error.message)
    return data
  }
  // ...
}

The service composes repositories and owns nontrivial logic — for example a semantic search that embeds the query, fetches candidates, then reorders by similarity score:

class TicketSearchService {
  constructor(private repo: TicketRepository) {}

  async search(query: string, limit = 10): Promise<Ticket[]> {
    const embedding = await embed(query)
    const hits = await vectorSearch(embedding, limit)   // {id, score}
    const tickets = await this.repo.findByIds(hits.map(h => h.id))
    const score = new Map(hits.map(h => [h.id, h.score]))
    return tickets.sort((a, b) => (score.get(b.id) ?? 0) - (score.get(a.id) ?? 0))
  }
}

Decide deliberately whether higher score means more similar for your vector store; do not assume ascending order.

Data access that scales

  • Select only the columns the response needs, never select('*') by habit
  • Filter and sort on indexed columns; use the pool rather than ad-hoc connections
  • Always cap result size

N+1 — batch instead of looping:

// BAD: one query per row
for (const t of tickets) t.assignee = await getUser(t.assignee_id)

// GOOD: one batched query + lookup map
const ids = tickets.map(t => t.assignee_id)
const people = await getUsers(ids)
const byId = new Map(people.map(p => [p.id, p]))
tickets.forEach(t => { t.assignee = byId.get(t.assignee_id) ?? null })

Multi-table writes — one transaction. A database function (RPC) keeps the inserts atomic; in PostgreSQL the JSON payload must be decomposed into typed columns, since INSERT ... VALUES (jsonb) does not insert a row shape:

CREATE OR REPLACE FUNCTION create_ticket_with_reply(ticket_data jsonb, reply_data jsonb)
RETURNS jsonb LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO tickets (subject, status)
  VALUES (ticket_data->>'subject', ticket_data->>'status');
  INSERT INTO replies (ticket_id, body)
  VALUES (currval('tickets_id_seq'), reply_data->>'body');
  RETURN jsonb_build_object('ok', true);
EXCEPTION WHEN OTHERS THEN
  RETURN jsonb_build_object('ok', false, 'error', SQLERRM);
END; $$;

Review privileges, commit/rollback semantics, and what the error string exposes — return a safe status to callers and log details internally.

Caching

Cache-aside: check cache → on miss load from the database → store a serializable value with a TTL → invalidate on writes.

async function getTicket(id: string): Promise<Ticket> {
  const key = `tenant:${tenantId}:ticket:${id}`
  const hit = await redis.get(key)
  if (hit) return JSON.parse(hit)

  const ticket = await repo.findById(id)
  if (!ticket) throw new ApiError(404, "Ticket not found")

  await redis.setex(key, 300, JSON.stringify(ticket))  // 5 min: tune per data
  return ticket
}

Rules that keep caches honest:

  • Scope keys by tenant/resource so one customer's data never serves another
  • Invalidate or refresh on every relevant write path
  • A caching decorator must still implement the full repository interface
  • Decide behaviour on Redis downtime: fail, serve stale, or pass through
  • Distinguish Redis, in-process, and HTTP cache headers; private data must

never land in a shared cache

Errors

One error type plus one handler keeps responses uniform:

class ApiError extends Error {
  constructor(public status: number, message: string, public operational = true) {
    super(message)
  }
}

export function handleError(err: unknown): Response {
  if (err instanceof ApiError)
    return json({ success: false, error: err.message }, err.status)

  if (err instanceof z.ZodError)
    return json({ success: false, error: "Validation failed",
                  details: err.issues }, 400)

  log.error("Unexpected error", err as Error)         // details stay internal
  return json({ success: false, error: "Internal server error" }, 500)
}

export async function GET(req: Request) {
  try { return json({ success: true, data: await listTickets() }) }
  catch (e) { return handleError(e) }
}

Retries — exponential backoff, only for operations that are safe to repeat:

async function withRetry<T>(fn: () => Promise<T>, tries = 3): Promise<T> {
  let last: unknown
  for (let i = 0; i < tries; i++) {
    try { return await fn() }
    catch (e) {
      last = e
      if (i < tries - 1) await sleep(2 ** i * 1000)  // 1s, 2s between attempts
    }
  }
  throw last
}

Three attempts means two waits — 1s and 2s — not a final 4s wait after the last failure. Never retry non-idempotent operations blindly; add jitter and timeouts for real traffic.

Authentication and authorization

Validate the token's signature, accepted algorithms, expiry, and claims — a TypeScript cast does not validate a role. Read secrets from the runtime environment; never print or log them.

export async function requireAuth(req: Request): Promise<SessionUser> {
  const token = req.headers.get("authorization")?.replace("Bearer ", "")
  if (!token) throw new ApiError(401, "Missing authorization token")
  const payload = await verifyJwt(token, { algorithms: ["RS256"] })
  return { id: payload.sub, role: payload.role }
}

Authorization is separate from authentication — check ownership and role per action and return 403 when insufficient:

const ROLE_PERMS = {
  admin:     ["read", "write", "delete", "admin"],
  moderator: ["read", "write", "delete"],
  agent:     ["read", "write"],
} as const

export function requirePermission(perm: keyof (typeof ROLE_PERMS)["agent"]) {
  return (handler: (req: Request, user: SessionUser) => Promise<Response>) =>
    async (req: Request) => {
      const user = await requireAuth(req)
      if (!ROLE_PERMS[user.role].includes(perm))
        throw new ApiError(403, "Insufficient permissions")
      return handler(req, user)
    }
}

export const DELETE = requirePermission("delete")(async (req, user) => {
  await assertOwnsTicket(user, req.params.id)   // ownership, not just role
  return new Response(null, { status: 204 })
})

Rate limiting

A sliding-window limiter keeps recent request timestamps per identity:

class RateLimiter {
  private hits = new Map<string, number[]>()

  allow(id: string, max: number, windowMs: number): boolean {
    const now = Date.now()
    const recent = (this.hits.get(id) ?? []).filter(t => now - t < windowMs)
    if (recent.length >= max) { this.hits.set(id, recent); return false }
    recent.push(now)
    this.hits.set(id, recent)
    return true
  }
}
// 100 requests per minute per IP
if (!limiter.allow(ip, 100, 60_000)) return json({ error: "Rate limit exceeded" }, 429)

Caveats that matter in production: derive the identity from trusted proxy headers, not any client-supplied value; a per-process in-memory map does not coordinate across instances — use a shared store for distributed limits; prune old entries so the map cannot grow without bound; and answer 429 with meaningful headers.

Background jobs

An in-process queue serializes work and keeps request handlers fast:

class JobQueue<T> {
  private queue: T[] = []
  private running = false
  constructor(private execute: (job: T) => Promise<void>) {}

  async add(job: T) {
    this.queue.push(job)
    if (!this.running) this.drain()
  }
  private async drain() {
    this.running = true
    while (this.queue.length) {
      try { await this.execute(this.queue.shift()!) }
      catch (e) { log.error("Job failed", e as Error) }
    }
    this.running = false
  }
}

Be honest about its guarantees: everything in memory is lost on restart, and "queued" does not mean "done". When delivery must be guaranteed, use a durable queue with retries, a dead-letter path, idempotent handlers, and graceful shutdown — implement execute for real, never as a placeholder.

Structured logging

One JSON line per event, with request correlation:

logger.info("listing tickets", { requestId, method: "GET", path: "/api/tickets" })
  • Include timestamp, level, message, request id, method/path, and actor id
  • Never log tokens, passwords, or raw personal data
  • Keep stack traces in internal logs, out of API responses
  • Monitor the operational signals: query latency, pool usage, cache hit rate,

job failures, rate-limit rejections

Never

  • Log, echo, or commit secrets and credentials, or read them from anywhere but the approved runtime config
  • Skip the ownership/permission check because the route already requires login
  • Serve one tenant's cached data under another tenant's key
  • Present the in-memory limiter or queue as production-grade without a shared/durable replacement
  • Retry non-idempotent operations or unbounded job failures without a policy