Docs / Introduction & Philosophy

Introduction to JSango

JSango is a production-grade, batteries-included TypeScript backend framework built on convention over configuration, expressive developer ergonomics, modern TypeScript type safety, and high-concurrency JavaScript runtimes (Node.js 20+ & Bun).

💡
Why JSango? In the TypeScript ecosystem, constructing an enterprise backend traditionally means assembling dozens of disjointed libraries for routing, ORM, migrations, authentication, 2FA, admin panels, background queues, AI agents, and telemetry. JSango solves this fragmentation by offering a cohesive, strictly typed monorepo ecosystem with zero runtime reflection overhead.

Core Principles

1. Strict Type Safety

100% strict TypeScript throughout with compile-time query checking, inferable schemas, and zero any.

2. Batteries Included

Built-in ORM, Multi-DB Drivers, Auto-Admin SPA, 2FA, AI Agent Runtime, Queues, and WebSockets.

3. Extreme Concurrency

Custom SegRadix Trie router executing >7,700,000 lookups/second with zero allocations on hot paths.

4. Security by Default

RFC 6238 TOTP 2FA, Scrypt password hashing, CSRF/CORS protections, and secure multi-device session management.


5-Minute Quickstart

Create a project, generate the database tables from the example model, and start the server.

1. Create a New Project

Terminal
npx jsango new my-backend
cd my-backend
npm install

The project uses SQLite (./db.sqlite3) out of the box on Node.js 22.13+, so no database server is needed. To use PostgreSQL or MySQL, set DATABASE_URL in .env (see Connecting a Database).

2. Define a Model

src/models/product.ts
import { defineModel, fields } from 'jsango';

export const Product = defineModel(
  'Product',
  {
    id: fields.id(),
    name: fields.string({ maxLength: 255 }),
    price: fields.decimal({ precision: 10, scale: 2 }),
    inStock: fields.boolean({ defaultValue: true }),
  },
  { table: 'products', timestamps: true }
);

3. Create the Tables

Terminal
npx jsango makemigrations   # writes migrations/<timestamp>_create_products.ts
npx jsango migrate          # creates the tables

4. Use It in Routes

src/index.ts
import { createApp } from 'jsango';
import { configureDatabase, db } from './database.js';
import { Product } from './models/product.js';

configureDatabase();                 // all models use the configured database
const app = createApp();

app.get('/api/products', () => Product.where('inStock', true).orderBy('name').get());
app.crud('/api/crud/products', Product);   // REST CRUD in one line (writes need access)

await db.verify();                   // fail fast if the database is unreachable
await app.listen(3000);

5. Start the Development Server

Terminal
npm run dev

Building with AI Assistants

jsango is ready for AI coding agents. Every project created with jsango new includes an AGENTS.md (read by Claude Code, Cursor, GitHub Copilot, Codex and others) that tells the agent to build with jsango's APIs instead of Express, Prisma or Passport, which API to use for each need, the project layout, the commands, and to check its work with tsc and migrate:check. A CLAUDE.md that imports it is added too.

WhatWhere
Add or refresh the rules in an existing projectnpx jsango ai:init (keeps your own AGENTS.md content; run again after upgrading)
MCP server for Claude Code, Cursor, VS Code (written to .mcp.json, .cursor/mcp.json, .vscode/mcp.json)npx jsango mcp: get_api (real signatures of your installed version), search_docs, run_check (type-check, migrations, tests with fix hints), report_issue. Runs locally, nothing to host.
Docs index for AI assistantsllms.txt
All guides in one file, to load into contextllms-full.txt
Found a bug or missing featurereport_issue removes secrets, .env values, emails and local paths, adds versions, searches for duplicates and gives a prefilled GitHub link. Nothing is submitted without you: you review it and press Submit.

Tip: start your prompt with "Use jsango (https://flutterbuddy1.github.io/jsango/llms.txt) to build…" when the project doesn't exist yet.


Recommended Project Structure

JSango enforces clean architectural layering while giving you flexibility:

Directory Layout
my-backend/
├── src/
│   ├── models/            # Declarative ORM models & relations
│   ├── routes/            # HTTP Route handlers & route groups
│   ├── middleware/        # Authentication, CORS & rate limit guards
│   ├── agents/            # Autonomous AI agents & custom tools
│   ├── workflows/         # Multi-agent orchestration workflows
│   ├── jobs/              # Background queue workers
│   ├── events/            # Strongly typed domain events
│   └── index.ts           # App bootstrap & server initialization
├── migrations/            # Version-controlled database migrations
├── jsango.config.ts       # Framework & multi-database configuration
├── .env                   # Environment variables
├── tsconfig.json          # Strict TypeScript configuration
└── package.json

Configuration & Environment

Runtime settings come from environment variables (.env is loaded by dotenv in the app and automatically by the CLI). jsango.config.ts tells the CLI where your database, models and migrations are:

jsango.config.ts
import { defineConfig } from 'jsango';
import { db } from './src/database.js';

export default defineConfig({
  database: db,               // a DatabaseManager, or { default, connections } config object
  models: './src/models',     // files/folders with defineModel() calls
  migrations: './migrations', // migration files directory
});
.env
DATABASE_URL=postgres://app:secret@localhost:5432/myapp
PORT=3000
JWT_SECRET=change-me
KeyDefaultPurpose
databasefrom DATABASE_URL / DATABASE_*Database used by migrate, db:status, …
models./src/modelsWhere models are imported from (recursive)
migrations./migrationsMigration files directory
envFile.envEnv file loaded first (existing variables win)

SegRadix Trie Router

JSango features a custom Segment Radix Trie router built for extreme throughput (>7.7M lookups/sec) and sub-millisecond route resolution.

Typed Route Parameters

Constrain parameters inline with built-in segment validators like :uuid, :int, and :slug:

Router Example
// Automatically validates UUID format before triggering handler
app.get('/api/v1/users/:id:uuid', async (ctx) => {
  const userId = ctx.request.params['id'];
  const user = await User.find(userId);
  return user ? ctx.response.json(user) : ctx.response.notFound();
});

Route Groups & Scoped Middleware

Route Groups
app.group('/api/v1/admin', (router) => {
  router.use(requireAdminAuth);
  router.get('/analytics', analyticsHandler);
  router.post('/settings', settingsHandler);
});

Request & Response Context

Every route handler receives an isolated RequestContext containing typed request data, headers, cookies, and high-performance response helpers:

src/routes/profile.ts
app.post('/api/users/profile', async (ctx) => {
  // Read parsed JSON body & query params
  const body = ctx.request.body;
  const query = ctx.request.query;

  // Read headers and cookies
  const authHeader = ctx.request.headers.get('Authorization');
  const sessionCookie = ctx.request.cookies.get('session_id');

  // Return standard JSON response with status
  return ctx.response.json({ success: true, user: body }, { status: 201 });
});

1-Line CRUD Generation

Generate RESTful endpoints (GET /, GET /:id, POST /, PUT|PATCH /:id, DELETE /:id) for any ORM model in one line, with pagination, search and filters. It is safe by default:

  • Reads are public, writes answer 403 until access allows them ('public' or middleware such as auth.required(), for all routes or per read / write / list|detail|create|update|delete).
  • No mass assignment: the primary key, timestamps, sensitive fields and privilege fields (isAdmin, isSuperuser, role, permissions...) are ignored in request bodies. Set writable to choose the fields yourself.
  • No leaks: fields named like password, secret, token, apiKey or hash are never returned (hidden adds more).
Secure CRUD Resource
import { createApp, model, fields, createAuth, schema, string } from 'jsango';

export const Article = model('Article', {
  id: fields.id(),
  title: fields.string({ maxLength: 200 }),
  content: fields.text(),
  published: fields.boolean({ defaultValue: false }),
}, { table: 'articles' });

const auth = createAuth({ secret: process.env.AUTH_SECRET!, users: userLookup });
const app = createApp();

// GET /api/articles, GET /api/articles/:id, POST, PUT/PATCH /:id, DELETE /:id
app.crud('/api/articles', Article, {
  access: { read: 'public', write: auth.required({ roles: ['editor'] }) },
  searchFields: ['title', 'content'],   // GET /api/articles?search=jsango
  filterFields: ['published'],          // GET /api/articles?published=true
  defaultPageSize: 25,                  // GET /api/articles?page=2&pageSize=50
  maxPageSize: 100,
  schema: schema({ title: string().min(3) }), // 400 with field errors
});

await app.listen(3000);

scope limits every query (for example to the signed-in user's rows), and a write that would move a record outside it is refused and rolled back. Hooks (beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete) run in one database transaction with the write: throwing in one rolls it back, and before* hooks may return changed data. only registers a subset of the routes.

Ownership, Hooks & Custom Writes
import { createApp, badRequest } from 'jsango';

const app = createApp();

// Every user works only with their own rows; business rules run in hooks.
app.crud('/api/addresses', Address, {
  access: auth.required(),
  writable: ['line1', 'city', 'pincode'],   // anything else in the body is ignored
  scope: (query, ctx) => query.where('userId', auth.identity(ctx).id),
  hooks: {
    beforeCreate: (data, ctx) => ({ ...data, userId: auth.identity(ctx).id }),
    beforeDelete: async (address) => {
      const used = await Order.where('addressId', address.get('id')).first();
      if (used) throw badRequest('Address is used by an order');
    },
  },
});

// A write that is a business process gets its own route; reads stay on app.crud.
app.crud('/api/orders', Order, {
  access: auth.required(),
  only: ['list', 'detail'],
  scope: (query, ctx) => query.where('userId', auth.identity(ctx).id),
});
app.post('/api/orders', auth.required(), (ctx) => placeOrder(auth.identity(ctx), ctx.body));

Onion Middleware Pipeline

JSango uses a zero-allocation onion middleware pipeline for logging, authentication guards, CORS, and request rate limiting.

src/middleware/auth.ts
import { HttpResponse, type RequestContext, type NextFunction } from 'jsango';

// A hand-written middleware: return a response to stop, or call next() to continue.
export async function apiKeyGuard(ctx: RequestContext, next: NextFunction) {
  const key = ctx.request.headers.get('x-api-key');
  if (key !== process.env.API_KEY) {
    return HttpResponse.unauthorized('Invalid API key');
  }
  ctx.state.set('client', { key }); // per-request state for later handlers
  return next();
}

// app.use(apiKeyGuard);                       // every route
// app.get('/api/reports', apiKeyGuard, handler); // one route

CORS, Security Headers & Rate Limits

Built-in middleware for the three things every public API needs. cors() answers preflight requests and only allows the origins you list ('*' can't be combined with credentials). rateLimit() counts per client IP by default (use trustProxy behind a proxy) and keeps counts in memory unless you pass a shared store.

Security Middleware
import { createApp, cors, securityHeaders, rateLimit } from 'jsango';

// Behind nginx / a load balancer: client IP, https and host from X-Forwarded-*
const app = createApp({ trustProxy: true });

app.use(securityHeaders()); // nosniff, X-Frame-Options: DENY, referrer policy, HSTS on https
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
app.use(rateLimit({ max: 300, windowSeconds: 60 })); // per client IP, 429 + Retry-After

// A stricter limit on one route; pass `store` (e.g. DatabaseAuthStore) to share between instances
app.post('/login', rateLimit({ max: 10 }), loginHandler);

Schema Validation

Validate request payloads with high-speed built-in schema builders that compile directly to native JavaScript validators:

Validation Example
import { createApp, validate, object, string, number, HttpResponse } from 'jsango';

const app = createApp();

const CreateProduct = object({
  name: string().min(3).max(100),
  price: number().positive(),
  category: string().optional(),
});

// validate() returns 400 with field errors when the body does not match
app.post('/api/products', validate({ body: CreateProduct }), async (ctx) => {
  const data = ctx.state.get('validatedBody') as { name: string; price: number; category?: string };
  const product = await Product.create(data);
  return HttpResponse.created(product);
});

Connecting a Database

JSango talks to PostgreSQL, MySQL/MariaDB, SQLite and MongoDB through one DatabaseManager. The same models, queries and migration commands work on all of them; jsango generates the right SQL (quoting, placeholders, types, RETURNING) or MongoDB commands (filters, pipelines, validators) for each.

DatabasedriverInstall in your appURL example
PostgreSQL 12+postgres (pg, postgresql)npm install pgpostgres://user:pass@host:5432/db
MySQL 8+ / MariaDBmysql (mariadb)npm install mysql2mysql://user:pass@host:3306/db
SQLitesqlitenothing on Node 22.13+ (else better-sqlite3)sqlite:./db.sqlite3
MongoDB 5+mongodb (mongo)npm install mongodbmongodb://user:pass@host:27017/db / mongodb+srv://…
In-memorymemory—tests only

Configure with Environment Variables

databaseConfigFromEnv() reads DATABASE_URL (preferred) or the individual DATABASE_* variables. This is what jsango new generates:

src/database.ts
import { DatabaseManager, databaseConfigFromEnv, setDatabaseManager } from 'jsango';

export const db = new DatabaseManager(databaseConfigFromEnv());

export function configureDatabase() {
  setDatabaseManager(db); // every model now uses this database
  return db;
}
.env
# Option A — one URL (wins if set)
DATABASE_URL=postgres://app:secret@localhost:5432/myapp

# Option B — individual settings
DATABASE_DRIVER=mysql
DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306
DATABASE_NAME=myapp
DATABASE_USER=app
DATABASE_PASSWORD=secret
DATABASE_SSL=true          # true/require, no-verify, false
DATABASE_POOL_MAX=10
DATABASE_FILE=./db.sqlite3 # SQLite only
💡
Special characters in passwords must be URL-encoded inside DATABASE_URL (p@ss → p%40ss), or use the separate DATABASE_PASSWORD variable.

Multiple Connections & Options

src/database.ts
export const db = new DatabaseManager({
  default: 'primary',
  connections: {
    primary: {
      driver: 'postgres',
      host: process.env.DB_HOST,
      database: 'myapp',
      username: 'app',
      password: process.env.DB_PASSWORD,
      ssl: true,
      pool: { max: 20, connectionTimeoutMs: 10_000 },
    },
    analytics: { url: process.env.ANALYTICS_URL }, // driver inferred from the URL
    local: { driver: 'sqlite', filename: './data/local.sqlite3' },
  },
});

// models: defineModel('Event', {...}, { connection: 'analytics' })

Models without a connection option use the default connection; the name 'default' always resolves to it.

Verify, Health Checks & Raw SQL

src/index.ts
await db.verify();                 // throws a descriptive error if it can't connect
await app.listen(3000);
process.once('SIGTERM', async () => { await db.close(); process.exit(0); });

// raw SQL: always write ? placeholders (converted to $1, $2 for PostgreSQL)
const { rows } = await db.query('SELECT id, email FROM users WHERE created_at > ?', [since]);
await db.transaction(async (tx) => {
  await tx.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, from]);
  await tx.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, to]);
});
Terminal
npx jsango db:status
# Connection  Driver    Target                     Status      Latency
# default     postgres  app@localhost:5432/myapp   ✓ HEALTHY   4ms

Connection failures name the target (never the password) and include a hint, e.g. Failed to connect to PostgreSQL at app@127.0.0.1:5432/myapp: connect ECONNREFUSED … Hint: Is the database running and listening on this host/port?


Defining Models

Models are the source of truth for your schema: migrations are generated from them. Put them in src/models/.

src/models/user.ts
import { defineModel, fields } from 'jsango';

export const User = defineModel(
  'User',
  {
    id: fields.id(),                                        // auto-increment primary key
    email: fields.string({ maxLength: 255, unique: true }),
    name: fields.string({ maxLength: 120, nullable: true }),
    role: fields.string({ maxLength: 20, defaultValue: 'member', indexed: true }),
    isActive: fields.boolean({ defaultValue: true }),
    settings: fields.json({ nullable: true }),
  },
  {
    table: 'users',     // default: lower-cased name + "s"
    timestamps: true,   // createdAt / updatedAt, maintained automatically
    softDelete: false,  // true: delete() sets deletedAt instead of removing the row
    relations: {
      posts: { type: 'hasMany', target: 'Post', foreignKey: 'userId' },
    },
  }
);
⚠️
Fields are NOT NULL by default. Add nullable: true for optional columns.

Field Types

FieldPostgreSQLMySQLSQLiteJS value
fields.id()SERIAL PRIMARY KEYINT AUTO_INCREMENTINTEGER PK AUTOINCREMENTnumber
fields.string({ maxLength })VARCHAR(n)VARCHAR(n)VARCHAR(n)string
fields.text()TEXTLONGTEXTTEXTstring
fields.integer() / bigint()INTEGER / BIGINTINT / BIGINTINTEGER / BIGINTnumber / bigint
fields.float() / decimal({ precision, scale })DOUBLE PRECISION / NUMERICDOUBLE / DECIMALREAL / NUMERICnumber
fields.boolean()BOOLEANTINYINT(1)INTEGER (0/1)boolean
fields.dateTime() / date() / time()TIMESTAMPTZ / DATE / TIMEDATETIME(3) (UTC)ISO textDate
fields.json()JSONBJSONTEXTobject / array
fields.uuid() / binary()UUID / BYTEACHAR(36) / LONGBLOBVARCHAR(36) / BLOBstring / Uint8Array
Field optionEffect
nullable: trueAllow NULL (default NOT NULL)
unique: trueUnique constraint uq_<table>_<column>
indexed: trueIndex idx_<table>_<column>
defaultValue: xDefault for new rows (a function is evaluated per insert)
maxLength, precision, scaleColumn size
columnNameColumn name when it differs from the property
primaryKey, autoIncrementCustom keys, e.g. fields.uuid({ primaryKey: true, defaultValue: () => crypto.randomUUID() })

Relations & Eager Loading (No N+1)

src/models/post.ts
export const Post = defineModel(
  'Post',
  {
    id: fields.id(),
    title: fields.string(),
    userId: fields.integer(),   // foreign key column
  },
  {
    table: 'posts',
    relations: {
      // posts.userId -> users.id; the migration creates a FOREIGN KEY (ON DELETE CASCADE)
      author: { type: 'belongsTo', target: 'User', foreignKey: 'userId' },
    },
  }
);

const posts = await Post.query().with('author').orderBy('id', 'DESC').limit(10).get();
posts[0].author.email; // all authors loaded with ONE extra query
TypeMeaningforeignKey is on
belongsTothis row points to one parentthis model
hasOne / hasManychildren point to this rowtarget model
manyToManyvia a pivot model (through, pivotForeignKey, pivotTargetKey)pivot model

target may be the model name ('User') or () => User. Nullable foreign keys default to ON DELETE SET NULL; override with options: { onDelete: 'RESTRICT' }.


Querying, Pagination & Transactions

CRUD
// Create
const user = await User.create({ email: 'a@example.com', name: 'Ada' });
user.id;        // assigned by the database
await Post.bulkCreate([{ title: 'One', userId: user.id }, { title: 'Two', userId: user.id }]);

// Read
await User.find(1);                                  // or null
await User.findOrFail(1);                            // throws ModelNotFoundError
await User.where('email', 'a@example.com').first();
await User.where({ role: 'admin', isActive: true }).get();

// Update
user.name = 'Ada Lovelace';
await user.save();                                   // only changed columns are written
await User.where('isActive', false).update({ role: 'inactive' });

// Delete
await user.delete();
await User.where('role', 'spam').delete();
Filters, sorting & pagination
const users = await User.query()
  .where('createdAt', '>=', since)
  .whereIn('role', ['admin', 'editor'])
  .whereNotNull('name')
  .orWhere('email', 'ILIKE', '%@example.com')
  .orderBy('createdAt', 'DESC')
  .limit(20)
  .offset(40)
  .get();

await User.count();
await User.where('isActive', true).exists();

const page = await User.query().orderBy('id').paginate({ page: 2, pageSize: 25 });
// page.items, page.total, page.page, page.pageSize, page.totalPages

for await (const u of User.query().cursor(500)) {
  // stream a large table in batches of 500
}

Operators: = != > >= < <= LIKE NOT LIKE ILIKE IN NOT IN; where('x', null) becomes IS NULL. Anything else is rejected, so user input can't inject SQL through the operator. Keys that aren't declared fields are ignored on insert/update.

Advanced Queries

Identical on PostgreSQL, MySQL, SQLite and MongoDB:

Advanced queries
// genre = 'fiction' AND (price < 10 OR pages > 500)
await Book.where('genre', 'fiction')
  .where((q) => q.where('price', '<', 10).orWhere('pages', '>', 500))
  .get();

await Book.whereNot('status', 'draft').get();
await Book.whereBetween('price', [10, 25]).get();
await Book.whereLike('title', '%guide%').get();     // case-insensitive
await Book.select('genre').distinct().get();
await Book.orderBy('price').pluck('title');
await Book.latest().first();

// aggregates
await Book.sum('price');
await Book.where('genre', 'science').avg('price');
await Book.min('price');
await Book.max('pages');

// GROUP BY / HAVING -> plain rows
await Book.query().groupBy(
  ['genre'],
  { total: ['sum', 'price'], books: ['count'] },
  { having: [['books', '>=', 2]], orderBy: [['total', 'DESC']] }
); // [{ genre: 'science', total: 42.5, books: 2 }, ...]

// atomic counters, find-or-create, batches, row locks
await Author.where('active', true).increment('logins');
await post.increment('views');
await Tag.firstOrCreate({ slug: 'news' }, { label: 'News' });
await Setting.updateOrCreate({ key: 'theme' }, { value: 'dark' });
await User.query().chunk(500, async (users) => { /* ... */ });
await transaction(async () => {
  const acc = await Account.where('id', id).lockForUpdate().first();
});

// escape hatch
await User.whereRaw('LOWER(email) = ?', [email]).get();      // SQL
await User.whereRaw({ tags: { $all: ['a', 'b'] } }).get();   // MongoDB

Soft Deletes

Soft deletes
// model option: softDelete: true
await post.delete();                  // sets deletedAt
await Post.query().get();             // excludes soft-deleted rows
await Post.withTrashed().get();       // includes them
await Post.onlyTrashed().get();       // only them
await post.delete({ force: true });   // real DELETE

Transactions

Transactions
import { transaction } from 'jsango';

await transaction(async () => {
  const user = await User.create({ email: 'ada@example.com' });
  await Profile.create({ userId: user.id });   // automatically in the same transaction
  if (!user.id) throw new Error('abort');       // any error rolls everything back
});

await transaction(async () => { /* ... */ }, { isolationLevel: 'SERIALIZABLE' });

// explicit alternative
await db.transaction(async (tx) => {
  await User.create({ email: 'ada@example.com' }, { connection: tx });
  await User.query().using(tx).where('id', 1).update({ name: 'x' });
});

MongoDB

Models, queries, relations, transactions and migrations all work on MongoDB. Install the driver and point DATABASE_URL at your server or Atlas cluster:

Terminal
npm install mongodb
# .env
DATABASE_URL=mongodb://app:secret@localhost:27017/myapp
src/models/post.ts
export const Post = defineModel('Post', {
  id: fields.objectId({ primaryKey: true }),  // maps to _id, new ObjectId on create
  title: fields.string(),
  authorId: fields.objectId(),                // ObjectId reference
  tags: fields.json({ nullable: true }),      // stored natively
}, {
  table: 'posts',                             // collection
  timestamps: true,
  relations: { author: { type: 'belongsTo', target: 'Author', foreignKey: 'authorId' } },
});

const post = await Post.create({ title: 'Hello', authorId: author.id });
post.id;                   // '65f1c2…' (ObjectId as string)
await Post.find(post.id);  // converted back to ObjectId in queries

where becomes a filter ($eq, $in, $regex for LIKE, $or/$and/$nor for groups, with SQL precedence); aggregates and groupBy run as aggregation pipelines; increment uses $inc.

Migration operationOn MongoDB
create tablecreateCollection + $jsonSchema validator (required fields & types) + indexes
unique / indexcreateIndex (unique on nullable fields ignores missing values, like SQL NULLs)
add columnbackfill the default into existing documents, then update the validator
drop / rename columnupdate the validator, then $unset / $rename the field and rebuild its indexes
foreign keysskipped — relations are resolved by the ORM
💡
Transactions need a replica set or sharded cluster (Atlas always has one). Locally: mongod --replSet rs0 and run rs.initiate() once. Migrations do not need transactions and work on a standalone server.
Data migrations & native access
import { defineMigration } from 'jsango';
import type { Db } from 'mongodb';

export default defineMigration({
  id: '20260930130000_backfill_roles',
  async up(ctx) {
    await ctx.execute({ op: 'updateMany', collection: 'users', filter: { role: null }, update: { $set: { role: 'member' } } });
  },
});

// anything else: the native driver
const mongo = await db.mongo<Db>();
await mongo.collection('events').aggregate([{ $match: { type: 'signup' } }]).toArray();

Migrations

Migrations turn changes in your models into versioned, reviewable changes to the real database:

  1. npx jsango makemigrations replays your existing migration files to know what the database should look like (no database connection needed), compares it with your models and writes a new file with just the difference.
  2. npx jsango migrate runs pending files in order and records each in the jsango_migrations table so it never runs twice.

Everyday Workflow

Terminal
# 1. change a model, e.g. add  age: fields.integer({ nullable: true })  to User

npx jsango makemigrations          # or: npx jsango migrate:generate add_age_to_users
#  ✔ Created migration migrations/20260930101500_add_age_to_users.ts
#    [+] Add column users.age (integer)

npx jsango migrate --dry-run       # optional: print the exact SQL
npx jsango migrate                 # apply
npx jsango migrate:status          # applied / pending
npx jsango migrate:rollback        # undo the last batch (--steps 1 for one migration)
migrations/20260930101500_add_age_to_users.ts (generated)
import { AddColumnOperation, Migration } from 'jsango';

export const id = '20260930101500_add_age_to_users';
export const name = 'add_age_to_users';

export default new Migration({
  id,
  name,
  operations: [
    new AddColumnOperation('users', { "name": "age", "type": "integer", "nullable": true }),
  ],
});

Generated migrations are reversible automatically. Review the file and commit it together with the model change.

⚠️
Destructive changes (dropping a table/column, changing a type, shrinking a column) are marked [destructive], and migrate refuses them until you confirm with --yes. Renames look like "drop + add" to the generator and would lose data — write them by hand with ctx.renameColumn(). Adding a NOT NULL column without a default to a table with rows fails on every database; the generator warns you.

Hand-written Migrations

Terminal
npx jsango makemigrations rename_user_name --empty
migrations/20260930120000_rename_user_name.ts
import { defineMigration } from 'jsango';

export default defineMigration({
  id: '20260930120000_rename_user_name',
  async up(ctx) {
    await ctx.renameColumn('users', 'name', 'fullName');

    await ctx.createTable('audit_logs', (t) => {
      t.id();
      t.integer('userId').references('users');   // FK -> users.id ON DELETE CASCADE
      t.string('action', 50).index();
      t.json('payload').nullable();
      t.timestamps();
    });

    await ctx.sql("UPDATE users SET role = 'member' WHERE role IS NULL"); // data migration
  },
  async down(ctx) {
    await ctx.dropTable('audit_logs');
    await ctx.renameColumn('users', 'fullName', 'name');
  },
});

Helpers: createTable, dropTable, renameTable, addColumn, dropColumn, alterColumn, renameColumn, addIndex, dropIndex, addUnique, dropUnique, addForeignKey, dropForeignKey, sql. Prefer the helpers for schema changes — makemigrations can see them; ctx.sql() is invisible to it.

How Each Database Runs Migrations

PostgreSQLSQLiteMySQL / MariaDBMongoDB
Each migration in a transaction✅✅❌ (DDL auto-commits)❌
Failure mid-migrationfully rolled backfully rolled backearlier statements stay appliedearlier commands stay applied
ALTER COLUMN, add/drop FKnativeautomatic table rebuild (data kept)nativevalidator update; FKs skipped

A migration lock prevents two deploys from migrating at the same time.

Production & CI

Release step
npm ci
npx jsango migrate:check --skip-db   # CI: fail if a model change has no migration
npx jsango migrate                   # apply pending migrations (locked)
npm start

Deploy the migrations/ folder and jsango.config.ts with the app. TypeScript migrations run without a build step. Full guide: docs/database/README.md.

Troubleshooting

MessageFix
No database is configured for this projectAdd jsango.config.ts or set DATABASE_URL in .env.
PostgreSQL support requires the 'pg' packagenpm install pg (or mysql2, better-sqlite3, mongodb).
ECONNREFUSEDThe database server is not running or the host/port is wrong.
password authentication failedWrong credentials; URL-encode special characters in DATABASE_URL.
database "x" does not existCreate it first: CREATE DATABASE x;
no such table / relation "users" does not existRun npx jsango makemigrations then npx jsango migrate.
Migration run contains destructive changesReview with migrate --dry-run, then migrate --yes.
MongoDB transactions need a replica setRun mongod --replSet rs0 + rs.initiate(), or use Atlas.
Document failed validationA MongoDB document misses a required field or has the wrong type; make the field nullable: true or pass a value.
Could not acquire migration lockAnother migrate is running; the lock of a crashed run expires after 15 minutes.

Admin Panel

app.admin() gives your app a ready-made admin panel: CRUD screens generated from your models, dashboards and custom pages built from widgets, CSV export, an audit trail and a system page. It is built for tables with millions of rows and is safe to expose in production.

src/index.ts
import { createApp, createAuth } from 'jsango';

const app = createApp();

app.admin({
  title: 'Shop Admin',
  // Sign in with your app's users: admin/staff role, admin.access permission or isSuperuser
  auth: createAuth({
    secret: process.env.AUTH_SECRET!,
    users: { findById: (id) => User.find(id), findByLogin: (email) => User.where('email', email).first() },
  }),
  resources: [User, Order, Product],
});

await app.listen(3000); // http://localhost:3000/admin

Who can sign in

Pass your createAuth() instance as auth (recommended): passwords, lockout and two-factor login come from your auth setup. For small tools, use a single built-in super admin instead: auth: { email, password } or JSANGO_ADMIN_EMAIL / JSANGO_ADMIN_PASSWORD. Without a password the development default admin123 works locally, and login is refused when NODE_ENV=production.

ProtectionHow
Password guessing5 failures / account / 15 min (20 per IP) → 429
Session tokens256-bit random, stored hashed, 8-hour lifetime, revocable from Profile & Security
Mass assignmentOnly createFields / editFields are written
Injection via sort / filterSort and filter fields are allow-listed, values are bound parameters
CSV formula injectionCells starting with = + - @ are neutralized

Customizing a model's screens

Pass { model, ...options }. Anything you don't set still comes from the model, so you only write what changes:

Resource options
app.admin({
  resources: [
    {
      model: Order,
      navigationGroup: 'Sales',
      listFields: ['id', 'customer', 'total', 'status', 'createdAt', 'summary'],
      searchFields: ['customer', 'email'],
      defaultSortField: 'createdAt',
      defaultSortDirection: 'desc',
      fields: [
        { name: 'status', enumChoices: [{ label: 'Paid', value: 'paid' }, { label: 'Refunded', value: 'refunded' }], filterable: true },
        { name: 'summary', type: 'computed', computedGetter: (o) => `${o['customer']} · ${o['total']}` },
      ],
      actions: [{ id: 'refund', label: 'Refund', requiresConfirmation: true, handler: async ({ item }) => refund(item['id']) }],
      bulkActions: [{ id: 'ship', label: 'Mark shipped', handler: ({ ids }) => Order.query().whereIn('id', ids).update({ status: 'shipped' }) }],
    },
    User, // plain models still work
  ],
});

Dashboards

The dashboard is made of widgets: metrics, line/bar charts, tables and activity feeds. Every widget loads its own data in parallel, can be cached (cacheSeconds), auto-refreshed (refreshIntervalSeconds) and restricted (permission).

Dashboard widgets
import { MetricWidget, ChartWidget, TableWidget } from 'jsango';

app.admin({
  resources: [Order],
  dashboard: [
    new MetricWidget({ title: 'Orders', cacheSeconds: 60, getValue: async () => ({ value: await Order.query().count(), change: 8.2, hint: 'vs last week' }) }),
    new MetricWidget({ title: 'Revenue', permission: 'finance.view', getValue: async () => await Order.query().sum('total') }),
    new ChartWidget({
      title: 'Orders by status',
      chartType: 'bar',
      getChartData: async () => {
        const rows = await Order.query().groupBy(['status'], { orders: ['count'] });
        return { labels: rows.map((r) => String(r['status'])), datasets: [{ label: 'Orders', data: rows.map((r) => Number(r['orders'])) }] };
      },
    }),
    new TableWidget({
      title: 'Latest orders',
      width: 'full',
      getTableData: async () => ({ headers: ['#', 'Customer'], rows: (await Order.query().latest().limit(5).get()).map((o) => [o.id, o.customer]) }),
    }),
  ],
});

Relations

A belongsTo relation turns its foreign key column (categoryId) into a dropdown of the related records. Register both models in resources. The dropdown loads its options once, shows a search box when there are more than 100, and has + New and Edit buttons that open the related record's form in a side panel. A record saved there is selected straight away, and side panels can stack (a category's parent category). hasMany / manyToMany relations are not editable in forms. Integer, UUID and ObjectId keys all work.

Relations, UUID keys & image fields
import { defineModel, fields, relations } from 'jsango';

export const Category = defineModel('Category', {
  id: fields.uuid({ primaryKey: true }),
  name: fields.string(),
});

export const Product = defineModel('Product', {
  id: fields.uuid({ primaryKey: true }),
  name: fields.string(),
  image: fields.string({ nullable: true }),
  categoryId: fields.uuid(),
}, {
  relations: { category: relations.belongsTo(() => Category, { foreignKey: 'categoryId' }) },
});

app.admin({
  resources: [
    // `image` gets an upload box and a media-library picker
    { model: Product, fields: [{ name: 'image', type: 'image' }] },
    Category,
  ],
});

Media library

Media in the admin sidebar lists files with previews (images, video, audio), uploads several at once or by drag and drop, searches, copies URLs and deletes, with a tab per storage disk. Fields of type image or file upload to the first disk and store the file's URL; their Library button picks an existing file.

Media disks
import { LocalDiskMediaStorage, S3MediaStorage, AdminMediaManager } from 'jsango';

app.admin({
  resources: [Product, Category],
  media: {
    // ./uploads, served by the app at /media (this is the default)
    local: new LocalDiskMediaStorage({ root: './uploads', publicUrl: '/media' }),
    // Amazon S3
    s3: new S3MediaStorage({
      bucket: 'assets',
      region: 'ap-south-1',
      accessKeyId: process.env.S3_KEY!,
      secretAccessKey: process.env.S3_SECRET!,
    }),
    // Cloudflare R2 / MinIO / DigitalOcean Spaces / Backblaze B2
    r2: new S3MediaStorage({
      bucket: 'assets',
      region: 'auto',
      endpoint: 'https://ACCOUNT_ID.r2.cloudflarestorage.com',
      publicUrl: 'https://cdn.example.com', // optional: without it previews use signed URLs
      accessKeyId: process.env.R2_KEY!,
      secretAccessKey: process.env.R2_SECRET!,
    }),
    // upload rules (size, MIME type, extension)
    avatars: new AdminMediaManager({
      storage: new LocalDiskMediaStorage({ root: './uploads/avatars', publicUrl: '/avatars' }),
      validation: { maxSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ['image/*'] },
    }),
  },
});
DiskNotes
LocalDiskMediaStorageDefault when media is not set. Files under root are served at publicUrl with nosniff and a sandboxing CSP, so an uploaded HTML or SVG file cannot run scripts on your site. Paths outside root are refused.
S3MediaStorageAmazon S3 and S3-compatible services (set endpoint). Requests are signed with SigV4 by jsango itself: no AWS SDK to install. Only works inside its root folder (default uploads), serves non-media files as downloads, lists the first 1000 files.
AdminMediaManagerWraps any disk with upload rules: maxSizeBytes (default 10 MB), allowedMimeTypes, allowedExtensions.
Your ownImplement IMediaStorage (store, get, delete, url, and optionally list / read) for GCS, Azure Blob or anything else.

Pass media: {} to turn the library off. Admin API: GET /media, GET /media/:disk?prefix=, POST /media/:disk (raw body, x-file-name header), DELETE /media/:disk?key=.

Custom pages

Custom page
import { AdminPage, MetricWidget } from 'jsango';

const finance = new AdminPage({
  id: 'finance',
  label: 'Finance',
  navigationGroup: 'Reports',
  permission: 'finance.view',
  widgets: [new MetricWidget({ title: 'Refunds this month', getValue: () => 12 })],
});

app.admin({ resources: [Order], pages: [finance] });

Millions of rows

FeatureHow it stays fast
ListLoads only list columns; COUNT(*) and the page run in parallel; stable primary-key tie-breaker
exactCount: falseSkips COUNT(*) entirely: next/previous paging with LIMIT n+1
CSV exportStreams every matching row in batches with keyset pagination (WHERE id > last): constant memory, native download via a one-time link
Bulk deleteOne query for up to 1,000 selected rows
SearchWaits until typing stops; limited to searchFields (index them)
ORMchunk() / cursor() without orderBy() seek by primary key instead of OFFSET

Audit trail & system health

The Audit Trail records every change (with before/after values), export, bulk action and sign-in, filterable by resource and action; plug in persistent storage with auditStore. Brand it with title, brandSubtitle, logoUrl, logoText, faviconUrl and customCss; the header adapts to phones. The System page shows process stats and health checks: the database is checked automatically, and you can add your own with healthChecks: { redis: () => redis.ping() }. Full guide: docs/admin/ADMIN-CUSTOMIZATION.md.


AI Agents & Tool Calling

JSango includes a native, provider-agnostic AI agent runtime with strongly typed tool execution and human-in-the-loop approvals:

src/agents/support.ts
import { agent, tool, object, string, number, createApp } from 'jsango';

// 1. Define tools with automatic schema validation
const getOrder = tool({
  name: 'getOrder',
  description: 'Fetch order details',
  schema: object({ orderId: string() }),
  execute: async ({ orderId }) => await Order.find(orderId),
});

const refundOrder = tool({
  name: 'refundOrder',
  description: 'Process a customer refund',
  schema: object({ orderId: string(), amount: number() }),
  requiresApproval: true, // Human approval gate
  execute: async ({ orderId, amount }) => await Stripe.refund(orderId, amount),
});

// 2. Create the Agent
export const supportAgent = agent({
  name: 'SupportAgent',
  model: 'openai:gpt-4o',
  instructions: 'Help customers with orders and refunds.',
  tools: { getOrder, refundOrder },
});

// 3. Expose over HTTP / SSE and WebSockets in 1 line
const app = createApp();
app.agent('/api/support', supportAgent);
app.wsAgent('/ws/support', supportAgent);

Token-Efficient Memory

With memory, an agent remembers the conversation per tenant, user and conversation. It sends the model as few tokens as possible: tool calls and results are kept only for the latest turn, RAG context is never stored, history has a token budget (default 4,000), and with summarize: true older turns are folded into a short running summary.

Memory with a token budget
const assistant = agent({
  instructions: 'Help users with their questions.',
  memory: true, // or new DatabaseMemoryStore({ connection: db }) to persist
  history: { maxTokens: 2000, summarize: true },
});

Universal LLM Providers & Custom LLMs

Switch between OpenAI, Anthropic Claude, Google Gemini, Local Ollama, OpenRouter, or your own custom provider:

Provider Configuration & OpenRouter
import { OpenAiProvider, AnthropicProvider, GeminiProvider, OllamaProvider, OpenRouterProvider, agent, provider } from 'jsango';

// 1. Local Ollama (auto-resolves http://localhost:11434 to /v1/chat/completions)
const localAgent = agent({
  provider: new OllamaProvider({ baseUrl: 'http://localhost:11434' }),
  model: 'llama3.2',
  instructions: 'Privacy-focused assistant',
});

// 2. OpenRouter (Unified access to 100+ models)
const routerAgent = agent({
  provider: new OpenRouterProvider({ apiKey: process.env.OPENROUTER_API_KEY }),
  model: 'deepseek/deepseek-chat',
  instructions: 'High-performance code generator',
});

// 3. Any OpenAI-compatible API (Groq, DeepSeek, vLLM, LM Studio...): no code
const groq = new OpenAiProvider({ baseUrl: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_API_KEY });

// 4. Anything else: one function that returns the reply text
const myProvider = provider(async ({ messages, model, signal }) => {
  const res = await fetch('https://my-model.example.com/chat', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ model, messages }),
    signal,
  });
  return (await res.json()).text; // or { text, toolCalls, usage }
});
const bot = agent({ name: 'Assistant', instructions: 'You are helpful' }, myProvider);

provider() gets messages with prompt / system already folded in. For tools, return { toolCalls: [{ id, name, arguments }] }; the result comes back as a role: 'tool' message. For RAG, pass provider(fn, { embed }). Streaming sends the reply as one chunk; for token-by-token streaming, extend BaseLlmProvider. Register it with ai.registerProvider('mine', myProvider) to use model: 'mine:…'.


Voice & Phone Calling Agents

The same agent you use for text can talk: in the browser, over WebRTC, or on a phone call. It keeps the same instructions, tools, permissions and memory. You choose every model: any LLM provider, any speech-to-text and any text-to-speech (including your own self-hosted models), or a speech-to-speech provider. API keys always stay on the server.

Voice with any models
import { createApp, agent, deepgram, cartesia } from 'jsango';

const support = agent({
  provider: myLlm, // any LLM: OpenAI, Anthropic, Gemini, Ollama, provider(fn)…
  instructions: 'You are a friendly support agent. Keep answers short.',
  memory: true,
});

const app = createApp();
app.voiceAgent('/voice', support, {
  middleware: [auth.required()], // voice costs money per minute
  stt: deepgram(), // speech-to-text
  tts: cartesia({ voiceId: 'your-voice-id' }), // text-to-speech
});

Everything streams: the LLM's answer is cut into sentences and each one is spoken while the LLM is still writing. When the user talks over the agent, the LLM and speech calls are aborted, memory keeps only what was actually heard, and tool calls from the cancelled reply never run. Every reply reports its latency (sttMs, llmMs, firstAudioMs).

AdapterKindNotes
deepgram()Speech-to-text, streamingnova-3, end-of-turn detection
openaiStt()Speech-to-textgpt-transcribe; any OpenAI-compatible server via baseUrl (e.g. faster-whisper)
openaiTts()Text-to-speech, streaminggpt-4o-mini-tts; OpenAI-compatible servers (e.g. Kokoro) via baseUrl
elevenlabs({ voiceId })Text-to-speech, streamingeleven_flash_v2_5
cartesia({ voiceId })Text-to-speech, streamingsonic-3.6
openaiRealtime()Speech-to-speechWebSocket or WebRTC
geminiLive({ model })Speech-to-speech16 kHz in, 24 kHz out

Your Own Speech Models

Any model is one function. Audio is PCM16 mono and is resampled automatically.

stt(fn) and tts(fn)
import { stt, tts } from 'jsango';

const myStt = stt(async (audio, { sampleRate, signal }) => {
  const res = await fetch('http://my-asr/transcribe', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ audio: Buffer.from(audio.buffer).toString('base64'), sampleRate }),
    signal,
  });
  return (await res.json()).text;
}, { sampleRate: 16000 });

const myTts = tts(async (text, { signal }) => {
  const res = await fetch('http://my-tts/speak', { method: 'POST', body: text, signal });
  return new Int16Array(await res.arrayBuffer());
}, { sampleRate: 22050 });

app.voiceAgent('/voice', support, { stt: myStt, tts: myTts });

WebRTC (lowest latency)

The browser streams audio over WebRTC directly to a speech-to-speech provider. Your server creates the call with its own key and keeps a control connection to it, where tools run with the user's permissions and transcripts, usage and the time limit (hang-up) are handled.

WebRTC voice
app.webrtcAgent('/voice/rtc', support, {
  realtime: openaiRealtime({ voice: 'marin' }),
  middleware: [auth.required()],
});
// Browser: create an RTCPeerConnection with the microphone track, POST the SDP offer
// to /voice/rtc (Content-Type: application/sdp) and set the returned SDP as the answer.

Phone Calling Agents

Answer and place real phone calls (Twilio Media Streams) with the same agent and models. Webhooks are verified with Twilio's signature, and a media stream is only accepted with a single-use token for a call this server just answered or dialed.

Inbound and outbound calls
const line = app.phoneAgent('/phone', support, {
  carrier: twilio({ from: '+15550001111' }), // TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN
  publicUrl: 'https://voice.example.com',
  stt: deepgram(),
  tts: cartesia({ voiceId: 'your-voice-id' }),
  identify: async (call) => findCustomerByPhone(call.from), // optional: who is calling
});

// Point your Twilio number's "A call comes in" webhook at POST /phone.
await line.dial('+919876543210'); // outbound

Full guides: docs/ai/voice.md and docs/ai/phone.md. A runnable browser client is in examples/voice-agent.


AI Insights: Usage, Cost & Latency

One line records every agent run and voice call: tokens, cost from your price table, latency per voice turn, interruptions, audio minutes and errors. Records go to your SQL database (or memory), show up in the admin panel and can feed Prometheus. Prompts, answers and transcripts are not stored unless you turn on captureContent; records are deleted after 30 days.

Insights in the admin panel
import { aiWidgets, aiAdminPage, recordTo, LocalDiskMediaStorage } from 'jsango';

const insights = app.aiInsights({
  store: db, // PostgreSQL, MySQL or SQLite
  prices: {
    'gpt-4o-mini': { input: 0.15, output: 0.6 }, // USD per 1M tokens
    deepgram: { perMinute: 0.0043 },
  },
});

const recordings = new LocalDiskMediaStorage();
app.admin({
  media: { local: recordings },
  dashboard: aiWidgets(insights), // usage, cost, latency, errors, charts
  pages: [aiAdminPage(insights)], // "AI Usage" page: recent calls, transcripts, recordings
});

// Optional, off by default: record calls (tell your callers)
app.voiceAgent('/voice', support, { stt: deepgram(), tts: openaiTts(), record: recordTo(recordings) });

// Your own dashboards
const today = await insights.summary(); // runs, tokens, costUsd, calls, latency p50/p95, byModel…
const chart = await insights.series({ bucket: 'day' });

Widgets are normal admin widgets behind the ai.insights.view permission. Pick the ones you want or build your own on insights.summary(), series(), runs(), calls() and call(id). observeAi(listener) streams every record to your own sink. Full guide: docs/ai/insights.md.


Multi-Agent Workflows & Orchestration

Compose sequential, parallel, and branching pipelines between multiple specialized agents:

src/workflows/research.ts
import { workflow, agent } from 'jsango';

const researcher = agent({ name: 'researcher', instructions: 'Collect key facts.' });
const writer = agent({ name: 'writer', instructions: 'Write a concise report.' });
const legalReviewer = agent({ name: 'legal', instructions: 'Review for compliance.' });
const fastTrack = agent({ name: 'fast-track', instructions: 'Approve routine reports.' });

const pipeline = workflow('document-review')
  .step('research', researcher)                      // output stored in state.research
  .step('draft', writer)
  .parallel('checks', {                              // run concurrently
    tone: async (_input, state) => String(state.draft).length > 0,
    length: async (_input, state) => String(state.draft).length,
  })
  .branch('review', (state) => state.length > 2000, {
    true: legalReviewer,                             // long reports go to legal
    false: fastTrack,
  });

const result = await pipeline.run({ input: 'Analyze quarterly earnings' });
console.log(result.status, result.state.review, result.steps.map((s) => s.name));

RAG & Vector Search

Embed, store, and retrieve semantic document chunks with zero external dependencies:

src/ai/knowledge.ts
import { knowledge, agent } from 'jsango';

export const docs = knowledge('handbook', { chunkSize: 500, chunkOverlap: 50 });

await docs.ingest('JSango is a high-performance TypeScript backend framework with built-in AI agents.', {
  metadata: { source: 'readme' },
});

const matches = await docs.search('What is JSango?', { limit: 3, minScore: 0.5 });
matches.forEach((m) => console.log(m.score.toFixed(2), m.document.content));

// Give an agent the knowledge base: relevant passages are added to the prompt
const answer = await agent({ name: 'docs-bot' }).run({ input: 'What is JSango?', knowledge: docs });

Model Context Protocol (MCP)

Expose JSango tools over standardized JSON-RPC MCP servers or consume remote MCP servers:

src/mcp/server.ts
import { McpServer, McpClient, tool, object, string, createApp, HttpResponse, agent } from 'jsango';

// 1. Expose your tools to MCP clients (Claude Desktop, Cursor, ...)
const server = new McpServer({ name: 'jsango-tools', version: '1.0.0' }).registerTool(tool({
  name: 'fetchInventory',
  description: 'Check stock inventory for SKU',
  schema: object({ sku: string() }),
  execute: async ({ sku }: { sku: string }) => ({ sku, inStock: true, count: 42 }),
}));

const app = createApp();
app.post('/mcp', async (ctx) => (await server.handleJsonRpc(await ctx.request.json())) ?? HttpResponse.noContent());

// 2. Use tools from a remote MCP server in an agent
const remote = await McpClient.connect('https://mcp.example.com/mcp');
const assistant = agent({ name: 'assistant', tools: await remote.tools() });

Streaming SSE & WebSockets

Stream agent thoughts, token chunks and tool approvals in real time. Responses contain the answer, conversationId, tool call names and usage, never the history or system prompt; anonymous visitors get their own server-issued conversation, and a run stops when the client disconnects. Tokens arrive as message.delta events while the model writes; agent.stream() gives the same events in code, and stopping the loop cancels the run.

Streaming Endpoints
const app = createApp();

// POST /api/agent { input, conversationId? }  and  GET /api/agent?input=...&stream=true (SSE)
app.agent('/api/agent', supportAgent, {
  middleware: [auth.required()], // agents cost tokens: don't leave them public by accident
  maxSteps: 5,
  maxInputLength: 4000,
});

// Bi-directional WebSocket agent: one run at a time per connection
app.wsAgent('/ws/agent', supportAgent, { middleware: [auth.required()] });

Authentication & Security

createAuth() gives you complete, production-grade authentication in one object: password login with JWT access + rotating refresh tokens, cookie sessions, API keys, social login (Google, GitHub, any OAuth2), external identity providers (Auth0, Clerk, Cognito, Firebase via JWKS) and TOTP two-factor login. Every method is checked by the same middleware, auth.required(), so one route can accept all of them.

MethodUse it forClient sends
Password + JWTAPIs, SPAs, mobile appsAuthorization: Bearer <token>
Cookie sessionsServer-rendered / same-site web appsjsango_session cookie
API keysServer-to-server, CLIs, partnersX-API-Key: live_…
Social login"Sign in with Google / GitHub"OAuth2 redirect → session or tokens
External IdPAuth0, Clerk, Cognito, Firebase, KeycloakProvider-issued Bearer JWT
TOTP 2FAAuthenticator-app codes on top of passwords{ mfaToken, code }

1. Setup

jsango doesn't own your user table: tell it how to load users. It reads id, passwordHash, role/roles, permissions, tenantId and totpSecret from your records.

src/auth.ts
import { createAuth, DatabaseAuthStore } from 'jsango';

export const auth = createAuth({
  secret: process.env.AUTH_SECRET!, // 32+ random characters: openssl rand -base64 48
  users: {
    findById: (id) => User.find(id),
    findByLogin: (email) => User.where('email', email).first(),
    isActive: (user) => user.isActive, // blocked users lose access immediately
  },
  roles: { admin: ['posts.update', 'posts.delete'], editor: ['posts.update'] },
  store: new DatabaseAuthStore({ connection: db }), // sessions & tokens survive restarts
});
Sign up, log in, current user
import { createApp } from 'jsango';

const app = createApp();

app.post('/auth/register', async (ctx) => {
  const { email, password } = (await ctx.request.json()) as { email: string; password: string };
  const user = await User.create({
    email: email.trim().toLowerCase(),
    passwordHash: await auth.hashPassword(password), // scrypt; rejects passwords under 8 chars (422)
  });
  return auth.issueTokens(user);
});

app.post('/auth/login', async (ctx) => {
  const { email, password } = (await ctx.request.json()) as { email: string; password: string };
  return auth.login(email, password, ctx);
  // => { tokenType: 'Bearer', accessToken, expiresIn: 900, refreshToken }
  // wrong password => 401 "Invalid login or password." | too many attempts => 429
});

app.get('/me', auth.required(), async (ctx) => {
  const user = await auth.user(ctx);
  return { id: user.id, email: user.email };
});

2. Tokens, refresh & logout

Access tokens live 15 minutes; refresh tokens 30 days and rotate on every use. If an old refresh token is replayed (it was stolen), the whole login is revoked. logout() kills the access token immediately and logoutAll() signs the user out on every device.

Refresh & logout
app.post('/auth/refresh', async (ctx) => {
  const { refreshToken } = (await ctx.request.json()) as { refreshToken: string };
  return auth.refresh(refreshToken); // new access token AND new refresh token
});

app.post('/auth/logout', auth.required(), async (ctx) => {
  await auth.logout(ctx);
  return { ok: true };
});

app.post('/auth/logout-all', auth.required(), async (ctx) => {
  await auth.logoutAll(auth.identity(ctx).id); // e.g. after a password change
  return { ok: true };
});

3. Protecting routes (roles & permissions)

Guards
app.get('/me', auth.required(), handler);                                      // any signed-in user
app.get('/admin', auth.required({ roles: ['admin'] }), handler);               // any of these roles
app.delete('/posts/:id', auth.required({ permissions: ['posts.delete'] }), handler); // all of these
app.get('/feed', auth.optional(), handler);                                    // anonymous allowed
app.post('/webhooks', auth.required({ methods: ['apiKey'] }), handler);        // API keys only

// Inside handlers
const identity = auth.identity(ctx); // { id, roles, permissions, tenantId, hasRole(), hasPermission() }
const user = await auth.user(ctx);   // your user record, loaded once per request

401 when not signed in, 403 for a missing role or permission. Invalid or expired credentials are always rejected, even on optional() routes.

The cookie holds only a random, HMAC-signed id: HttpOnly, SameSite=Lax, Secure in production, with sliding expiry. Unsafe requests (POST/PUT/PATCH/DELETE) made with the cookie need a trusted Origin, which blocks CSRF. Add your frontend with session: { trustedOrigins: ['https://app.example.com'] }.

Session login
import { HttpResponse } from 'jsango';

app.post('/login', async (ctx) => {
  const { email, password } = (await ctx.request.json()) as { email: string; password: string };
  const result = await auth.login(email, password, ctx);
  if (result.mfaRequired) return result; // 2FA user: see below
  return auth.startSession(HttpResponse.json({ ok: true }), result.user);
});

app.post('/logout', auth.required(), async (ctx) => {
  const response = HttpResponse.json({ ok: true });
  await auth.logout(ctx, response); // deletes the session and clears the cookie
  return response;
});

5. API keys

API keys
// createAuth({ ..., apiKeys: { find: (hash) => ... } })
const apiKeys = {
  find: async (hash: string) => {
    const key = await ApiKey.where('hash', hash).whereNull('revokedAt').first();
    return key ? User.find(key.userId) : null; // the user the request acts as
  },
};

app.post('/settings/api-keys', auth.required(), async (ctx) => {
  const { key, hash, prefix, last4 } = auth.createApiKey('live'); // live_9fKx...
  await ApiKey.create({ userId: auth.identity(ctx).id, hash, prefix, last4 });
  return { key }; // shown once; only the SHA-256 hash is stored
});

6. Social login (Google, GitHub, any OAuth2)

Authorization code flow with PKCE and a signed one-time state cookie. Forged or replayed callbacks get a 400. Only link accounts by email when emailVerified is true.

OAuth login
import { createAuth, google, github, HttpResponse } from 'jsango';

export const auth = createAuth({
  secret: process.env.AUTH_SECRET!,
  users: { findById: (id) => User.find(id) },
  oauth: [
    google({ clientId: process.env.GOOGLE_ID!, clientSecret: process.env.GOOGLE_SECRET!, redirectUri: 'https://api.example.com/auth/google/callback' }),
    github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET!, redirectUri: 'https://api.example.com/auth/github/callback' }),
  ],
});

app.get('/auth/:provider', (ctx) => auth.oauth.redirect(ctx.request.params['provider']!));

app.get('/auth/:provider/callback', async (ctx) => {
  const profile = await auth.oauth.callback(ctx.request.params['provider']!, ctx);
  // { provider, id, email, emailVerified, name, avatarUrl }
  if (!profile.email || !profile.emailVerified) return HttpResponse.badRequest('A verified email is required.');
  const user = await User.firstOrCreate({ email: profile.email.toLowerCase() }, { name: profile.name });
  return auth.startSession(HttpResponse.redirect('https://app.example.com/'), user);
});

Any other provider: oauthProvider({ name, clientId, clientSecret, redirectUri, authorizeUrl, tokenUrl, userInfoUrl }).

7. External identity providers (Auth0, Clerk, Cognito, Firebase)

Provider tokens are verified with the provider's public keys (JWKS: RS*, PS*, ES*, EdDSA). Expiry, issuer and audience are always checked, and shared-secret algorithms are refused.

JWKS verification
import { createAuth } from 'jsango';

export const auth = createAuth({
  secret: process.env.AUTH_SECRET!,
  users: { findById: (id) => User.find(id) },
  external: {
    jwksUrl: 'https://YOUR_TENANT.auth0.com/.well-known/jwks.json',
    issuer: 'https://YOUR_TENANT.auth0.com/',
    audience: 'https://api.example.com',
    identity: (claims) => ({ id: String(claims.sub), roles: (claims['https://example.com/roles'] as string[]) ?? [] }),
  },
});

8. Two-factor authentication (TOTP)

For users with a totpSecret, login() returns { mfaRequired: true, mfaToken } instead of tokens. Codes allow ±30s drift, work once, and are brute-force limited.

2FA enrollment & login
app.post('/account/2fa/setup', auth.required(), async (ctx) => {
  const user = await auth.user(ctx);
  const { secret, uri } = auth.totp.generateSecret({ issuer: 'My App', accountName: user.email });
  await User.query().where('id', user.id).update({ pendingTotpSecret: secret });
  return { uri }; // render as a QR code in the browser
});

app.post('/account/2fa/confirm', auth.required(), async (ctx) => {
  const { code } = (await ctx.request.json()) as { code: string };
  const user = await auth.user(ctx);
  if (!auth.totp.verifyToken(code, user.pendingTotpSecret)) return HttpResponse.badRequest('Invalid code');
  await User.query().where('id', user.id).update({ totpSecret: user.pendingTotpSecret, pendingTotpSecret: null });
  return { backupCodes: auth.totp.generateBackupCodes(8) };
});

app.post('/auth/login/2fa', async (ctx) => {
  const { mfaToken, code } = (await ctx.request.json()) as { mfaToken: string; code: string };
  return auth.verifyMfa(mfaToken, code); // => tokens
});

Built-in protections

ThreatProtection
Password database leakscrypt with per-password salt; automatic rehash on login
Password guessing5 failures / account / 15 min (20 per IP) → 429
Account enumerationOne generic error; unknown users cost the same hashing time
Stolen access token15-minute lifetime; logout() revokes it instantly
Stolen refresh tokenRotation on every use; reuse revokes the whole login
JWT forgery / alg confusionHS256 pinned with a derived key; external tokens asymmetric-only; tokens without exp rejected
CSRF / session fixationTrusted Origin check; new signed session id per login
OAuth login CSRFSigned one-time state + PKCE S256
Leaking user recordsToken results never serialize user; API keys stored as SHA-256
🚀
Production: set a random AUTH_SECRET (32+ chars), use store: new DatabaseAuthStore({ connection: db }) (works on PostgreSQL, MySQL, SQLite and MongoDB) so sessions survive restarts and are shared across instances, serve over HTTPS, and call auth.logoutAll(userId) after password changes. Full guide: docs/auth/README.md. Low-level building blocks (JwtService, authenticate(), authorize(), policies) are still exported.

Background Job Queues & Caching

Execute heavy background tasks reliably with automatic retries, dead-letter store management, and concurrent worker loops.

Defining & Dispatching Jobs
import { jobs } from 'jsango';

// 1. Register a job handler
jobs.register<{ email: string }>('send-welcome-email', async (payload) => {
  await mailer.send({ to: payload.email, subject: 'Welcome!' });
});

// 2. Dispatch it (retried up to maxAttempts times on failure)
await jobs.dispatch('send-welcome-email', { email: 'user@example.com' }, {
  maxAttempts: 3,
  delay: 5000, // ms before the first attempt
});

High-Performance Caching

Cache Operations
import { cache } from 'jsango';

// Cache expensive computation or query with remember()
const topProducts = await cache.remember('top-products', 300, async () => {
  return await Product.where('sales', '>', 1000).get();
});

// Invalidate on update
await cache.delete('top-products');

Typed Event Emitter

Domain Events
import { events } from 'jsango';

events.on('user:registered', async ({ user }) => {
  console.log('New user registered:', user.email);
});

await events.emit('user:registered', { user: newUser });

Realtime WebSockets

app.ws() works like an HTTP route: path params, and middleware such as auth.required() or a rate limiter runs on the connection request. Messages are JSON-parsed, rooms are shared across routes, and app.to(room) pushes to sockets from anywhere in your app.

WebSocket Server
import { createApp, createAuth } from 'jsango';

const app = createApp();
const auth = createAuth({ secret: process.env.AUTH_SECRET!, users: userLookup });

// Works like an HTTP route: params + middleware (runs on the connection request)
app.ws('/chat/:room', auth.required(), {
  open(socket) {
    socket.join(socket.params.room);
    socket.to(socket.params.room).emit('joined', { user: socket.user?.id });
  },
  message(socket, data) {
    socket.to(socket.params.room).send(data); // JSON is parsed and sent for you
  },
  close(socket, code) {},
});

// Event style: the client sends { "event": "typing", "data": { ... } }
app.ws('/live', (socket) => {
  socket.on('typing', (data) => socket.broadcast({ event: 'typing', data }));
});

// Server push from any HTTP route, job or event handler
app.post('/notify/:userId', auth.required({ roles: ['admin'] }), async (ctx) => {
  await app.to(`user:${ctx.params.userId}`).emit('notification', { text: 'Hello' });
  return { sent: true };
});

await app.listen(3000);
Socket APIDoes
send(data) / emit(event, data)Send JSON / send { event, data }
join(room), leave(room), roomsRooms; signed-in sockets are automatically in user:<id>
to(room).send/emitEveryone in the room except this socket
broadcast(data)Everyone else on the same route
on('message' | 'close' | 'error' | name)Listen; a custom name receives the data of client messages { event: name, data }
user, params, request, ctx, idSigned-in user, route params, the connection request

Secure by default: only pages from your own host can connect (set origins: ['https://app.example.com'] or '*'; clients without an Origin header such as servers and mobile apps are allowed), messages are capped at 64 KB (maxPayload), dead connections are dropped by a 30-second ping, slow clients are disconnected instead of filling memory, and errors thrown in handlers go to error and the log instead of crashing the server. server.close() closes open sockets with code 1001.


Prometheus Metrics & Tracing

Built-in Prometheus metrics exposition and distributed tracing hooks for production observability:

Observability
import { createApp, MetricRegistry, HealthRegistry, HttpResponse } from 'jsango';
import { createHealthHandler } from '@jsango/observability';

const app = createApp();
export const metrics = new MetricRegistry();
const requests = metrics.counter('http_requests_total', 'HTTP requests', ['route']);

app.get('/api/hello', () => {
  requests.inc(1, { route: '/api/hello' });
  return { hello: 'world' };
});

// Prometheus scrape endpoint
app.get('/metrics', () =>
  HttpResponse.text(metrics.toPrometheus(), { headers: { 'content-type': 'text/plain; version=0.0.4' } })
);

// Liveness / readiness probes (503 when a critical check fails)
const health = new HealthRegistry()
  .register('database', async () => (await db.health()).every((c) => c.status === 'healthy'));
app.get('/health', createHealthHandler(health));

OpenAPI 3.1 & Swagger UI Documentation

JSango automatically generates compliant OpenAPI 3.1 JSON schemas by introspecting your route signatures, input validation schemas, and ORM models, and renders an interactive, high-contrast dark-themed Swagger UI dashboard out of the box.

1-Line Auto Documentation

src/index.ts
import { createApp } from 'jsango';
import { Product } from './models/product.js';

const app = createApp();

// Mount CRUD routes
app.crud('/api/products', Product);

// Enable automated OpenAPI 3.1 spec and interactive Swagger UI docs
app.openapi({
  path: '/openapi.json',
  title: 'E-Commerce Store API',
  version: '1.0.9',
  description: 'Production REST API with real-time inventory and search',
});

await app.listen(3000);
// Interactive Swagger UI is live at: http://localhost:3000/docs
// OpenAPI JSON schema at: http://localhost:3000/openapi.json

CLI Commands Reference

Run npx jsango help for the full list and npx jsango <command> --help for options. Every command accepts --json.

Command Description
npx jsango new <name> Scaffold a project (SQLite configured, example model, migrations folder).
npx jsango makemigrations [name] Create a migration from model changes (migrate:generate). --dry-run, --empty.
npx jsango migrate Apply pending migrations. --dry-run prints SQL, --yes confirms destructive changes, --target <id>.
npx jsango migrate:status Show applied and pending migrations.
npx jsango migrate:rollback Undo the last batch; --steps N or --target <id>.
npx jsango migrate:check Fail when models have unmigrated changes or migrations are pending (CI). --skip-db.
npx jsango migrate:reset --yes Roll back all migrations; --fresh re-applies them. Refused in production.
npx jsango db:status Test every configured database connection.
npx jsango model:list / model:show <Name> Inspect registered ORM models.
npx jsango route:list List HTTP routes.
npx jsango make:admin <Model> Generate an admin resource.
npx jsango make:agent <Name> Generate an AI agent and tool.
npx jsango openapi:generate Generate an OpenAPI 3.1 document.
npx jsango queue:work Run a background job worker.
npx jsango doctor Check environment, database and migrations.

Modular Packages Directory

JSango is built as an interconnected suite of 28 specialized packages. You can import from the monolithic jsango meta-package or install individual modular packages:

Package Name Version Description & Key Exports
jsango v1.6.0 Primary batteries-included meta-package (createApp, model, agent, tool).
@jsango/ai v1.6.0 AI Platform: Autonomous Agents, Multi-Agent Workflows, RAG Vector Search, MCP Protocol.
@jsango/orm v1.6.0 Declarative ORM, Relations, Eager Loading (No N+1), AST Query Builder.
@jsango/database v1.6.0 Database Drivers: PostgreSQL, MySQL/MariaDB, SQLite, MongoDB, In-Memory Engine.
@jsango/router v1.6.0 Ultra-fast SegRadix Trie Router (>7.7M ops/sec) with inline parameter validators.
@jsango/http v1.6.0 Typed HTTP Request, Response, RequestContext, Cookies, and HTTP Status Codes.
@jsango/admin-server v1.6.0 Backend server & REST endpoints powering the dynamic Admin Console.
@jsango/admin-ui v1.6.0 React Single-Page Application (SPA) dashboard for database records & system diagnostics.
@jsango/admin-core v1.6.0 Resource registry, faceted filters, search rules, and CSV/JSON export definitions.
@jsango/auth v1.6.0 RFC 6238 TOTP 2FA, Scrypt Password Hashing, JWT Tokens, Multi-device Sessions.
@jsango/queue v1.6.0 Background job worker loops, automatic exponential retries, dead-letter storage.
@jsango/cache v1.6.0 High-speed caching layer supporting memory and Redis drivers with TTL & tags.
@jsango/events v1.6.0 Strongly typed in-memory and distributed Pub/Sub event bus.
@jsango/websocket v1.6.0 Realtime WebSockets with room grouping, client broadcasting, and heartbeat pings.
@jsango/validation v1.6.0 Compiled schema validators (string, number, object, array).
@jsango/migrations v1.6.0 Automated schema diffing, batch migration runner, and rollback engine.
@jsango/openapi v1.6.0 OpenAPI 3.1 specification generation and dark-themed Swagger UI dashboard.
@jsango/observability v1.6.0 Structured logging, Prometheus metric exposition, and distributed tracing hooks.
@jsango/cli v1.6.0 Command-line interface for scaffolding, model generation, migrations, and diagnostics.