Getting Started

Templates

The 10 axil create templates in AxilJS 0.3.6: REST, chat, jobs, webhooks, AI, SaaS, microservice, dashboard, high-scale.

18 min readUpdated DocumentationEdit this page
On this page21

axil create ships 10 ready-made applications. Each one is a complete, working service rather than an empty skeleton: real routes, validation, one JSON error shape, a README with endpoints, curl and PowerShell examples, a configuration table, and its own tests.

Success

Every generated project compiles under strict TypeScript ("strict": true) and ships its own passing test suite. Run it with npm test right after creating the project; no server, database or API key is needed.

Choosing and creating a template

Pick one interactively (step 2/4 of axil create), or name it with --template / -t:

Terminal
❯npx @axiljs/cli create my-api # browse the picker
❯npx @axiljs/cli create my-api --template rest-api # or name it directly
❯axil create chat -t realtime-chat --skip-install

--template cannot be combined with --db, --auth, --ai, --ws or --queue: a template defines its own stack.

CategoryTemplate idTitlePortTests
StartminimalMinimal API300013
APIsrest-apiREST API300135
APIssaas-apiSaaS API300539
Realtimerealtime-chatRealtime Chat300230
Realtimelive-dashboardLive Dashboard300821
Backgroundbackground-jobsBackground Jobs300322
Backgroundwebhook-receiverWebhook Receiver300723
AIai-assistantAI Assistant300436
ProductionmicroserviceResilient microservice300618
Productionhigh-scale-apiHigh-scale API300917

What every template contains

axil create writes the template's files plus a shared shell around them:

  • package.json: ESM ("type": "module"), scripts dev (axil run), build (tsc), start (node dist/main.js), test (axil test) plus any template scripts; devDependencies @axiljs/cli, @axiljs/studio, @axiljs/testing, typescript and @types/node
  • tsconfig.json: strict, module: Node16, experimentalDecorators, src/ to dist/
  • .gitignore, .env.example, README.md
  • src/main.ts (loads .env, builds the app, listens, shuts down gracefully) and usually a src/app.ts factory, so tests can drive createApp() without opening a port
  • src/config.ts: typed configuration with defineConfig
  • src/middleware/error-handler.ts: every thrown error becomes { "error": { "code", "message", "details"? } }; 500 messages are hidden in production

Every template binds to HOST=127.0.0.1 by default; set HOST=0.0.0.0 in containers.

Shared runtime state in multi-instance templates

saas-api and high-scale-api are set up to run as several instances. Since CLI 0.3.6 they add three files to the list above:

  • src/shared-state.ts: openSharedState(url) opens DATABASE_URL with createConnection from @axiljs/orm, builds every SQL store with createSqlStores(fromConnection(db)) from @axiljs/stores, creates the tables with ensureSchema() (axil_rate_limits, axil_idempotency, axil_cache, axil_locks, …) and installs them into @axiljs/runtime with useStores(stores). Its close() stops the stores' timers, then disconnects.
  • src/shared-state.test.ts: checks the driver chosen for each URL form and that the store tables are created on SQLite :memory:.
  • src/dev/studio-intent.ts: Studio's intent endpoint (GET /__axil/studio/intent, read by the Studio Intent view under axil run). It is loaded with a dynamic require only when NODE_ENV is not production, because @axiljs/studio is a devDependency; a production install without dev dependencies never touches it.

src/main.ts opens the shared state before the app is built, calls wireAll() after every module is imported so the t* decorators run, and closes the app and then the shared state on shutdown. The runtime dependencies gain @axiljs/orm, @axiljs/runtime, @axiljs/stores and better-sqlite3.

DATABASE_URLUse
sqlite:./shared-state.db (default)One machine: processes on one host share the file
postgres://user:pass@host:5432/dbSeveral servers (npm install pg)
mysql://user:pass@host:3306/dbMySQL 8 (npm install mysql2)

Anything that is not a postgres://, postgresql:// or mysql:// URL is treated as a SQLite file. Each template's README has a Running several instances section that lists what is still per process. See Stores.

Start

Minimal API

minimal · port 3000 · Routes, validation, CORS and tests; nothing else.

❯npx @axiljs/cli create my-api --template minimal
❯pnpm dlx @axiljs/cli create my-api --template minimal
❯yarn dlx @axiljs/cli create my-api --template minimal
❯bunx @axiljs/cli create my-api --template minimal

The smallest useful AxilJS service, built on @axiljs/core, @axiljs/config and @axiljs/validation.

  • Typed .env config with defineConfig (PORT, HOST, NODE_ENV, CORS_ORIGIN)
  • Validated routes; 404, 405 (method not allowed) and 422 come back as one JSON shape
  • CORS for a configurable origin (* or a comma-separated list)
  • Tests that never open a port
MethodPathDescription
GET/Service name, version and endpoints
GET/healthLiveness: status, uptime, timestamp
GET/hello/:nameGreeting; name is letters only (422 otherwise)
POST/echoEcho a validated JSON body

Files: src/app.ts, src/app.test.ts, src/config.ts, src/main.ts, src/middleware/error-handler.ts.

APIs

REST API

rest-api · port 3001 · CRUD on SQLite with JWT auth, validation and paging.

❯npx @axiljs/cli create shop --template rest-api
❯pnpm dlx @axiljs/cli create shop --template rest-api
❯yarn dlx @axiljs/cli create shop --template rest-api
❯bunx @axiljs/cli create shop --template rest-api

Products owned by users, on @axiljs/orm, @axiljs/auth, @axiljs/validation and @axiljs/config with better-sqlite3.

  • ORM @Entity models and BaseRepository subclasses on SQLite; migrations applied at startup (and via npm run migrate, migrate:status, migrate:down)
  • GET /products filters (q, category, minPrice, maxPrice, ownerId), sorts (name, price, createdAt, - prefix for descending) and paginates (page, perPage 1–100) with validated query strings, answered with res.paginated
  • Register/login with scrypt password hashes and HS256 JWTs; writes need a Bearer token and are owner-or-admin
  • JWT_SECRET is required: the app refuses to start without one
  • Tests run on an isolated :memory: database per file; dev.db is never touched
MethodPathAuthDescription
GET/Service name, version, endpoints
GET/healthLiveness plus a database ping (503 when down)
POST/auth/registerCreate an account, returns a token
POST/auth/loginExchange email/password for a token
GET/auth/meBearerThe current user
GET/productsList: filter, sort, paginate
GET/products/:idOne product
POST/productsBearerCreate; the caller becomes the owner
PATCH/products/:idowner or adminPartial update
DELETE/products/:idowner or adminDelete (204)

After creating: set JWT_SECRET in .env to 32+ random characters.

SaaS API

saas-api · port 3005 · Multi-tenant API: plans, flags, quotas, RBAC, audit log.

❯npx @axiljs/cli create saas --template saas-api
❯pnpm dlx @axiljs/cli create saas --template saas-api
❯yarn dlx @axiljs/cli create saas --template saas-api
❯bunx @axiljs/cli create saas --template saas-api

Tenants share one deployment but never each other's data. Built on @axiljs/cloud, @axiljs/auth, @axiljs/events, @axiljs/validation, @axiljs/stores, @axiljs/runtime and @axiljs/config.

  • multiTenancy() resolves the tenant from the X-Tenant-ID header or the subdomain and rejects unknown or suspended tenants
  • Per-plan feature flags (FeatureFlagManager), quotas on projects, users and daily API calls (QuotaManager, 429 QUOTA_EXCEEDED) and a per-tenant rate limit (tenantRateLimiter(), 429 RATE_LIMIT_EXCEEDED)
  • JWTs carry tenantId, role and permissions; a token from another tenant gets 403 and is audited
  • Roles admin, member, viewer; plans free, pro, enterprise (edit src/tenancy/plans.ts)
  • Audit events on the global event bus; storage is in memory with the tenant id as the first argument of every store method
  • The runtime's rate-limit, idempotency, cache and lock state lives in DATABASE_URL (SQLite by default) through @axiljs/stores, so several instances share it; see Shared runtime state
  • Studio's intent endpoint is mounted in development only
  • Seeded tenants to try: acme (pro), globex (free), initech (suspended)
MethodPathRequiresDescription
POST/api/auth/registertenantFirst account of a tenant becomes its admin
POST/api/auth/logintenantToken with tenantId, role, permissions
GET / POST/api/projectsprojects:read / projects:writeList or create (projects quota)
GET / DELETE/api/projects/:idprojects:read / projects:deleteOne project; delete is audited
GET/api/tenantany memberTenant, plan, features, quota usage
GET / POST/api/tenant/membersmembers:read / members:inviteList or invite members (users quota)
PUT/api/tenant/planrole adminChange plan (stand-in for a billing webhook)
GET/api/tenant/auditaudit:readThis tenant's audit events
GET/api/tenant/analyticsanalytics:read + plan featurePro and enterprise only

Plus GET / and GET /health. After creating: set JWT_SECRET in .env, and point DATABASE_URL at PostgreSQL before running several servers.

Note

Still per process in this template: the stores in src/data/*, QuotaManager and tenantRateLimiter(), whose counters are internal. Move the data to a database before running several instances. For a shared per-tenant limit, the template README suggests rateLimit({ store: stores.rateLimit, keyGenerator: req => 'tenant:' + req.locals?.tenant?.id }) from @axiljs/security.

Realtime

Realtime Chat

realtime-chat · port 3002 · WebSocket rooms, presence, history and JWT auth.

❯npx @axiljs/cli create chat --template realtime-chat
❯pnpm dlx @axiljs/cli create chat --template realtime-chat
❯yarn dlx @axiljs/cli create chat --template realtime-chat
❯bunx @axiljs/cli create chat --template realtime-chat

A chat server on @axiljs/websocket and @axiljs/core, with a browser client in public/index.html (no build step).

  • WSServer rooms on the same port as the HTTP API, at /ws
  • JWT auth on connect: ?token=<jwt> during the handshake (403 when bad), or a first { "type": "auth", "token": "…" } message; anything else closes the socket with code 4401
  • Validated JSON frames (join, leave, message), presence events and per-room history in a ring buffer; frames over 16 KiB close the connection (1009)
  • Tests do real WebSocket round-trips on port 0
MethodPathAuthDescription
GET/Browser client
GET/apiService name, version and endpoints
GET/healthLiveness: status, uptime, room count
POST/api/tokenDemo sign-in { "name": "Ada" } (when DEMO_LOGIN is on)
GET/api/roomsBearerRooms with online and message counts
GET/api/rooms/:room/messagesBearerHistory, oldest first (?limit=1..500)
GET/api/rooms/:room/membersBearerUsers online in the room
GET/wstokenWebSocket upgrade

After npm run dev, open http://localhost:3002 in two browser windows and chat with yourself.

Live Dashboard

live-dashboard · port 3008 · SSE live metrics, Prometheus /metrics and health probes.

❯npx @axiljs/cli create dash --template live-dashboard
❯pnpm dlx @axiljs/cli create dash --template live-dashboard
❯yarn dlx @axiljs/cli create dash --template live-dashboard
❯bunx @axiljs/cli create dash --template live-dashboard

One process, three views of the same numbers, on @axiljs/observability and @axiljs/core.

  • A stats snapshot every second over Server-Sent Events (createSSE): requests/s, average and p95 latency, 5xx rate, heap/RSS, CPU, event-loop delay and business totals
  • Prometheus /metrics with HTTP metrics from observabilityMiddleware plus custom business counters
  • Liveness and readiness probes with HealthChecker (event loop, memory, collector)
  • Dashboard in public/index.html: vanilla JS and SVG sparklines
MethodPathDescription
GET/The dashboard
GET/eventsSSE stream of stats events
GET/api/statsLatest snapshot as JSON
POST/api/ordersRecord an order { amount, channel? }
POST/api/signupsRecord a sign-up
GET/metricsPrometheus text format
GET/health, /health/live, /health/readyHealth checks and probes
GET/apiService name, version and endpoints

Background

Background Jobs

background-jobs · port 3003 · API + workers: queued jobs, retries, cron, events.

❯npx @axiljs/cli create jobs --template background-jobs
❯pnpm dlx @axiljs/cli create jobs --template background-jobs
❯yarn dlx @axiljs/cli create jobs --template background-jobs
❯bunx @axiljs/cli create jobs --template background-jobs

Built on @axiljs/queue, @axiljs/events, @axiljs/validation and @axiljs/config.

  • POST enqueues a job and answers 202 with its id; workers run with concurrency, retries and backoff
  • Failed jobs are kept as dead letters and can be retried by id; running jobs can be cancelled
  • Job lifecycle events via EventBus and an @OnEvent subscriber
  • An opt-in cron Scheduler (RUN_SCHEDULER=true) with cleanup-finished-jobs and daily-signups-report; the tasks only enqueue jobs, so the work gets retries and events too
MethodPathDescription
GET/healthLiveness plus queue counts
POST/jobs/welcome-emailEnqueue { email, name } (202)
POST/jobs/reportsEnqueue { kind, rows }; reports progress (202)
GET/jobsRecent jobs; ?status=failed etc.
GET/jobs/:idStatus, progress, attempts, result or error
POST/jobs/:id/retryRe-enqueue a failed or cancelled job
DELETE/jobs/:idCancel a pending, delayed or running job
GET/eventsRecent job events seen by the subscriber
GET/scheduleCron tasks of this process

Warning

Cron needs a single owner. Every process that starts a Scheduler fires every task, so set RUN_SCHEDULER=true on exactly one instance. The queue is in memory: for several processes or durability, give the Queue a shared QueueStore.

Webhook Receiver

webhook-receiver · port 3007 · Signed webhooks: verify, dedupe, queue, retry.

❯npx @axiljs/cli create hooks --template webhook-receiver
❯pnpm dlx @axiljs/cli create hooks --template webhook-receiver
❯yarn dlx @axiljs/cli create hooks --template webhook-receiver
❯bunx @axiljs/cli create hooks --template webhook-receiver

Providers POST events to /webhooks/:source. Built on @axiljs/queue, @axiljs/security, @axiljs/validation and @axiljs/config. Each delivery is:

  1. rate limited per source (rateLimit, 429),
  2. authenticated with HMAC-SHA256 over the raw request body, compared with crypto.timingSafeEqual,
  3. checked for freshness: the signed timestamp must be within WEBHOOK_TOLERANCE_SEC (default 300), so captured requests cannot be replayed,
  4. deduplicated: an event id already seen from that source is acknowledged (200) but not processed again,
  5. acknowledged fast with 202, then processed on a retrying queue; GET /deliveries shows each delivery's state.

The signature header is Webhook-Signature: t=<unix seconds>,v1=<hex hmac>, where v1 is the HMAC of `${t}.${rawBody}` with the source's secret. Several v1= entries are accepted, which allows secret rotation. Secrets come from WEBHOOK_SECRETS as comma-separated source=secret pairs.

Note

Why the raw body: re-serialising parsed JSON changes whitespace and key order, so the HMAC would not match. src/webhooks/raw-body.ts keeps the exact body the built-in parser read in req.locals.rawBody, and verification uses that string.

MethodPathDescription
GET/healthLiveness plus queue counts
POST/webhooks/:sourceReceive a signed event (202, or 200 for a duplicate)
GET/deliveriesRecent deliveries (?status=&source=&limit=)
GET/deliveries/:idOne delivery, including its payload
POST/deliveries/:id/retryRe-queue a failed delivery

Try it: npm run dev, then npm run send-test-webhook in another terminal signs and sends a sample event.

AI

AI Assistant

ai-assistant · port 3004 · LLM chat, SSE streaming, RAG with sources and an agent.

❯npx @axiljs/cli create assistant --template ai-assistant
❯pnpm dlx @axiljs/cli create assistant --template ai-assistant
❯yarn dlx @axiljs/cli create assistant --template ai-assistant
❯bunx @axiljs/cli create assistant --template ai-assistant

An LLM behind a small, safe HTTP API on @axiljs/ai (no provider SDK), with @axiljs/security rate limits and @axiljs/validation.

  • Chat with per-session history, and token streaming over SSE (POST /chat/stream)
  • RAG: POST /documents chunks, embeds and stores text with RAGPipeline + VectorStore; answers return the chunks they used as sources
  • A tool-using Agent (calculator, document search, current time)
  • Provider errors map to 502; AI routes are rate limited per client IP
  • Tests inject a deterministic fake provider: no API key, no network

The provider is chosen with environment variables; the app refuses to start when the selected provider's key is missing:

AI_PROVIDERKey variableDefault model (AI_MODEL overrides)
anthropic (default)ANTHROPIC_API_KEYclaude-sonnet-5-5
openaiOPENAI_API_KEYthe @axiljs/ai default
geminiGEMINI_API_KEYthe @axiljs/ai default
ollamanone (OLLAMA_BASE_URL, default http://localhost:11434)llama3.2

Embeddings follow EMBEDDING_PROVIDER (default auto): the chat provider when it has an embeddings API, otherwise a built-in offline local embedder (used with Anthropic). Set EMBEDDING_PROVIDER=openai, gemini or ollama for semantic search.

MethodPathDescription
GET/Service info, provider, model and endpoints
GET/healthLiveness
POST/chatReply as JSON with sessionId, sources, usage
POST/chat/streamSame, streamed as SSE: start, delta…, done
GET / DELETE/sessions/:idRead or forget a session's history
POST / GET/documentsIngest text for RAG / list documents
DELETE/documents/:idRemove a document and its chunks
POST/agentRun the tool-using agent on a task

Production

Resilient microservice

microservice · port 3006 · Circuit breaker, retries, metrics, tracing and probes.

❯npx @axiljs/cli create quotes --template microservice
❯pnpm dlx @axiljs/cli create quotes --template microservice
❯yarn dlx @axiljs/cli create quotes --template microservice
❯bunx @axiljs/cli create quotes --template microservice

Serves stock quotes by calling a pricing service that may be slow, flaky or down. Built on @axiljs/circuit and @axiljs/observability.

  • Every downstream call runs through CircuitBreaker, which wraps retry() (exponential backoff with jitter), which wraps withTimeout() per attempt; only network errors, timeouts, 5xx and 429 are retried
  • While the circuit is open, the service answers with the last known quote
  • JSON logs with request ids, Prometheus /metrics (including the circuit state), and the W3C traceparent forwarded to the downstream call
  • Readiness reports the circuit state (503 while open, unless READINESS_FOLLOWS_CIRCUIT=false); on SIGTERM readiness turns 503 and in-flight requests drain
  • Tests use a fake pricing service that can be told to fail or slow down; npm run fake-downstream starts it on port 4000 for manual testing
MethodPathDescription
GET/Service name, version and endpoints
GET/api/quotes/:symbolQuote from pricing, or last known while the circuit is open
GET/health/liveLiveness
GET/health/readyReadiness: circuit and shutdown state
GET/metricsPrometheus text format

High-scale API

high-scale-api · port 3009 · Cluster on every core, capacity plan, runtime decorators.

❯npx @axiljs/cli create fast --template high-scale-api
❯pnpm dlx @axiljs/cli create fast --template high-scale-api
❯yarn dlx @axiljs/cli create fast --template high-scale-api
❯bunx @axiljs/cli create fast --template high-scale-api

Shows how an AxilJS service uses every core of a machine, how many machines it needs for a target, and how decorators become behaviour. Built on @axiljs/scale, @axiljs/runtime, @axiljs/stores, @axiljs/decorator and @axiljs/events.

  • src/main.ts calls serve() with an async factory: one worker process per core (node:cluster), crashed workers restarted with backoff, graceful drain on SIGTERM. Each worker opens the shared state, calls wireAll() and builds createApp(config); the drain closes the app, then the stores and the connection
  • onPrimary: () => installClusterEventRelay() runs once in the primary before the workers fork, so an EventBus created with new EventBus({ transport: new ClusterTransport() }) reaches every worker on the machine. The audit log stays on the per-worker global bus on purpose: each event is written once, by the worker that handled it
  • The runtime's rate-limit, idempotency, cache and lock state lives in DATABASE_URL (SQLite by default), so a @tRateLimit, @tIdempotent, @tCache or @tLock you add counts, caches and locks once across all workers; see Shared runtime state
  • axil.scaling.json in the project root holds the target (50,000 req/s, p99 50 ms), the worker shape and 3 to 10 instances of 4 CPU / 8 GB; it is read by serve(), axil capacity and axil deploy
  • AXIL_WORKERS overrides vertical.workers; .env.example sets AXIL_WORKERS=1 so npm run dev runs one process
  • @tAudit, @tRetry and @tTimeout on service methods are executed by wire() from @axiljs/runtime (TimeoutError maps to 504, transient errors to 503)
  • requestContext() gives every request an id readable anywhere with getContext(); redactResponses() applies @tRedact so password hashes and API keys never leave the API
  • Hot paths kept lean: no access log in production, everything built once in createApp(), and the Studio intent endpoint is absent in production
  • Tests drive createApp() in one process (the cluster is never forked in tests) and check that axil.scaling.json is valid
MethodPathDescription
GET/Service name, version, worker pid
GET/health/liveLiveness (used by the axil deploy manifest)
GET/health/readyReadiness (used by the axil deploy manifest)
GET/api/users?limit=20Users, redacted
GET/api/users/:idOne user: audited, retried, 250 ms deadline
GET/api/users/:id/activityRecent activity: audited, 300 ms deadline

Run on all cores:

Terminal
❯npm run build
AXIL_WORKERS=auto NODE_ENV=production npm start

Then plan capacity from the real route:

Terminal
❯axil capacity --url http://localhost:3009/api/users/u_1 --server-workers 4

The project ships an in-memory user store; axil capacity flags it (and other per-process state) in its multi-process readiness scan. Replace it with a database before running several workers or instances. See Scaling.

For several pods or servers, set a PostgreSQL DATABASE_URL (from a Secret) in the deploy manifest's env: list: the default SQLite file would be one per pod. If you add rateLimit() from @axiljs/security, give it store: new ClusterStore() and call installClusterRateLimitPrimary() in onPrimary (one machine), or store: stores.rateLimit (every server).

Custom

The Custom entry in the picker (or any of --db, --auth, --ai, --ws, --queue without --template) generates a modular starter with a users module, optional database and migrations. See Quick Start and Project Structure.

Next steps

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY