惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
C
Check Point Blog
有赞技术团队
有赞技术团队
H
Help Net Security
V
Vulnerabilities – Threatpost
N
News | PayPal Newsroom
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 最新话题
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 【当耐特】
爱范儿
爱范儿
I
InfoQ
V
Visual Studio Blog
O
OpenAI News
Google DeepMind News
Google DeepMind News
S
Security Affairs
T
Troy Hunt's Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
N
Netflix TechBlog - Medium
Latest news
Latest news
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Webroot Blog
Webroot Blog
S
Schneier on Security
MongoDB | Blog
MongoDB | Blog
T
Tor Project blog
V2EX - 技术
V2EX - 技术
Security Latest
Security Latest
Cloudbric
Cloudbric
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
T
The Exploit Database - CXSecurity.com
P
Privacy International News Feed
S
Securelist
C
Cisco Blogs
博客园_首页
TaoSecurity Blog
TaoSecurity Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threat Research - Cisco Blogs
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
A NestJS reference app that proves the nest-native stack under realistic backend pressure
Rodrigo Nogueira · 2026-05-25 · via DEV Community

TL;DR: nest-native/reference-app is a v0.1 reference application that demonstrates the nest-native stack end-to-end — nest-drizzle-native and nest-trpc-native composing under realistic backend pressure: feature modules, multi-tenant auth context, cross-service transactions via @Transactional(), an outbox-pattern worker for post-commit side effects, and a typed tRPC client smoke check. Everything decorator-first, ~zero hidden magic, and all eight implementation milestones shipped via PR with security and dependency review on each one. Repo: github.com/nest-native/reference-app.

A quick note about the org

nest-native is a fresh community GitHub organization publishing decorator-first NestJS integrations. The point is that each integration should feel like an official NestJS package — modules, decorators, DI, enhancers, lifecycle hooks — while staying honest about the underlying tool. Drizzle stays SQL-first. tRPC stays tRPC. No hidden magic where explicit application code would be clearer.

Two libraries are currently published:

  • nest-drizzle-native — Drizzle ORM with DrizzleModule.forRoot(), forFeature([Repo]), @DrizzleRepository, @InjectDrizzle, and @Transactional via @nestjs-cls/transactional.
  • nest-trpc-native — Decorator-first tRPC for NestJS: TrpcModule.forRoot(), @Router, @Query/@Mutation/@Subscription, @Input, @TrpcContext, plus generated AppRouter types for fully-typed tRPC clients.

Both ship with samples, ≥99% coverage, support policies, and a strict design bar. That bar is exactly what made the reference app necessary.

The problem this exists to solve

If you're starting a new NestJS backend in 2026 and you've picked Drizzle for the database and tRPC for the API layer, you have a composition problem. Each library is well-documented in isolation, but a real backend is the composition — and the composition is where most of the design decisions live. Library docs cover their slice; nobody covers the seams.

Here are the questions you'd otherwise have to answer from scratch, in roughly the order they bite:

  • How do I thread "current user" and "current organization" through everything? An Express middleware can set req.authContext easily enough — but how does that reach a tRPC procedure? A guard? A service three calls deep in a request? The right answer involves request-scoped DI, TrpcModule.forRoot({ createContext }), custom param decorators that work for both transports, and class-level @UseGuards. There's no canonical example anywhere that wires all of it together end-to-end.

  • How do I do a real transaction across services? "Insert a user, then a membership, then a project, then an audit row, then enqueue a notification" is a single business operation. If you split it across services — which you should — do they share a transaction? @nestjs-cls/transactional gives you a @Transactional() decorator, but how does the inner repo know to use the tx client and not the raw one? And what if you're on better-sqlite3 for local dev? (Spoiler: not with the official adapter — its async wrapper silently commits empty transactions against synchronous sqlite. You need a custom sync adapter, which the reference app ships as ~30 lines.)

  • How do I send a post-commit side effect without losing it? "After the transaction commits, send the welcome email" sounds easy until you realize you can't send inside the tx (rollback → ghost email) and you can't send after the tx return either (process crashes → lost email). The transactional outbox is the right answer. Reinventing it is a week of subtle bugs around atomic claims, idempotency keys, stuck-claim recovery, and exponential backoff.

  • How do I prove my tRPC procedures still match my clients? tRPC's pitch is end-to-end type safety — but only if the generated AppRouter actually round-trips into a real typed client at CI time. Most teams skip this and find out their procedures broke when their frontend breaks in staging.

  • What does the boring scaffolding actually look like? ESLint flat config with a cognitive-complexity ceiling, drizzle-kit migrations with a forward-only contract, node:test + c8 coverage, an npm run ci chain (typecheck → lint → complexity → tests → audit → build), a Dockerfile that runs both API and worker off the same image, a CHANGELOG with per-dependency justifications. Two to four days of YAML and config decisions before you can write any business logic.

This repo answers each of those with a decision, not a menu of options. You can disagree with any one of them and swap it out — but you're disagreeing with something concrete rather than designing in a vacuum.

It is not a product and not a library. The two implicit deliverables are:

  1. A credible demo a team can fork (or copy patterns from) for a real backend.
  2. A feedback loop into the libraries themselves — if a pattern feels awkward here, that's signal to add API upstream in a separate PR to the relevant library repo.

A bug found while building it actually flowed exactly that way. A missing await in nest-trpc-native was silently mis-mapping HttpException → INTERNAL_SERVER_ERROR whenever any interceptor was in the chain (and @nestjs-cls/transactional always registers a passthrough interceptor). The fix shipped as nest-trpc-native@0.4.3 before milestone 6 of the reference app could land. Without a reference app exercising the composition under load, that bug would have hit production for someone else first.

The stack

Layer Pick
API NestJS 11.x
RPC tRPC 11.x via nest-trpc-native
ORM Drizzle 0.45.x via nest-drizzle-native
DB (local) better-sqlite3 (zero-setup)
DB (prod recipe) Postgres via pg (documented swap)
Transactions @nestjs-cls/transactional with a custom sync adapter for better-sqlite3
Auth scrypt + HS256 JWT, all via node:crypto (no JWT lib dep)
Tests node:test + c8 coverage
Lint ESLint 10 flat config + sonarjs (cognitive complexity ceiling 15)

Runtime dependencies are pinned and every one of them has a one-line justification in CHANGELOG.md. Default to Node built-ins. New deps need explicit acceptance in the PR.

Module shape

reference-app as an architecture city: a central reference-app building wires nine feature modules (auth, users, projects, memberships, onboarding, audit, outbox, trpc, db) via glowing teal paths; two red arcs trace the cross-cutting concerns — tx (transactions) and auth (request context)

reference-app (center) wires the nine feature modules around it. Two concerns cut across the architecture: *tx** — a @Transactional() method spans users, memberships, projects, audit, outbox in one transaction — and auth — the request-scoped CURRENT_USER / CURRENT_ORGANIZATION context is consumed by every procedure.*

AppModule wires DatabaseModule (with DrizzleModule.forRoot), ClsModule (with ClsPluginTransactional), AuthModule, RequestContextModule, one module per feature (organizations, users, projects, audit-log, outbox, onboarding), and AppTrpcModule (with TrpcModule.forRoot). Every feature module is the same four files: <feature>.repository.ts (@DrizzleRepository), <feature>.service.ts (business logic, reads CURRENT_USER / CURRENT_ORGANIZATION), <feature>.router.ts (@Router('…') + @UseGuards(AuthGuard)), <feature>.module.ts (DrizzleModule.forFeature([Repo]) + service + router). Shape borrowed from nest-drizzle-native's sample-17.

Multi-tenant auth, end-to-end

One Express middleware reads the Authorization: Bearer … header, calls AuthService.resolve(token) (HS256 verify via node:crypto), and sets req.authContext = { user, organization }. That single shape is then consumed three ways:

  • REST controllers@CurrentUser() / @CurrentOrganization() param decorators read it via switchToHttp().getRequest().
  • tRPC proceduresTrpcModule.forRoot({ createContext: ({ req }) => ({ authContext: req.authContext ?? null }) }) puts the same value on the tRPC ctx. The same param decorators fall through getArgs()[1] first, so one implementation serves both transports.
  • Request-scoped DIRequestContextModule exposes CURRENT_USER and CURRENT_ORGANIZATION as Scope.REQUEST providers backed by req.authContext. Services inject them directly, no threading through every method signature.

JWT signing and verification: ~50 lines on top of node:crypto's HMAC, no JWT library dep. Password hashing: scrypt with the format scrypt$<salt-hex>$<hash-hex> — same helpers in the seed and the auth service so seeded admins can log in immediately.

The central proof — a five-step @Transactional() workflow

The brief calls it "the central proof": one method that writes across five tables inside a single transaction, then queues a post-commit side effect via the outbox pattern. If transactions don't compose cleanly across services, this is where it breaks.

inviteUser as a pipeline: five numbered steps — users, memberships, projects, audit_events, outbox_events — flow through a transaction; a commit valve releases the queued outbox event to the worker

Five steps inside one transaction (1. users, 2. memberships, 3. projects, 4. audit_events, 5. outbox_events), then commit, then the worker delivers the post-commit side effect.

The annotated body:

@Transactional()
inviteUser(input: InviteUserInput): Promise<InviteUserResult> {
  const user       = this.upsertUser(input.email, input.initialPassword);
  const membership = this.memberships.create({ /* orgId, userId, role */ });
  const project    = this.projects.create({    /* orgId, name, createdBy */ });
  this.audit.record({          /* "user.invited" with invitee+project metadata */ });
  const event = this.outbox.enqueue({
    topic: 'user.invited',
    payload: { invitedEmail: input.email, /* … */ },
    idempotencyKey: `user.invited:${input.orgId}:${user.id}:${project.id}`,
  });
  return { user, membership, project, outboxEventId: event.id };
}

Two non-obvious choices in the wiring around it:

  1. @InjectTransaction(), not @InjectDrizzle(). The CLS proxy resolves to the active tx client inside @Transactional and falls back to the raw client outside one — transparent to the repo. @InjectDrizzle() always returns the raw client, so writes from inside the transactional method would not participate in the transaction. Easy to miss; the symptom is "everything looks fine, nothing rolls back."
  2. A custom sync transactional adapter for better-sqlite3. The official @nestjs-cls/transactional-adapter-drizzle-orm wraps the inner Drizzle callback in async, which silently commits empty transactions against synchronous sqlite (its client.transaction(fn) is sync and treats the async callback's immediately-returned Promise as a successful return). The repo ships a ~30-line SyncDrizzleTransactionalAdapter that keeps the inner callback synchronous while still returning a Promise to satisfy the plugin contract. Swap to the official adapter when moving to libsql or Postgres.

The brief mandates three tests around this method, and all three pass:

  • Happy path — all five rows persisted; the outbox row is visible after commit; the worker tick processes it; FakeEmailTransport records exactly one email.
  • Rollback safety — force a throw between project insert and the audit event; assert zero rows from this transaction persist; assert no email recorded.
  • Worker crash recovery — seed an outbox row in processing state with a stale claimed_at; the next claimer tick re-claims it (under the stuck-timeout), processes it exactly once, and a follow-up tick is a no-op.

The outbox + worker

The outbox lifecycle: a worker picks up envelopes from a

Rows go pending → processing → completed. Retryable errors bounce back to pending (attempts++ + backoff). Max attempts go to failed. Stuck processing rows get re-claimed by another worker after a timeout.

Three small pieces, one file each: OutboxProducer inserts a pending row inside the active tx with a partial-unique idempotency key (multiple NULLs coexist, non-null is unique). OutboxRegistry is a Map<topic, handler> populated by handlers on module init. OutboxClaimer.tick() opens a tx, selects pending-OR-stuck rows, marks them processing, dispatches, then marks completed / retries with backoff+jitter / marks failed at max attempts. The claim is the "BEGIN IMMEDIATE + status filter" shape from the brief; Postgres would use SELECT … FOR UPDATE SKIP LOCKED.

The worker process is just scripts/start-worker.ts — boot a headless Nest application context, resolve OutboxClaimer, tick on a configurable interval, abort cleanly on SIGTERM/SIGINT. Same Docker image runs either the API (default CMD) or the worker (node dist/scripts/start-worker.js override); docker-compose.yml wires both on a shared SQLite volume with a healthcheck.

Typed tRPC client smoke

The brief's "definition of done" requires a typed client that consumes the generated AppRouter and exercises one query, one mutation, and one auth-protected call against a live local server. That lives in client-smoke/ and is part of npm run ci:

import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../src/@generated/server';

const anon = createTRPCClient<AppRouter>({ links: [httpBatchLink({ url: `${baseUrl}/trpc` })] });

const ping = await anon.ping.query();                              // query
const login = await anon.auth.login.mutate({ email, password });   // mutation

const auth = createTRPCClient<AppRouter>({
  links: [httpBatchLink({
    url: `${baseUrl}/trpc`,
    headers: () => ({ authorization: `Bearer ${login.token}` }),
  })],
});
const me = await auth.users.me.query();                            // auth-protected query

The compiled output (which lands in CI as npm run client-smoke:typecheck) catches any router-shape change that would break a real client.

Try it in 30 seconds

git clone https://github.com/nest-native/reference-app
cd reference-app
nvm use && npm install
DATABASE_URL=./reference-app.db npm run db:migrate
DATABASE_URL=./reference-app.db npm run seed

AUTH_SECRET=dev-secret-must-be-at-least-32-characters-xxxxx \
  DATABASE_URL=./reference-app.db \
  npm run start:dev

Then in another terminal:

AUTH_SECRET=dev-secret-must-be-at-least-32-characters-xxxxx \
  DATABASE_URL=./reference-app.db \
  npm run start:worker

The seed creates admin@acme.test / admin123! with one starter project. client-smoke walks the typed end-to-end flow.

What it deliberately is not

Restating these because they shape what shouldn't be added:

  • Not a CLI (create-nest-native-app). Permanent maintenance cost, marginal value over a well-organized template repo.
  • Not the home of a standalone outbox package. The outbox pattern lives here as an in-app module. A hypothetical nest-outbox-native extraction (no such package exists today) would only be worth considering after three+ real apps independently rewrite the same shape.
  • Not a frontend. client-smoke/ is a typed-client smoke test, not a UI.
  • Not multi-database / GraphQL / micro-frontends. Resist scope creep.

If a pattern repeats three times here, it's a candidate for upstreaming to nest-drizzle-native or nest-trpc-native — not for a local helper.

Where to find it

The org as a whole: nest-native.dev · github.com/nest-native.

If you build something on top, open an issue — pattern repetition is what tells us when an idea is ready to graduate from "this is how the reference app does it" to "this is shipped library API."