Please bump the version in package.json and add description of changes into CHANGELOG.md when making changes.
When synchronizing services built with the template with the upstream changes, please bump the version in package.json to reflect the step up to which the changes are synchronized.
node-service-template provides a "battery-included" starter template for building enterprise Node.js webservices.
It comes with the following out-of-the-box:
- fastify as a basis for the general web application skeleton;
- Modular, domain-driven structure that encourages separation of concerns;
- Server/app separation, for convenient bootstrapping in e2e tests;
- Global error handler;
- JSON-based, single line standardized logging;
- Automatic population of
req.idfor incoming requests based onx-request-idheader, or generation of new UUID if none is set, for the purposes of distributed tracing.
Mechanisms:
- Type-safe config management;
- Dependency injection (using awilix);
- Scheduling (using toad-scheduler and redis-semaphore);
- Type-safe message queue handling, using message-queue-toolkit framework;
- Type-safe dependency mocking for tests;
Scaffolding:
- Periodic in-memory jobs;
- Durable enqueued Redis jobs;
- API client, using opinionated high-performance backend client, based on undici
- AWS configuration loading
Basic building block examples:
- Repository (using drizzle);
- Domain service;
- Controller;
- Route;
- Schema (published independently as
@node-service-template/api-contracts); - e2e test;
Plugins:
- JWT plugin (using @fastify/jwt);
Scripts:
- Generate OpenAPI specification from your route definitions;
- Validate your OpenAPI specification;
- GenerateJwt generate jwt for dev usage.
Service template also comes with a curated set of plugins installed:
@fastify/helmet(security headers)@fastify/swagger(OpenAPI specification generation)@fastify/awilix(dependency injection)@fastify/schedule(scheduling background jobs)@fastify/auth(authentication)@scalar/fastify-api-reference(OpenAPI specification website)fastify-graceful-shutdown(handlingSEGTERMgracefully)fastify-no-icon(avoiding warnings when sending GET calls via browser)@lokalise/fastify-extras->metricsPlugin(exposing Prometheus metrics)@lokalise/fastify-extras->requestContextProviderPlugin(storing requestId in AsyncLocalStorage and populating requestContext on request)@lokalise/observability->OpenTelemetryTransactionManager(creating custom OpenTelemetry spans for background jobs)@lokalise/observability->BugsnagErrorReporter(reporting errors to BugSnag)@lokalise/fastify-extras->amplitudePlugin(tracking events in Amplitude)@lokalise/fastify-extras->commonHealthcheckPlugin(registering public healthchecks)
Note that some of the fastify-extras plugins may not be relevant for you (e. g. if you are not using Prometheus, New Relic or Bugsnag). In that case you should remove the plugins and delete everything that breaks when you attempt to build the project.
We recommend you to create your own @your-org/fastify-extras package and create your own mix of vendor plugins that
are relevant for the technological stack of your organization, and replace @lokalise/fastify-extras with it.
apps/service/ the service: source, tests, scripts, Dockerfile, docker-compose.yml, env files
packages/api-contracts/ API contracts, published to npm
package.json workspace-wide scripts and tooling (Turborepo, Biome)
turbo.json task graph: build, lint and test:ci build workspace dependencies first
biome.jsonc shared Biome config, extended by each app and package
Keeping the service in apps/ the same way the contracts live in packages/ means adding another
app (a UI, a worker) needs no restructuring, and the root only holds repository-wide config.
The root scripts run every app and package through Turborepo, building workspace dependencies first and caching the results:
| Command | What it does |
|---|---|
pnpm run build |
Builds the contracts, then the service |
pnpm run dev |
Builds the contracts, then starts the service in watch mode |
pnpm run lint |
Lints every app and package against freshly built contracts |
pnpm run test:ci |
Starts each app's Docker stack, applies test migrations, runs the tests with coverage and stops the stack |
The rest of the commands in this README are service scripts. Run them from apps/service, or from
the root with pnpm --filter @node-service-template/service run <script>.
-
Make sure your node version is compatible with the requirements in package.json. We are working with
node >= 24and recommend using a version manager, such as nvm, to manage multiple Node versions on your device if needed. -
Install pnpm (this project uses pnpm as its package manager — the exact version is pinned in the
devEngines.packageManagerfield of package.json, and a mismatch hard-fails). Corepack is deliberately not used; install pnpm directly:npm install -g pnpm@12.16.1
-
Install all project dependencies:
pnpm install
This is a pnpm workspace run with Turborepo. The service lives under
apps/serviceand the publishable API contracts underpackages/api-contracts. The service consumes the contracts via@node-service-template/api-contracts(workspace:*). The repository root holds only workspace-wide config and tooling. See Repository structure. -
Optionally create an
apps/service/.env.development.localfile for secrets and anything you want to change locally. The start and db scripts load .env.development first and.env.development.localon top, so the service runs without it, and it only needs the values you override. -
Launch all the infrastructural dependencies locally:
pnpm run docker:start:dev
This starts PostgreSQL, Redis, RabbitMQ, and fauxqs (local SQS/SNS emulator).
- Database is initialized via scripts/db/init-dbs.sh.
- SQS/SNS queues, topics, and subscriptions are seeded from scripts/fauxqs-init.json. The service only locates them, see SNS/SQS resources.
In tests, fauxqs runs as an embedded library (no Docker required) and is seeded by test/FauxqsHelper.ts.
-
Run migrations to synchronize your database schema with defined models:
pnpm run db:apply-migrations
-
To run application:
pnpm run dev
Turborepo builds the API contracts first, then starts the service in watch mode.
NOTE: By default all calls to the
node-templateapp will require a valid JWT token, hence authentication errors when running the application are expected if you haven't yet followed the steps in Create jwt for dev usage.
We use Drizzle as convenient mechanism for building queries.
In order to automatically generate a new migration,
- Edit an existing schema file or add a new one to src/db/schema;
- Run
node --run db:generate-migrations -- --name {migrationName}, wherecustomNameis a short message describing your change separated by underscores (_); - Run
node --run db:apply-migrationsto apply your new migration.
To remove a migration that has not been applied anywhere, delete its directory under src/db/migrations.
Before running your tests, make sure to run
node --run test:migrateTo initialize your test database and/or apply your latest schema changes.
The file names follow the Vite convention: one file
per mode, and a gitignored .local file on top of it for your own overrides. The schema defaults in
src/infrastructure/config.ts take the place of Vite's generic
.env. There is no .env or .env.local, because Vite loads those in every mode, tests included.
| File | Committed | Read by | Purpose |
|---|---|---|---|
.env.development |
yes | start, db and script commands | Local development values (localhost hosts, local credentials). Never read by tests or deployed environments. |
.env.development.local |
no | start, db and script commands, on top of .env.development |
Your secrets and personal overrides for local development. Optional. |
.env.test |
yes | tests (test/envSetupHook.ts), test:migrate, Docker healthcheck |
Every variable the test suite runs with: test database, in-process fakes, vendors switched off. |
.env.test.local |
no | tests and test:migrate, on top of .env.test |
Your personal overrides for test runs, for example a database on another port. Optional. |
.env.docker-test |
yes | scripts/docker-healthcheck-test.sh | Overrides on top of .env.test for the container healthcheck. |
A variable that needs a value in every environment gets a schema default, set to the production
value. A variable that has a sensible local value but must be set explicitly in deployed
environments (a hostname, a connection URL) has no schema default and goes in .env.development
and .env.test, so a missing value stops the service from starting instead of pointing it at
localhost.
All supported variables, with their defaults, are documented in docs/environment-variables.md, generated from the config schema.
getConfig() enables envase's emptyStringAsUndefined, so an empty value (KEY=) counts as unset: the schema default applies, optional variables stay undefined and required ones fail validation.
The service never creates SNS/SQS resources. Consumers built on AbstractSnsSqsConsumer only locate their topic, queue and subscription, and the service fails to start when one is missing. The one thing a consumer still writes is its subscription filter policy, derived from the message types its handlers accept.
Every topic, queue and subscription must therefore exist before the service starts:
- Deployed environments: topics, queues, DLQs, queue policies and subscriptions are declared in
Terraform in
infra/<env>/sns-sqs.tf, using thespacelift.io/lokalise/tf-mod-aws-sns-sqs/defaultmodule. - Local development and PR environments: the shared fauxqs is seeded from the
init.jsonoflokalise/dev-localstack. This repository'sdocker composefauxqs is seeded from scripts/fauxqs-init.json. - Tests: the in-process fauxqs is seeded by test/FauxqsHelper.ts.
You can access OpenAPI specification of your application, while it is running, by opening /documentation
Validation uses zod 4.5. Schemas that are parsed at runtime (API contracts, message
payloads, job payloads, database row schemas) are wrapped in z.compile(), which returns a clone
backed by an ahead-of-time compiled parser. Valid input takes the compiled path; invalid input falls
back to the regular parser, so error reporting and generated JSON Schema are unchanged.
Two rules when adding schemas:
- Compile the final schema.
.extend(),.omit(),.refine()and friends applied to a compiled schema return an uncompiled one. - Skip
z.compile()for schemas parsed once per process (environment config, CLI arguments). The compilation step costs more than the single parse saves.
The alternative is the global import 'zod/compile' side-effect import, which compiles every schema
constructed afterwards on first parse. This template uses explicit calls instead, so compilation does
not depend on module evaluation order and behaves the same under vitest as it does in src/server.ts.
Errors are modelled with @lokalise/errors.
Client-facing errors are PublicError subclasses, internal ones InternalError subclasses. Every class
carries a literal code, and public errors add an ErrorType that determines the HTTP status.
- Public error definitions (
definePublicError()) live in the api-contracts package, next to the contracts that reference them viamergeErrorSchemasByStatusCode(). The error payload is therefore part of the contract and generated OpenAPI spec, and clients can parse it with the same schema. - The owning module binds each definition to a class, e.g.
UserNotFoundError.ts, and throws it from its
services. Match errors with the static
isInstance()guard, notinstanceof. - The global error handler turns a
PublicErrorintoerror.httpStatusCodepluserror.toPayload(), and reports and logs anything mapped to a 5xx.
There is an OpenTelemetry integration included, using the gRPC exporter. See environment variable configuration for the details on configuring it.
It should work out-of-the-box for all incoming HTTP requests, as long as correct exporter URL is configured.
Continuous CPU, wall-clock and heap profiling with Grafana Pyroscope is wired in through @lokalise/pyroscope-profiling: the profiler starts in serverInternal.ts and pyroscopeProfilingPlugin labels every request's samples with its route. It is off unless PYROSCOPE_ENABLED=true, and never on under NODE_ENV=test.
perf/ holds a local load-test stack built on it: the service as a host process, its datastores in containers, k6 driving it, a database probe counting what each run cost in statements, and Pyroscope profiling it on request.
node --run perf:run:smoke # up, one pass per journey, down
node --run perf:run -- --profiling --keep # up, 60s of load, profiled, left up
node --run perf:analyze # where the time went
node --run perf:downSee perf/README.md for the full guide.
You have multiple options to ease your development:
- Comment
onRequesthook for JWT verification here - Generate a valid JWT with provided generateJwt script
-
Script requires public-private key pair encrypted with
RS256algorithm:mkdir -p ./scripts/keys && ssh-keygen -t rsa -b 4096 -m PEM -f ./scripts/keys/jwtRS256.key # Don't add passphrase openssl rsa -in ./scripts/keys/jwtRS256.key -pubout -outform PEM -out ./scripts/keys/jwtRS256.key.pub
-
Default file names are
jwtRS256.keyfor private key andjwtRS256.key.pubfor public key -
Run JWT generate script:
node --run jwt:generate
-
Your public key and token will be printed to console to make things easier. This is an example output:
Public key: -----BEGIN PUBLIC KEY-----||MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAt+2fSaw+mjbQpbPYcGv7||A0zs+P1yuCcM4LzTRpMmtXCoxCg3hwVZUM9HoxM4NxSga5A/jdHDhn1qEgQF38cX||N/wG+cRx1YfxDV2fSYxO9ouh+0J+uJaAXs0kWM0oAojrcMI4q1PcTeCFBvKDR+ei||Nu5auiRe7yrBfQTqsSmvEDRlnhUnF24CnNQPuzeN4Qe8LmcXuwimEyAi9Tf7hXBN||H31j+jnUfIq9Yy7EsbmZhW3aEmQlmR6RY/9g+IEzbpmBoYznYsxmvtODpay7n+NY||zWtOdtJC9eKDaOs3wYjDR0G9uHe00ZIBiNfZ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OQ-RhNSu28REd4Mp0xHySYsn0ukf4kZHPUoGbMIuIMg6WhVTsz7V4n0nd1iPIjBfJjWM5dDSZfQvg4whwO1jeaE4BXxpjeiFqxf_tOT1QM Verified payload: {"claim":"value","iat":1676958080} -
Copy your public key to
JWT_PUBLIC_KEYin your.env.development.localfile. Make sure to replace occurrences of||in your key with new lines -
Restart the application to load the new public key:
node --run start:dev
-
Use your token to authenticate through bearer authentication in your requests
-
Script will get all environment variables used in config.ts and validate that all are documented in docs
node --run docs:validate
On successful validation, the script will print a message to the console:
✅ All environment variables are documented!
If any variable is not documented you will see a list of undocumented ones:
❌ Missing documentation for the following environment variables:
- VARIABLE_NAME
- If you are running a service in a monorepo setup, it is launched in the background and you want to always force closing the service before attempting to restart, you can use
node --run free-ports, which will kill an application running on the predefined port (in an OS-independent way).
To create a new CLI command, create a new file in the scripts/cmd directory. The file should be self-executable and wrap its logic with cliCommandWrapper, which boots the app, parses and validates arguments, and handles logging, graceful shutdown, and exit codes.
To use arguments in your command, provide a zod schema to cliCommandWrapper(). CLI flags are derived from the schema itself — string, boolean, repeatable (array) and optional flags are supported, and the schema may end in .transform()/.pipe() to reshape flat flags into a nested args object. See docs/cli-commands.md for the full description of what is supported.
Create a new command in the scripts section of apps/service/package.json:
"scripts": {
"cmd:getUserImportJobs:dev": "node --env-file=.env.development --env-file-if-exists=.env.development.local scripts/cmd/getUserImportJobs.ts",
"cmd:getUserImportJobs:prod": "node scripts/cmd/getUserImportJobs.js",
}!!! Be aware of extensions and node / typescript execution commands in command paths, as development environment differs from non-development.
To run a command locally, use node --run {npmScriptName} -- {arguments}. Example:
node --run cmd:getUserImportJobs -- --queue=activeTo run a command in a run-command pipeline, use {npmScriptName} -- {arguments} as a command argument. Example:
cmd:getUserImportJobs -- --queue=active