TypeScript · Backend · MIT
IN DEVELOPMENT

Write the application.
Not the plumbing.

A TypeScript backend for people who build applications. Secure by default, small by design: routes, sessions, access rights, models, Postgres or SQLite, workers and logs in one package, written together.

$npm install @r-libre/z4js

Most Node backends start as a blank Express app and grow by accretion.

z4js starts with everything refused.

01 / MODEL

A small mental model.

The main concepts are deliberately few. Use TypeScript and Node when they already solve the problem, and add an abstraction only where it earns its place.

01

Config

What the deployment is. The class is the schema of the file: an unknown key is an error, and secrets live in separate files.

this.secret( "mail.passwordFile" )
02

Model

What the database holds. A model manages a table and the queries on it: SQL is written there, nowhere else.

notesModel.get( id )
03

EndPoints

What a resource answers. An object that only notes its routes: created anywhere, tested alone, mounted in several groups.

this.get( "/item/:id", … )
04

RouteGroup

Who may reach it. A prefix and a decision, guarded or unprotected, written in the main.

RouteGroup.guarded( … )
05

Access

What a user may do. Four actions per resource, nothing else, checked in every handler.

notes/create
06

Sessions

Who the user is. Opaque tokens, no cookies, refresh tokens rotated on every use.

sessions.guard
07

Workers

What runs beside the requests. Classes registered by name, messages both ways, named mutexes.

stats.call( "count", … )
08

Logger

What happened. One line per event: a stable name, then the data in JSON.

req.log.info( "note.created" )
02 / JUST TYPESCRIPT

The whole surface, in the main.

A group is either guarded or unprotected, and you have to say which one. An open route stands out in review instead of hiding behind a forgotten middleware.

  • Guarded or unprotected, always explicit
  • Plain classes, mounted in groups
  • No decorators, no injection container
  • Code that runs when you call it
main.tsTypeScript
const api = RouteGroup.guarded( "/api", sessions.guard )
  .add( "/notes", new NotesEP( deps ) )
  .add( "/live", live );

const auth = RouteGroup.unprotected( "/auth" )
  .add( "/", sessions.endPoints );

await serve( {
  config, logger,
  groups: [api, auth],
  statics: [{ path: "/", folder: config.www }]
} );
One main · every route visible · nothing implicit
03 / SECURITY

Secure by default.
Not by checklist.

Security is not a chapter at the end of the documentation. It is what happens when you write nothing special.

SAME RULES EVERYWHERE3

Three rules.

Anything not explicitly allowed is refused. The client gets a status and a short message, never an internal detail. Every value from a client is checked before you use it.

SessionsOpaque tokensRefresh token rotationTheft detection PBKDF2-SHA256Step-upAccess rightsRate limits CORSSecurity headersRequest idCentral error handler Security logWebSocket ticketsDeclared uploadsStrict configuration Mandatory TLSRefused by default
SESSIONSno cookies · no JWT

A stolen token ends the session.

Opaque tokens, only their SHA-256 hash stored. 15 minute access tokens, refresh tokens rotated on every use: a reused one ends the session. A sensitive route adds a step-up filter.

this.del( "/item/:id", this.on_delete,
  { filter: sessions.stepUp } );

// without a recent confirmation of identity:
// 403 step-up required
ACCESS RIGHTSresource/action

Four actions per resource. Nothing else.

An import creates, so it needs notes/create: no right is ever invented for a feature. In debug mode, a handler that forgets to check access is reported.

notes/createnotes/readnotes/updatenotes/deletenotes/**
ERRORS + LOGSnothing leaks

The client gets a status. The log gets the cause.

One central handler: the cause goes to the log, never to the response. Security events come from a closed list, never filtered, in their own file.

throw new HttpError( 404, "unknown note" );auth.login.failed · auth.unauthorized · auth.stepup.failed
BUILT FOR APPLICATIONS

The pieces a business backend actually needs.

One package provides them, written together, with the same rules everywhere.

ROUTES

EndPoints

A handler is a method. paramValue, bodyValue and queryValue read one named value, convert it, check it, and return the right TypeScript type; a structured object goes through a Shape. A missing, malformed, too long or out of range value is a 400 that names the parameter and never echoes its value.

async on_update( req: Request, res: Response ) {
  await this.need( req, "notes/update" );

  const id = this.paramValue( req, "id", "uuid" );
  const changes = noteShape.parse( this.bodyValue( req, "note", "object" ) );

  await notesModel.update( id, changes );
  res.json( {} );
}
VALIDATION

Shape

Describe an object once, validate it everywhere: a shape has no Node or browser dependency, so the server and the client share the same one. Only the declared fields are kept, and a forgotten field fails to compile. A refused value is a 400 that names the field, never its value. Never mandatory.

import { Shape } from "@r-libre/z4js/shape";

interface NoteText {
  title: string;
  text: string;
}

// what a client may change in a note
export const noteShape = Shape.object<NoteText>( {
  title: Shape.string( ).trim( ).maxLen( 100 ),
  text: Shape.string( ).maxLen( 10_000 ),
} );

const note = noteShape.parse( data );           // NoteText, or ShapeError: "title": too long (max 100)
const changes = noteShape.parse( data, true );  // Partial<NoteText>: only the fields received
const notes = noteShape.parseArray( data );     // NoteText[]
DATABASE

Model

A model is the abstraction of the database: SQL is written in models, nowhere else. It manages one table, or a few, and the queries on it are its methods: a handler calls notesModel.get( id ) and gets a typed object back. The model also creates its table and migrates it at startup.

// the notes table
export class NotesModel extends Model {
  constructor( ) {
    super( "notes", 40 );
  }

  async get( id: UUID ): Promise<Note> {
    const [note] = await sql<Note[]>`select * from notes where id = ${id}`;
    return note;
  }

  async get_from_author( author: string ): Promise<Note[]> {
    return sql<Note[]>`select * from notes where author = ${author}`;
  }

  async update( id: UUID, changes: NoteText ): Promise<void> {
    await sql`update notes set ${sql( changes, "title", "text" )} where id = ${id}`;
  }
}

export const notesModel = new NotesModel( );
UPLOADS

Files

Refused unless declared. The file arrives with the request of the action, so access is checked before a single byte is read. Each file field has its size limit, files are streamed to disk under a random name, and whatever is not kept is deleted when the answer is sent.

400
413
415
async on_import( req: Request, res: Response ) {
  await this.need( req, "notes/create" );          // before reading a single byte

  const { data } = await this.filesOf( req, {
    data: { maxBytes: 1_000_000, types: ["text/csv"] },
  } );
  const comment = this.bodyValue( req, "comment", "string", { required: false } );

  // otherwise deleted at the end of the request
  await data.keep( join( config.data, "imports", data.id ) );
  res.status( 201 ).json( { id: data.id } );
}
THREADS

Workers

A worker is a class and a name, running in a thread of its own. Starting one gives the object you talk to: post, call, broadcast, on. A class can be started several times, each worker with its name and its own data: one device, one worker. A worker receives its messages one at a time in onMessage, or reads them itself in its loop to stay reachable in the middle of heavy work. A crashed worker is logged, its calls fail and its mutexes are released.

// one worker per device: scans it without end, and stays reachable between two scans
class Device extends Worker {
  private link: Link;
  private values: number[] = [];

  onStart( ) {
    const { ip } = this.data as { ip: string };
    this.link = openLink( ip );
  }

  onRun( ) {
    let msg: WorkerMessage;

    while( !this.signal.aborted ) {
      if( msg = this.peekMessage( ) ) {              // never waits, sees the stop too
        const { address, value } = msg.data as { address: number, value?: number };

        if( msg.type === "read" ) {
          msg.reply( this.values[address] );         // answers the call
        }
        else if( msg.type === "write" ) {
          this.link.write( address, value );
        }
      }

      this.values = this.link.scan( );               // heavy, synchronous
    }
  }

  onStop( ) {
    this.link.close( );
  }
}

Worker.register( "device", Device );

// main.ts: one device, one worker
const press = await workers.start( "device", { name: "press", data: { ip: "10.0.0.5" } } );
const oven = await workers.start( "device", { name: "oven", data: { ip: "10.0.0.6" } } );

press.post( "write", { address: 12, value: 1 } );
const value = await oven.call( "read", { address: 3 } );
WEBSOCKETS

Channel

A channel notes its WebSocket endpoints and is mounted in a group, like end points. In a guarded group, the client asks for a ticket with a POST, then opens the socket within one second: the ticket is one-time, bound to the endpoint and the user. Messages of one socket are processed one at a time, in order, so per-socket state needs no lock. To push events, the channel keeps its open sockets and gives the end points a method to call.

// live notifications of the notes
export class LiveChannel extends Channel {
  private readonly sockets = new Set<WSocket>( );

  constructor( ) {
    super( );
    this.route( "/notes", {
      onOpen: socket => { this.sockets.add( socket ); },
      onMessage: ( ) => { },                  // the clients only listen
      onClose: socket => { this.sockets.delete( socket ); },
    } );
  }

  // called by the end points
  notify( event: object ) {
    for( const socket of this.sockets ) {
      socket.send( event );
    }
  }
}

// POST /api/live/notes                → { ticket }
// wss://host/api/live/notes?ticket=…  → socket
04 / SQL

Postgres or SQLite.
One style.

Postgres through postgres.js for sites, SQLite through node:sqlite for small projects and desktop apps. Both are written the same way, in the models, with tagged templates, and values are always bound. No ORM, no query builder.

const [note] = await sql`select * from notes where id = ${id}`;
await sql`insert into notes ${sql( note )}`;
await sql`update notes set ${sql( changes, "title", "text" )} where id = ${id}`;
Two engines. Same code. No added dependency for SQLite.
05 / DEPENDENCIES

Very few dependencies.

Five packages, that is all. No ORM, no validation library, no logger, no session store, no JWT library, no upload middleware. Sources are published as TypeScript, as is: what you debug is what was written.

TypeScript source5 dependenciesNo side effect at import
YOUR BACKENDdepends on
express 5postgresws@fastify/busboyx4buildORMJWTvalidation
↓ build
demo bundle1280 KB → 776 KB
Its workers bundle only what they use: 684 KB → 29 KB.
06 / DEVELOPER EXPERIENCE

Logs you can read.
No ceremony.

z4js keeps the daily work short: readable logs, an API description read from your sources, and threads you can actually debug.

Logs you can grepOne line per event: date, level, request id, event name, then the data in JSON.
z4js apidocThe TypeScript compiler reads your sources and writes an OpenAPI 3 description. No annotations, no decorators.
TypeScript end to endSources are published as TypeScript: what you debug is what was written.
Threads you can debugEach thread carries its name in the debugger, and calls never time out while you sit on a breakpoint.
Try the demo
$ git clone https://github.com/rlibre/z4js
$ cd z4js/demo/frontend
$ npm install && npm run build
$ cd ../backend
$ npm install && npm run build
$ npm run start:log

# a notes application: z4js backend, x4js frontend
07 / HUMANS + MACHINES

Readable by humans.
Predictable for machines.

z4js ships an AI guide (the rules) and an AI context (the API). Agents can also inspect the TypeScript sources shipped in node_modules/@r-libre/z4js.

SECURE BY DEFAULT. SMALL BY DESIGN.

Use the simplest tool
that fits.

CLIENT SIDE

x4js.
The same idea, client side.

x4js is the UI counterpart of z4js: the same philosophy on both sides. Plain TypeScript classes, very few dependencies, and code that runs when you call it. More than 50 components for dense, professional interfaces.

x4jsTypeScript UI framework · MITVisit x4js.org →