Templates
The 10 axil create templates in AxilJS 0.3.6: REST, chat, jobs, webhooks, AI, SaaS, microservice, dashboard, high-scale.
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:
--template cannot be combined with --db, --auth, --ai, --ws or --queue: a template defines its own stack.
| Category | Template id | Title | Port | Tests |
|---|---|---|---|---|
| Start | minimal | Minimal API | 3000 | 13 |
| APIs | rest-api | REST API | 3001 | 35 |
| APIs | saas-api | SaaS API | 3005 | 39 |
| Realtime | realtime-chat | Realtime Chat | 3002 | 30 |
| Realtime | live-dashboard | Live Dashboard | 3008 | 21 |
| Background | background-jobs | Background Jobs | 3003 | 22 |
| Background | webhook-receiver | Webhook Receiver | 3007 | 23 |
| AI | ai-assistant | AI Assistant | 3004 | 36 |
| Production | microservice | Resilient microservice | 3006 | 18 |
| Production | high-scale-api | High-scale API | 3009 | 17 |
What every template contains
axil create writes the template's files plus a shared shell around them:
package.json: ESM ("type": "module"), scriptsdev(axil run),build(tsc),start(node dist/main.js),test(axil test) plus any template scripts; devDependencies@axiljs/cli,@axiljs/studio,@axiljs/testing,typescriptand@types/nodetsconfig.json: strict,module: Node16,experimentalDecorators,src/todist/.gitignore,.env.example,README.mdsrc/main.ts(loads.env, builds the app, listens, shuts down gracefully) and usually asrc/app.tsfactory, so tests can drivecreateApp()without opening a portsrc/config.ts: typed configuration withdefineConfigsrc/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)opensDATABASE_URLwithcreateConnectionfrom@axiljs/orm, builds every SQL store withcreateSqlStores(fromConnection(db))from@axiljs/stores, creates the tables withensureSchema()(axil_rate_limits,axil_idempotency,axil_cache,axil_locks, …) and installs them into@axiljs/runtimewithuseStores(stores). Itsclose()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 underaxil run). It is loaded with a dynamicrequireonly whenNODE_ENVis notproduction, because@axiljs/studiois 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_URL | Use |
|---|---|
sqlite:./shared-state.db (default) | One machine: processes on one host share the file |
postgres://user:pass@host:5432/db | Several servers (npm install pg) |
mysql://user:pass@host:3306/db | MySQL 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.
The smallest useful AxilJS service, built on @axiljs/core, @axiljs/config and @axiljs/validation.
- Typed
.envconfig withdefineConfig(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
| Method | Path | Description |
|---|---|---|
| GET | / | Service name, version and endpoints |
| GET | /health | Liveness: status, uptime, timestamp |
| GET | /hello/:name | Greeting; name is letters only (422 otherwise) |
| POST | /echo | Echo 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.
Products owned by users, on @axiljs/orm, @axiljs/auth, @axiljs/validation and @axiljs/config with better-sqlite3.
- ORM
@Entitymodels andBaseRepositorysubclasses on SQLite; migrations applied at startup (and vianpm run migrate,migrate:status,migrate:down) GET /productsfilters (q,category,minPrice,maxPrice,ownerId), sorts (name,price,createdAt,-prefix for descending) and paginates (page,perPage1–100) with validated query strings, answered withres.paginated- Register/login with scrypt password hashes and HS256 JWTs; writes need a Bearer token and are owner-or-admin
JWT_SECRETis required: the app refuses to start without one- Tests run on an isolated
:memory:database per file;dev.dbis never touched
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | / | Service name, version, endpoints | |
| GET | /health | Liveness plus a database ping (503 when down) | |
| POST | /auth/register | Create an account, returns a token | |
| POST | /auth/login | Exchange email/password for a token | |
| GET | /auth/me | Bearer | The current user |
| GET | /products | List: filter, sort, paginate | |
| GET | /products/:id | One product | |
| POST | /products | Bearer | Create; the caller becomes the owner |
| PATCH | /products/:id | owner or admin | Partial update |
| DELETE | /products/:id | owner or admin | Delete (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.
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 theX-Tenant-IDheader or the subdomain and rejects unknown or suspended tenants- Per-plan feature flags (
FeatureFlagManager), quotas on projects, users and daily API calls (QuotaManager, 429QUOTA_EXCEEDED) and a per-tenant rate limit (tenantRateLimiter(), 429RATE_LIMIT_EXCEEDED) - JWTs carry
tenantId,roleandpermissions; a token from another tenant gets 403 and is audited - Roles
admin,member,viewer; plansfree,pro,enterprise(editsrc/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)
| Method | Path | Requires | Description |
|---|---|---|---|
| POST | /api/auth/register | tenant | First account of a tenant becomes its admin |
| POST | /api/auth/login | tenant | Token with tenantId, role, permissions |
| GET / POST | /api/projects | projects:read / projects:write | List or create (projects quota) |
| GET / DELETE | /api/projects/:id | projects:read / projects:delete | One project; delete is audited |
| GET | /api/tenant | any member | Tenant, plan, features, quota usage |
| GET / POST | /api/tenant/members | members:read / members:invite | List or invite members (users quota) |
| PUT | /api/tenant/plan | role admin | Change plan (stand-in for a billing webhook) |
| GET | /api/tenant/audit | audit:read | This tenant's audit events |
| GET | /api/tenant/analytics | analytics:read + plan feature | Pro 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.
A chat server on @axiljs/websocket and @axiljs/core, with a browser client in public/index.html (no build step).
WSServerrooms 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
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | / | Browser client | |
| GET | /api | Service name, version and endpoints | |
| GET | /health | Liveness: status, uptime, room count | |
| POST | /api/token | Demo sign-in { "name": "Ada" } (when DEMO_LOGIN is on) | |
| GET | /api/rooms | Bearer | Rooms with online and message counts |
| GET | /api/rooms/:room/messages | Bearer | History, oldest first (?limit=1..500) |
| GET | /api/rooms/:room/members | Bearer | Users online in the room |
| GET | /ws | token | WebSocket 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.
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
/metricswith HTTP metrics fromobservabilityMiddlewareplus custom business counters - Liveness and readiness probes with
HealthChecker(event loop, memory, collector) - Dashboard in
public/index.html: vanilla JS and SVG sparklines
| Method | Path | Description |
|---|---|---|
| GET | / | The dashboard |
| GET | /events | SSE stream of stats events |
| GET | /api/stats | Latest snapshot as JSON |
| POST | /api/orders | Record an order { amount, channel? } |
| POST | /api/signups | Record a sign-up |
| GET | /metrics | Prometheus text format |
| GET | /health, /health/live, /health/ready | Health checks and probes |
| GET | /api | Service name, version and endpoints |
Background
Background Jobs
background-jobs · port 3003 · API + workers: queued jobs, retries, cron, events.
Built on @axiljs/queue, @axiljs/events, @axiljs/validation and @axiljs/config.
POSTenqueues 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
EventBusand an@OnEventsubscriber - An opt-in cron
Scheduler(RUN_SCHEDULER=true) withcleanup-finished-jobsanddaily-signups-report; the tasks only enqueue jobs, so the work gets retries and events too
| Method | Path | Description |
|---|---|---|
| GET | /health | Liveness plus queue counts |
| POST | /jobs/welcome-email | Enqueue { email, name } (202) |
| POST | /jobs/reports | Enqueue { kind, rows }; reports progress (202) |
| GET | /jobs | Recent jobs; ?status=failed etc. |
| GET | /jobs/:id | Status, progress, attempts, result or error |
| POST | /jobs/:id/retry | Re-enqueue a failed or cancelled job |
| DELETE | /jobs/:id | Cancel a pending, delayed or running job |
| GET | /events | Recent job events seen by the subscriber |
| GET | /schedule | Cron 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.
Providers POST events to /webhooks/:source. Built on @axiljs/queue, @axiljs/security, @axiljs/validation and @axiljs/config. Each delivery is:
- rate limited per source (
rateLimit, 429), - authenticated with HMAC-SHA256 over the raw request body, compared with
crypto.timingSafeEqual, - checked for freshness: the signed timestamp must be within
WEBHOOK_TOLERANCE_SEC(default 300), so captured requests cannot be replayed, - deduplicated: an event id already seen from that source is acknowledged (200) but not processed again,
- acknowledged fast with 202, then processed on a retrying queue;
GET /deliveriesshows 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.
| Method | Path | Description |
|---|---|---|
| GET | /health | Liveness plus queue counts |
| POST | /webhooks/:source | Receive a signed event (202, or 200 for a duplicate) |
| GET | /deliveries | Recent deliveries (?status=&source=&limit=) |
| GET | /deliveries/:id | One delivery, including its payload |
| POST | /deliveries/:id/retry | Re-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.
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 /documentschunks, embeds and stores text withRAGPipeline+VectorStore; answers return the chunks they used assources - 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_PROVIDER | Key variable | Default model (AI_MODEL overrides) |
|---|---|---|
anthropic (default) | ANTHROPIC_API_KEY | claude-sonnet-5-5 |
openai | OPENAI_API_KEY | the @axiljs/ai default |
gemini | GEMINI_API_KEY | the @axiljs/ai default |
ollama | none (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.
| Method | Path | Description |
|---|---|---|
| GET | / | Service info, provider, model and endpoints |
| GET | /health | Liveness |
| POST | /chat | Reply as JSON with sessionId, sources, usage |
| POST | /chat/stream | Same, streamed as SSE: start, delta…, done |
| GET / DELETE | /sessions/:id | Read or forget a session's history |
| POST / GET | /documents | Ingest text for RAG / list documents |
| DELETE | /documents/:id | Remove a document and its chunks |
| POST | /agent | Run the tool-using agent on a task |
Production
Resilient microservice
microservice · port 3006 · Circuit breaker, retries, metrics, tracing and probes.
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 wrapsretry()(exponential backoff with jitter), which wrapswithTimeout()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 W3Ctraceparentforwarded 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-downstreamstarts it on port 4000 for manual testing
| Method | Path | Description |
|---|---|---|
| GET | / | Service name, version and endpoints |
| GET | /api/quotes/:symbol | Quote from pricing, or last known while the circuit is open |
| GET | /health/live | Liveness |
| GET | /health/ready | Readiness: circuit and shutdown state |
| GET | /metrics | Prometheus text format |
High-scale API
high-scale-api · port 3009 · Cluster on every core, capacity plan, runtime decorators.
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.tscallsserve()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, callswireAll()and buildscreateApp(config); the drain closes the app, then the stores and the connectiononPrimary: () => installClusterEventRelay()runs once in the primary before the workers fork, so anEventBuscreated withnew 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,@tCacheor@tLockyou add counts, caches and locks once across all workers; see Shared runtime state axil.scaling.jsonin 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 byserve(),axil capacityandaxil deployAXIL_WORKERSoverridesvertical.workers;.env.examplesetsAXIL_WORKERS=1sonpm run devruns one process@tAudit,@tRetryand@tTimeouton service methods are executed bywire()from@axiljs/runtime(TimeoutErrormaps to 504, transient errors to 503)requestContext()gives every request an id readable anywhere withgetContext();redactResponses()applies@tRedactso 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 thataxil.scaling.jsonis valid
| Method | Path | Description |
|---|---|---|
| GET | / | Service name, version, worker pid |
| GET | /health/live | Liveness (used by the axil deploy manifest) |
| GET | /health/ready | Readiness (used by the axil deploy manifest) |
| GET | /api/users?limit=20 | Users, redacted |
| GET | /api/users/:id | One user: audited, retried, 250 ms deadline |
| GET | /api/users/:id/activity | Recent activity: audited, 300 ms deadline |
Run on all cores:
Then plan capacity from the real route:
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
- Quick Start: the full create flow
- Capacity: check a project against its scaling target
- Project Commands:
create,run,test,deployand more
Was this page helpful?