SpaceDev's reusable NestJS backend template. It exists to serve two workflows: lift one module into an existing project, or clone the whole thing and delete what you don't need. See below for what that means and how to work with it, or jump to what is in here for the module catalogue. If you are handing the first workflow to an agent rather than doing it yourself, read Handing this to Claude.
This is the SpaceDev reusable NestJS template. Each top-level directory under
src/ is a module designed to be lifted into another project on its own.
CLAUDE.md— project invariants, commands and the module map. Start here.src/<module>/CLAUDE.md— rules, public surface and extraction recipe for that module.src/<module>/README.md— human-facing recipes and examples for that module..claude/skills/setup-template/— the guided setup wizard, run by hand with/setup-template. See Guided setup.
Each module's two files are self-contained on purpose: they describe how that module works and what it needs elsewhere, and they reference nothing outside their own directory. A module copied into another project takes its documentation with it and none of it dangles.
Run pnpm run docs:check after editing any CLAUDE.md.
Sixteen modules. "Companions" are the other src/ directories that module's
imports reach into — the narrowest subtree that has to travel with it, taken
from pnpm run modularity:check -- --report, which is the source of truth when
this table drifts. Each module's own README.md has the recipes and its
## Reuse section the full peer-dependency list.
| Module | Owns | Adapters | Companions in src/ |
|---|---|---|---|
analytics |
Product event capture and feature-flag checks | console, posthog |
logger, config-provider |
auth |
JWT issuance and verification, Passport strategies, Google OAuth, Auth0 | — (providers: google, auth0) |
logger, common/exception/, config-provider, database |
cache |
Key/value cache with TTL, plus an extension mechanism for provider-specific ops | redis |
none |
cloud-storage |
File upload, retrieval and deletion, with an optional mountable controller | local, s3 |
logger, config-provider |
common |
HTTP exception vocabulary, global response interceptor and exception filter, shared decorators, module-validation helper | — | none inside src/ — but see the @types/ caveat |
common/observability/logger |
The logging abstraction and trace-id correlation | nest, pino, winston |
none |
common/observability/telemetry |
OpenTelemetry bootstrap and the @Span() decorator |
— | none |
config-provider |
Config resolution for the whole app: source adapters, the dynamic module, defineConfigScope |
env, secrets-manager |
logger |
database |
TypeORM connection, entities, base entity, migrations | — | config-provider |
email |
Email delivery of pre-rendered content | aws-ses, sendgrid, resend, console |
logger, config-provider |
health |
Readiness (GET /health) and liveness (GET /health/live) for load balancers and container runtimes |
— | logger, cache — both optional |
push-notification |
Push delivery | expo |
logger, config-provider |
queues |
Producer and consumer abstractions for message queues | bullmq, rabbitmq, sqs |
logger, config-provider |
spaceship |
The reference domain module — CRUD, cache-aside reads and a background email job. Written to be deleted, not lifted | — | nine of the other thirteen; see its README |
templates |
The template files and the typed registry naming them — no executable code | — | none |
templating |
Compiling a template to HTML | pug |
common/utils/ |
"logger" above means src/common/observability/logger/ specifically, not all
of src/common/. Ten modules have an edge into common; seven of them reach
only into that subtree. auth and spaceship also use common/exception/,
and templating uses only common/utils/ — one import,
nest-module-validation. Four things
the table cannot show:
- Config scopes live with their consumer, not with
config-provider. So a module that listsconfig-provideras a companion needsjoitoo, and the scope file comes with the module. cacheneeds zero companions but does not bring its own config.src/app.module.tsfeeds it fromsrc/redis.scope.ts, an application-level scope shared withsrc/queues/bullmq-adapter/. Bring that file or hand the adapter a plain object — seesrc/cache/CLAUDE.md's## Reuse.health's two companions are both@Optional(). It boots with neitherCacheServicenorLoggerServiceregistered — the cache simply drops out of the readiness check instead of being reported healthy. The imports still have to resolve, which is why they are listed.commonhas a companion that is not a directory undersrc/. Its middleware only type-checks because of the ambientExpress.Useraugmentation in the repo-root@types/directory, which no import statement names. Step 3 of the recipe below covers it.
Only cache, email and queues have been measured by actually copying them
into a clean project; the numbers and the caveats are below.
The general recipe:
- Copy
src/<module>/into the destination project. - Copy each companion directory that module depends on (see below) into the
destination's
src/. - If
commonis one of those companions, also copy the repo-root@types/directory, and put it somewhere the destination'stsconfig.jsonactually compiles — this repo declares noinclude, so a.d.tsat the project root is part of the program; a destination with"include": ["src"]needs the file undersrc/instead.commondepends on the ambientExpress.Usertype declared there — seesrc/common/CLAUDE.md's## Reusesection for the details, since this is the dependency with no import statement, so no amount of reading the source will surface it. (Thesrc/common/observability/logger/subtree on its own does not need it: the queues measurement below compiled clean without it.) - Install the module's npm packages (below).
- Register the module in the destination's
src/app.module.ts, the way this template's ownsrc/app.module.tsdoes.
Prerequisite — the destination's module system. nest new asks which
module system you want and defaults to ESM: "type": "module" in
package.json, nodenext resolution, and Vitest. Under "type": "module"
every relative import needs an explicit .js extension, and no file in this
template writes one, so no module from this template compiles into a default
scaffold until either the destination drops "type": "module" or every
relative import in the copied code gains a .js extension.
The other answer to that prompt is the one that fits. nest new --type cjs
produces "module"/"moduleResolution": "nodenext" with no "type" field
and Jest — which is exactly this repo's tsconfig.json since the 2026-09-21
Nest 12 upgrade. Into that scaffold a module copies across unchanged.
Extensionless relative imports stay legal because the package is CommonJS;
nodenext is only how TypeScript reads the exports map that every Nest 12
package now ships. The wider gap this paragraph replaces was measured against
@nestjs/cli 12.0.3 and TypeScript 6.0.3, before this template moved to
nodenext.
One thing does not travel with the source, whichever answer you give: a
CommonJS destination on Jest must start Jest with
node --experimental-vm-modules ./node_modules/jest/bin/jest.js, or any
spec that reaches an ESM package — @nestjs/terminus, or @nestjs/common
itself — dies with SyntaxError: Unexpected token 'export'. Copy this repo's
test scripts along with the code. On Vitest the question does not arise.
What that costs, measured by copying each module alone into a fresh nest new
project and running tsc --noEmit. The 2026-09-19 queues run is not
reproducible from a bare nest new any more: the scaffold was first aligned to
this template's CommonJS settings, for the reason given in the prerequisite
above, before any template code was copied in.
cachelifts with zero companion directories —tsc --noEmitexits 0. Needs the npm packageioredis. Measured 2026-09-18.emaillifts with two companions,commonandconfig-provider. Needsresend,@sendgrid/mail,@aws-sdk/client-ses,joi. Measured 2026-09-18.queueslifts with two companions,src/common/observability/logger/andsrc/config-provider/. Copyingsrc/queues/alone leaves 19 unresolved imports; with both companionstsc --noEmitexits 0.src/queues/itself needsbullmq,amqplib(plus@types/amqplib),@aws-sdk/client-sqsandjoi, plus@types/jestif you copy itstests/folders — 11 of those 19 errors are in spec files, 8 are not; the companions bring their own —class-transformer,pino,winston,@opentelemetry/apiand@opentelemetry/sdk-trace-nodefor the logger,@aws-sdk/client-secrets-manageranddotenvforconfig-provider. Measured 2026-09-19.
The cache and email figures were measured on 2026-09-18 and have not been
re-verified since; in particular they predate the scaffold change described
above, which was only discovered during the 2026-09-19 queues measurement.
queues is the one that changed, and the reason is worth keeping: it used not
to lift at all, because the root module named the demo domain's handler. Moving
consumer registration to QueueConsumerModule.forFeature — where the domain
module binds its own handler — brought its closure down to the two companions
above. The binding now travels from the domain module to queues and never the
other way, which is why spaceship can sit in the tree without queues
depending on anything but common and config-provider.
This measures compile time, not boot time. Every result above means
tsc --noEmit exits 0 — it does not mean the lifted module works once
running. Whether, say, cache's forRootAsync resolves when the host project
registers no matching config scope is untested — nothing here answers that.
The recipe above assumes you are reading it. The other way to run it is to
point an agent at this repository from the destination project — "use the
email module from NestJS-Template here". For that to work the agent needs
both repositories on disk; it cannot read a module it cannot open.
Give it the path and the module, and say to follow this section:
Both repos are local: the template is at
<path>, we are in the destination. Lift<module>from the template into this project following the "Handing this to Claude" section of the template'sREADME.md.
What the agent should then do, in this order:
- Read three files before copying anything — the template's root
CLAUDE.md(invariantsT1-T8, which the copied code assumes), andsrc/<module>/CLAUDE.md's## Scopeand## Reuse. If the module will gain an adapter in the destination, readsrc/cache/CLAUDE.mdtoo — it is the reference implementation of the shape.## Reuseis the authoritative list of what travels with the module; the catalogue table above is the summary, that section is the detail. - Settle the module system first, before deciding anything else. Check
the destination's
package.jsonfor"type": "module"and itstsconfig.jsonfor"moduleResolution". If the destination is ESM, this is a real fork in the road and the wrong moment to guess — the prerequisite above explains why, and the two ways out are to drop"type": "module"or to add a.jsextension to every relative import in the copied code. Say which one you are taking and why, rather than discovering it as a wall ofTS2307s later. Then check how the destination runs Jest: a CommonJS project whosetestscript is a barejestwill fail on the first ESM import, and the fix is the--experimental-vm-modulesinvocation in this repo'spackage.json. - Copy the module, then its companions, from the
## Reuselist — not from the import errors, which under-report: the@types/expressambient augmentation thatsrc/common/middleware/response.interceptor.tsneeds has no import statement, so no compiler error names it. - Install the peer packages named in
## Reuse, with the destination's package manager, not necessarilypnpm. - Register it the way
src/app.module.tshere does — the abstract module'sforRoot/forRootAsync, never the adapter class directly (T1). If the destination has no config-provider, this is the step that needs a decision: portsrc/config-provider/too, or write a factory against whatever the destination already uses. Do not invent a third mechanism. - Verify with the destination's own gates, and say which ones ran.
tsc --noEmitis the floor, and it is exactly what the measurements above mean — nothing here has been proven to boot in another project. If the destination has tests, run them. Do not report the lift as working on the strength of a clean compile alone; say "compiles, not booted".
Two failure modes worth naming, because both look like success:
- Copying an adapter without its abstraction.
S3AdapterServiceimported directly into a destination service compiles and runs, and throws away the entire point of the module (T1). The destination should injectCloudStorageService. - Rewriting relative imports to absolute ones.
src/...specifiers break the next copy out (T5) andpnpm run modularity:checkfails on them here. Keep them relative in the destination too.
The other supported workflow: clone the repository and delete what you don't need, keeping the rest wired together.
Start with spaceship. It is the one demo module — the reference domain
implementation — and it is the only thing here written to be thrown away.
Nothing imports it, but it imports nine of the other thirteen directories, so
removing it first is what makes several of them free-standing.
src/spaceship/README.md's Deleting it is the
seven-step checklist; it is longer than the three edits below because the
module owns an entity, two config scopes and an email template.
After that, what comes out cleanly is a module no other module imports: the
seven adapter modules analytics, cache, cloud-storage, email,
push-notification, queues and templating, and also auth, which is not
an adapter module but has no inbound edges either once spaceship is gone
(removing it leaves database with no importers left). Each of those is
removed with the same three edits:
- Remove its registration from
src/app.module.ts. - Remove its config scope from that file's
scopesarray.templatingregisters none;cacheandqueuessharesrc/redis.scope.ts, so that one goes only when both have. - Remove its variables from
.env.example.
The rest of the tree is not free-standing. pnpm run modularity:check -- --report prints the edges that say so, and today they are:
commonis imported byanalytics,auth,cloud-storage,config-provider,email,health,push-notification,queues,spaceshipandtemplating.config-provideris imported byanalytics,auth,cloud-storage,database,email,push-notification,queuesandspaceship— and importscommonitself.databaseis imported byauth(27 specifiers) andspaceship(8).auth,email,queues,templatesandtemplatingare imported byspaceshipand by nothing else;cachebyspaceshipandhealth. Delete the demo module first and all six come out with the three edits above.
So common, config-provider and database do not come out on their own:
deleting any of them while something above still imports it leaves the tree
non-compiling. They go last, once everything that imports them has gone.
One directory fits neither list, having no registration and no config scope in
src/app.module.ts:
src/templates/holds three templates registered insrc/templates/template.const.ts.WELCOMEandVERIFICATIONare starting points, not demo content — there is nothing to strip there.SPACESHIP_CREATEDis demo content and goes withspaceship, which is the only thing that imports this directory. Once it has,src/templates/is free-standing again — take it or delete it without touching anything else. (The other importer it used to have, theGET /emaildemo route, was removed: unguarded, it sent a real message to a hardcoded address from whatever provider the environment had configured. The render-then-send pattern it showed is written up insrc/email/README.md.)
Run pnpm run modularity:check -- --report for the current dependency graph
before deleting anything, rather than trusting a copy of it that will drift.
$ pnpm install # pnpm 10.15.1, Node 24.15.0 — never npm or yarn
$ cp .env.example .env # then fill the required keys, see belowNestJS 12, TypeScript 6, Jest 30, Node 24. Two consequences worth knowing
before the first pnpm test: every Nest 12 package is ESM-only, so
tsconfig.json uses "module": "nodenext" while still emitting CommonJS (the
nest new --type cjs layout), and the test scripts start Jest through
node --experimental-vm-modules because a CommonJS test cannot otherwise load
an ESM dependency. Run pnpm test, never a bare jest. CLAUDE.md's
## Toolchain has the rest.
.env.example lists every key the code actually reads, grouped by the module
that reads it, and marks which ones are required. Copied as it ships, it boots
against the containers below with exactly one thing to fill in: JWT_SECRET,
left blank on purpose so the app refuses to start rather than sign tokens with
a shared constant. The database address has no default either — DATABASE_URL
or the full DB_* set — but the value in the file is the one
docker-compose.yml creates. Everything else has a working local default, and
the provider-backed modules all ship a no-network adapter for development:
EMAIL_ADAPTER=CONSOLE and ANALYTICS_ADAPTER=CONSOLE, with both OAuth
providers off.
One rule that file states and that is easy to get wrong: a blank value is a
value, not an omission. KEY= hands the config scope an empty string, and Joi
rejects an empty string for every key but nine. To leave something unset,
comment the line out — which is why the optional blocks in that file ship
commented rather than empty.
The section above is the manual route: read .env.example, decide each key,
delete what you don't need. The other route is to have an agent walk you
through the same decisions one at a time. In Claude Code, type:
/setup-template
It does not start on its own. The skill lives in
.claude/skills/setup-template/ and carries
disable-model-invocation: true, so an agent cannot reach for it — only you
can, by typing the command. That is deliberate: it rewrites .env,
src/app.module.ts and src/main.ts, and every step needs your answer.
Asking an agent what TRUST_PROXY does gets you an answer, not a wizard.
Fourteen stages, one question per message, and nothing is written until you
submit. Stage 14 shows the resolved .env, every file edit and every
deletion, and asks once; only then does anything change, and the five CI gates
run straight after.
You do not have to know the answers. Stage 1 asks how much you want explained, and every question after it carries a "no sé qué es esto" option: it explains the decision in plain terms, says which option it would pick and why, and then asks you again rather than deciding for you. If it is genuinely not your call — the database URL, the OTLP collector — you can park the question: the shipped default stays in place and the stage is listed at the submit as a handoff for whoever does know. A run where half the stages are parked still ends with a working local configuration and a clear list of what is missing.
| Stage | Decides |
|---|---|
| 1 | Preflight — toolchain, .env, containers |
| 2 | Deployment topology — load balancer, or an instance on its own elastic IP |
| 3 | Rate limiting — window, allowance, or off |
| 4 | Public surface — NODE_ENV, PORT, SELF_URL, CORS_ORIGINS, Swagger |
| 5 | Database — DATABASE_URL or the discrete DB_* set |
| 6 | Auth — JWT secret and expiry, Google OAuth, Auth0 |
| 7 | Redis — keep it, or remove cache / queues |
| 8 | Email — CONSOLE, SES, SendGrid or Resend |
| 9 | Cloud storage — the S3 block, and whether the default controller stays |
| 10 | Push notifications — Expo, and the same controller question |
| 11 | Analytics — CONSOLE or PostHog |
| 12 | Observability — OTLP endpoint, or tracing off |
| 13 | Reference domain module — keep or delete src/spaceship/ |
| 14 | Submit — one confirmation, then everything is applied |
Stage 2 is the one worth knowing about before you start, because it is the
answer the rest lean on. Behind a load balancer — ECS, Elastic Beanstalk, an
ALB, nginx, Cloudflare — the app never sees the client, so TRUST_PROXY has to
name the hop count or every request looks like it came from the proxy and the
whole deployment shares one rate-limit bucket. On an instance reached directly
on its own elastic IP the same setting is a hole: with it on, a client sends
its own X-Forwarded-For and decides what req.ip returns, which is what the
limiter keys on. Off is the correct setting there, not the lazy one. The
follow-up — one instance or several — decides whether the in-memory throttler
counters are good enough, since N instances allow N times the configured limit.
The security headers need no decision and the wizard says so rather than
offering one: src/main.ts applies helmet() with its defaults, first in the
middleware stack, and src/swagger.bootstrap.unit.spec.ts fails if the docs
page ever needs something that policy does not allow.
You can stop at any stage and re-run it later; the wizard keeps its answers in
a scratch sheet outside the repository, and re-running it against a configured
.env offers your current values as the defaults.
This project needs PostgreSQL and Redis running locally. Start both with:
docker-compose up -d # postgres, redis and jaeger
pnpm run db:migration:run # creates the schema on a fresh databaseRedis backs the BullMQ background job queues: src/app.module.ts wires both
the producer and the consumer adapter against it, and the reference domain
module ships one handler — src/spaceship/notification/, which emails several
employees after a spaceship is created and registers itself with
QueueConsumerModule.forFeature. Delete that module and the brokers stay
wired with nothing consuming them. See REDIS_HOST / REDIS_PORT /
REDIS_PASSWORD in .env.example. The app depends on Redis at runtime, not
just in tests.
Once it is up, GET /health tells you whether it found both:
$ curl -s localhost:5000/health | jq .data.info
{ "database": { "status": "up" }, "cache": { "status": "up" } }A 503 there means a dependency is missing, not that the app is broken — see
src/health/README.md.
Swagger is at /api, and it is gated: SWAGGER_ENABLED defaults to false
when NODE_ENV=PROD and true everywhere else, so the full API surface is not
published in production by default. Set it explicitly to serve docs from a
prod-like environment — that is why it is a flag rather than a bare NODE_ENV
check, since the alternative is lying about NODE_ENV, which would also
re-enable the CORS_ORIGINS wildcard.
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod# unit tests
$ pnpm run test
# unit tests + the coverage floor — what CI runs
$ pnpm run test:covpnpm run test:e2e exists but proves nothing. test/app.e2e-spec.ts is
24 lines of unmodified Nest scaffold: it boots the whole AppModule and
expects 'Hello World!' on GET /, so it needs a live database and Redis and
runs nowhere — not locally by default, and not in CI. This is accepted
debt, recorded deliberately rather than papered over: a green boilerplate
e2e run would be worse than none. Closing it means either writing real e2e
specs with postgres and redis services in bitbucket-pipelines.yml, or
deleting the file, test/jest-e2e.json and the script. Do not half-fix it.
These are the five commands bitbucket-pipelines.yml's test-build step runs,
in this order. They also run on staging and master before the deploy step,
so a merge is proved as merged, not just as a pull-request source.
$ pnpm run docs:check # every CLAUDE.md: map entry, sections, README sibling
$ pnpm run modularity:check # module import graph vs. the recorded baseline
$ pnpm run lint:ci # eslint WITHOUT --fix, so formatting drift fails
$ pnpm run test:cov # jest + the coverage floor
$ pnpm run build # nest buildTwo of those differ from what you would reach for locally, and both differences are the point:
lint:ci, neverlint.lintcarries--fix, so running it in a pipeline repairs formatting drift instead of failing on it. Usepnpm run lintwhile you work,pnpm run lint:cito predict CI.test:cov, nevertest. ThecoverageThresholdinpackage.jsonis a floor, and Jest only enforces it when coverage is actually collected. Under plainpnpm testthe threshold is inert. The floor today is 95% statements, 88% branches, 94% functions, 95% lines, measured just under the real numbers so it fails on a regression rather than on ambition.
collectCoverageFrom excludes main.ts, app.module.ts,
src/database/data-source.ts, the migrations and every mocks/ directory —
bootstrap, composition root, the TypeORM CLI entry point, generated schema and
test doubles respectively. Everything else counts, including files that sit at
0% and drag the average down; that is information, not noise.