Skip to content

Keep shipping as your backend grows.

Nile Js is a TypeScript-first, service and actions oriented backend framework. Built for small teams and coding agents that iterate fast.

bunx @nilejs/cli new my-app

How It Works

Services And Actions Architecture

A service groups related actions. Every call names one service and one action.

One call{ service: "projects", action: "create" }

Serviceprojects

  • Actioncreate
  • Actionlist
  • Actionarchive

Servicebilling

  • Actioncharge
  • Actionrefund

Servicemembers

  • Actioninvite
  • Actionremove
  1. Validate input
  2. Run handler
  3. OkErr

Errors As Values, Make The Happy Path Obvious

Every failure is a value the handler returns, never a surprise throw. The caller checks it first, then reads the result.

services/orders/actions/quote.tsBackend
import { createAction } from "@nilejs/nile";
import { Err, Ok } from "@nilejs/nile/fp";
import { z } from "zod";
import { productModel } from "@/db/models";

const quoteSchema = z.object({
  id: z.string().min(1),
  quantity: z.number().int().positive(),
});

type QuoteData = z.infer<typeof quoteSchema>;

const quoteHandler = async (data: QuoteData) => {
  const product = await productModel.findById(data.id);
  if (product.isErr) {
    return Err("Product not found");
  }

  if (product.value.stock < data.quantity) {
    return Err("Not enough stock");
  }

  return Ok({ total: product.value.price * data.quantity });
};

export const quoteAction = createAction({
  name: "quote",
  description: "Quote a product order",
  validation: quoteSchema,
  handler: quoteHandler,
});
components/quote.tsxFrontend
const result = await nile.invoke({
  service: "orders",
  action: "quote",
  payload: { id, quantity },
});

if (result.isErr) {
  showError(result.error);
  return;
}

showTotal(result.value.total);

Failure pathHappy path

REST RPC Innovation

REST RPC borrows from both: plain HTTP and JSON from REST, named operations from RPC. One endpoint, /api/services, takes three intents, so there are no route trees to design or keep in sync.

An agent asks what the projects service can do.

POST /api/servicesAgent
{
  "intent": "explore",
  "service": "projects",
  "action": "*",
  "payload": { "discoverySecret": "dev-secret" }
}
200 OK
{
  "status": true,
  "message": "Actions for 'projects'",
  "data": {
    "actions": [
      {
        "name": "create",
        "description": "Create a project",
        "isProtected": false,
        "validation": true,
        "accessControl": []
      }
    ]
  }
}

Domain Driven

Open the domain, find the action, follow it to the model. Nile checks this layout at startup.

  • src
  • index.ts
  • services
  • services.config.ts
  • projects
  • actions
  • create-project.ts
  • archive-project.ts
  • modules
  • db/models
  • hooks
Services
One folder per business domain
Actions
One file per operation
Modules
Rules shared within the domain
Models
Data access that returns Results
Hooks
Policies around every action

The full layout is in the application structure guide.

  1. Request
  2. Hooks
  3. Action
  4. Model
  5. Result

Agents Ready

Named actions, typed input and one registry give a coding agent the same map your team uses. When a call fails, Nile tells the agent exactly what to fix.

Start prompt

You are working on a Nile Js backend (TypeScript-first, service and actions oriented).

Before you write code:
1. Read https://nile-js.github.io/nile/llms.txt, and node_modules/@nilejs/nile/SKILL.md if the package is installed.
2. If there is no project yet, create one with: bunx @nilejs/cli new my-app
3. Read src/services/services.config.ts, then the action files of the service you will change.

When you add or change an action:
- Use a named Zod schema, an inferred input type, a named handler and createAction<T>.
- Return Ok(value) or Err(message) from @nilejs/nile/fp. Do not throw for expected failures.
- Register the action in its service's actions list.
- Run ./node_modules/.bin/tsc --noEmit and fix every error before you continue.

When a call fails validation, read data.issues, fetch the action's input with the "schema" intent, fix the payload and retry.
If a Nile Js API is not in the documentation or the installed package, say so instead of inventing it.
Stop after each step and tell me what you changed.

My first task: 
  1. The agent calls an action

    It sends the payload it expects projects.create to accept.

  2. Nile names every problem

    A 400 answer lists each failing field in data.issues, with its path.

  3. The agent checks the contract

    The schema intent returns the action's JSON Schema. The agent fixes the payload and retries.

POST /api/servicesAgent
{
  "intent": "execute",
  "service": "projects",
  "action": "create",
  "payload": { "name": "" }
}
400 Bad Request
{
  "status": false,
  "message": "✖ Name is required\n  → at name",
  "data": {
    "errorCode": "jN8sQ4tV2pLm",
    "issues": [
      { "path": "name", "message": "Name is required" }
    ]
  }
}

TypeScript Backend,
Any JavaScript Frontend

01Define it on your backend

services/projects/actions/create-project.ts
import { createAction } from "@nilejs/nile";
import { Ok } from "@nilejs/nile/fp";
import { z } from "zod";

const createProjectSchema = z.object({
  name: z.string().trim().min(1, "Name is required"),
});

type CreateProjectInput = z.infer<typeof createProjectSchema>;

const createProjectHandler = (data: CreateProjectInput) => {
  const project = {
    id: crypto.randomUUID(),
    name: data.name,
  };

  return Ok({ project: project });
};

export const createProject = createAction({
  name: "create",
  description: "Create a project",
  validation: createProjectSchema,
  handler: createProjectHandler,
});

02Call it from React

components/create-project-button.tsx
import { createNileClient } from "@nilejs/client";

const nile = createNileClient({
  baseUrl: "http://localhost:8000/api",
});

export function CreateProjectButton() {
  const handleClick = async () => {
    const result = await nile.invoke({
      service: "projects",
      action: "create",
      payload: { name: "Customer portal" },
    });

    if (result.isErr) {
      console.error(result.error);
      return;
    }

    console.log(result.value);
  };

  return <button onClick={handleClick}>Create project</button>;
}

Go Full Functional Programming With slang-ts

Nile Js is built on slang-ts, a small functional programming library from the creator of Nile Js. Your handlers already return its Results. Import all of it from @nilejs/nile/fp, with no extra dependency.

  • ResultUsed by Nile

    Ok · Err

    Success or failure as a value. Every Nile handler returns one.

  • safeTryUsed by Nile

    safeTry(fn)

    Runs code that can throw or reject and hands back one Result.

  • Option

    option · Some · None

    A value that may be missing, without null checks everywhere.

  • match

    match(value, cases)

    Handles every case of a Result or Option, checked by the compiler.

  • pipe

    pipe(value, ...steps)

    Composes Result-returning steps that stop at the first Err.

  • SuperPromise

    superPromise(task, options)

    Retry, time out or cancel a promise, then settle into Ok or Err.

modules/load-settings.ts
import { Err, Ok, match, option, safeTry } from "@nilejs/nile/fp";

const port = match(option(process.env.PORT), {
  Some: (presentPort) => {
    return Number(presentPort.value);
  },
  None: () => {
    return 8000;
  },
});

export const loadSettings = async (path: string) => {
  const file = await safeTry(() => Bun.file(path).json());
  if (file.isErr) {
    return Err(`Could not read ${path}`);
  }
  return Ok({ ...file.value, port });
};
slang-ts on npm

Measured With
A 300-Action Backend.

We measured the same authenticated shopping workflow in ten frameworks on an everyday PC, to see how Nile Js holds up under realistic load. Your numbers will depend on your application and hardware.

Ecommerce APIAverage requests per second · higher is better
Six-round throughput averages with payload validation enabled. JWT and CORS enabled in both modes.
FrameworkRelative throughputReq/s
Nile JsRange 6194 to 7964 requests per second.7,290
HonoRange 6140 to 8105 requests per second.7,067
ElysiaRange 3405 to 8128 requests per second.6,797
EffectRange 4790 to 5644 requests per second.5,343
FastifyRange 1553 to 3369 requests per second.2,790
NestJSRange 1068 to 3067 requests per second.2,302
AdonisJSRange 1269 to 2534 requests per second.2,001
ExpressRange 940 to 2376 requests per second.1,729
tRPCRange 680 to 1518 requests per second.1,295
EncoreRange 635 to 680 requests per second.668
Workload
Up to 32 shoppers · 5,000 six-request journeys a sample · 6 rounds
Checks
Responses and order counts verified · in-memory data, no database
Machine
Intel Core i5-6300U · 4 logical CPUs · 15.5 GiB · October 2026

App and client shared a desktop with other apps running. Adapter choice and machine variation affect these results.

Hussein Kizza
Hussein KizzaCreator of Nile Js

More To Ship,
But Still A Small Team.

I needed something easy to work with as a solo engineer, in a small team and alongside AI agents, where the right thing is obvious and easy to do, with maximum predictability of what goes where and each domain owning its concerns. It had to be lazy and boring, with no fighting over or deciding how to name endpoints, so that I could focus on the business and what I need to do rather than framework plumbing. That is how Nile Js was born.

Now my team and I use it for all our systems. We think in services and business operations. When a change comes in, we know which domain to open and which action to follow. Error handling, logs and data validation are first class, so we can sleep well while serving real-world users.

1000+
actions in real world systems
2 years
in production
1000s
of requests per day across services

The Thinking Behind Nile Js.

Hussein Kizza and Ssali Jonathan on the Nile Js approach to backend APIs. Watch on YouTube ↗

Built-In Features

The pieces a small backend team reaches for. Use only what your application needs.

Validation and error handling

Zod validates input before your handler runs. Results keep expected errors beside the happy path.

Read the guide
actions/rename-project.ts
import { Err, Ok } from "@nilejs/nile/fp";
import { z } from "zod";

const renameSchema = z.object({
  name: z.string().min(1),
});

type RenameInput = z.infer<typeof renameSchema>;

const renameHandler = (data: RenameInput) => {
  if (data.name === "system") {
    return Err("Choose a different name");
  }

  return Ok({ name: data.name });
};

Authentication and hooks

Verify JWTs on protected actions and run a global hook before every action. Your application owns the rules.

Read the guide
server/access.ts
import { createNileServer } from "@nilejs/nile";
import type { BeforeActionHandler } from "@nilejs/nile";
import { Err, Ok } from "@nilejs/nile/fp";

const requireSession: BeforeActionHandler<boolean, string> = (hookContext) => {
  const session = hookContext.nileContext.getSession("rest");

  if (hookContext.action.isProtected && session === undefined) {
    return Err("Sign in to continue");
  }

  return Ok(true);
};

const server = await createNileServer({
  serverName: "Workspace",
  services: services,
  auth: { secret: config.jwtSecret, method: "header" },
  onBeforeActionHandler: requireSession,
});

Context and logging

Share resources once. Each call keeps its own session, and logs carry request IDs.

Read the guide
modules/log-project.ts
import { getContext } from "@nilejs/nile";

const logProjectCreated = (projectId: string) => {
  const context = getContext();
  const logger = context.resources?.logger;

  if (logger === undefined) {
    return;
  }

  logger.info({
    atFunction: "logProjectCreated",
    message: "Project created",
    data: { projectId: projectId },
  });
};

Queues, debounce and throttle

Queue, debounce, throttle or batch ordinary functions with limited concurrency.

Read the guide
modules/resize-queue.ts
import { utils } from "@nilejs/nile";

const resizeImage = async (imageId: string) => {
  const image = await images.resize(imageId);
  return image.url;
};

const resizeQueue = utils.createQueue({
  task: resizeImage,
  concurrency: 4,
  capacity: 100,
});

const result = await resizeQueue.run("image-42");

Telemetry

Readable logs first. Export OpenTelemetry traces and metrics when you need them.

Read the guide
server/diagnostics.ts
import { createNileTelemetry } from "@nilejs/nile";

const telemetry = await createNileTelemetry({
  serviceName: "shop",
  endpoint: config.otelEndpoint,
});

export const execution = {
  diagnostics: {
    telemetry: telemetry,
    slowMs: 1000,
  },
};

WebSockets

Typed topics validate every message before Socket.IO delivers it. Each topic decides who can receive and send.

Read the guide
messaging/order-updates.ts
import { createTopic, createTopics, getContext } from "@nilejs/nile";
import { z } from "zod";

const orderUpdated = createTopic({
  name: "orders.updated",
  data: z.object({
    orderId: z.string(),
    status: z.enum(["pending", "paid"]),
  }),
  canReceive: ({ user }) => user !== undefined,
});

export const topics = createTopics([orderUpdated]);

const notifyOrderPaid = async (orderId: string, userId: string) => {
  const { socket } = getContext({ topics: topics });

  return await socket.send({
    topic: "orders.updated",
    to: { userId: userId },
    data: { orderId: orderId, status: "paid" },
  });
};

Cron jobs

Run jobs at midnight, weekly, once, on an interval or with a cron expression, in a real timezone.

Read the guide
server/schedules.ts
import type { ScheduledJob } from "@nilejs/nile";

const sendWeeklySummary = async () => {
  const summary = await buildSummary();
  await emailTeam(summary);
};

export const weeklySummary: ScheduledJob = {
  name: "weekly-summary",
  schedule: {
    weekly: "monday",
    at: "09:00",
    timezone: "Africa/Kampala",
  },
  handler: sendWeeklySummary,
};

Database models

Optional Drizzle helpers return Results from CRUD and generate reusable Zod schemas.

Read the guide
models/projects.ts
import { utils } from "@nilejs/nile";
import { database } from "../db/client";
import { projects } from "../db/schema";

const projectModel = utils.createModel(projects, {
  name: "project",
  db: database,
});

const findProject = async (projectId: string) => {
  return await projectModel.findById(projectId);
};

API discovery and schemas

Opt-in discovery lists actions and their schemas. Export them so the CLI can generate input types.

Read the guide
scripts/export-contracts.ts
import { server } from "../server";

const result = await server.schema({
  path: "./contracts/nile.schemas.json",
});

if (result.isErr) {
  console.error(result.error);
} else {
  console.log("Contracts exported");
}

HTTP and direct calls

Call the same action over HTTP or directly in your backend. Run on Bun native or Hono.

Read the guide
modules/create-from-job.ts
import { server } from "../server";

const result = await server.invoke({
  service: "projects",
  action: "create",
  payload: { name: "Customer portal" },
});

if (result.isErr) {
  console.error(result.error);
} else {
  console.log(result.value);
}

Retries and utilities

Jittered retries, bounded TTL storage and safe database calls under one utils namespace.

Read the guide
modules/check-delivery.ts
import { utils } from "@nilejs/nile";

const checkDelivery = async () => {
  return await courier.getStatus("parcel-42");
};

const result = await utils.retryFnWithJitter({
  fn: checkDelivery,
  maxAttempts: 5,
  onResult: (attempt) => {
    if (attempt.result.isErr) {
      return attempt.retry();
    }

    return attempt.end(attempt.result.value);
  },
});

Rate limiting

Share one action quota across HTTP and direct calls. Fixed or sliding windows, token buckets and cooldowns.

Read the guide
server/quotas.ts
import { utils } from "@nilejs/nile";
import type { ExecutionDetails } from "@nilejs/nile";

const limiter = utils.createRateLimiter({
  strategy: "token-bucket",
  capacity: 20,
  refillPerSecond: 5,
  maxKeys: 10000,
});

const getQuotaKey = (details: ExecutionDetails) => {
  const clientKey = details.context.clientKey;

  if (clientKey === undefined) {
    return "anonymous";
  }

  return clientKey;
};

export const execution = {
  rateLimit: { store: limiter, key: getQuotaKey },
};

File uploads

Multipart uploads arrive as actions, with file count, size and type limits. Serve static files when useful.

Read the guide
server/files.ts
const fiveMegabytes = 5 * 1024 * 1024;

export const rest = {
  enableStatic: true,
  staticDir: "./assets",
  uploads: {
    enforceContentType: true,
    limits: {
      maxFiles: 3,
      maxFileSize: fiveMegabytes,
    },
    allow: {
      extensions: [".png", ".jpg"],
      mimeTypes: ["image/png", "image/jpeg"],
    },
  },
};

Readiness and graceful shutdown

Startup stats, readiness checks and a shutdown that finishes accepted work.

Read the guide
server/shutdown.ts
import { server } from "../server";

const stats = server.stats();
const isReady = server.lifecycle.isReady();

const report = await server.lifecycle.shutdown({
  timeoutMs: 10000,
});

if (report.timedOut) {
  console.error("Shutdown deadline reached");
}

Snippets reference your own config and modules. In-memory queues, quotas and schedules work within one process; use an external system for durable or cross-process coordination.

Open The Domain.
Find The Action. Get To Work.

Every operation has a well known place, so a new teammate knows where to start. Application structure ↗

  • src/
  • services/
  • projects/
  • actions/
  • archive-project.ts
  • modules/
  • services.config.ts
services/projects/actions/create-project.ts
import { createAction } from "@nilejs/nile";
import { Ok } from "@nilejs/nile/fp";
import { z } from "zod";

const createProjectSchema = z.object({
  name: z.string().trim().min(1, "Name is required"),
});

type CreateProjectInput = z.infer<typeof createProjectSchema>;

const createProjectHandler = (data: CreateProjectInput) => {
  const project = {
    id: crypto.randomUUID(),
    name: data.name,
  };

  return Ok({ project: project });
};

export const createProject = createAction({
  name: "create",
  description: "Create a project",
  validation: createProjectSchema,
  handler: createProjectHandler,
});

Made Possible By Open Source.

Nile Js stands on these projects. Thank you to everyone who builds and maintains them.

Help shape Nile Js.

Nile Js is open source under the MIT license. Report an issue, improve the docs or send a pull request. Every contribution helps the next team ship.

A Small Framework.
Room For Your People.

More libraries by the creator of Nile Js

Frequently Asked Questions

Who is Nile Js for?

Small teams building growing business applications: internal tools, dashboards, billing systems and product backends. A few conventions give each operation a recognizable home, so the next feature does not need a new structure.

Does Nile enforce domain-driven design?

Yes, so the codebase still scales as it grows. Each business domain is a service under src/services, listed in services.config.ts, with one file per action. Nile checks that layout at startup: the CLI starter refuses to boot on a violation, and existing apps get warnings until they opt in.

How are actions addressed?

Every call is a POST to /api/services whose body names the intent, service, action and payload. Custom routes remain available for webhooks and health checks.

What happens when an action fails?

Return Err(message) for an expected failure. A handler that throws is caught and answered as a failed Result. Startup configuration errors can still throw, and transport errors can return HTTP 500.

Does Nile handle access control?

Nile verifies JWTs for protected actions when server authentication is configured. Your application implements role, organization and resource policies in hooks or business logic.

How does the frontend connect?

Use @nilejs/client to invoke named actions and read Results. The CLI can generate input types from your service registry, so names and payloads are checked when you pass them to the client.

Can agents discover and execute operations?

When you enable discovery, the explore and schema intents expose operation metadata and input schemas. An agent integration still chooses permitted tools, supplies credentials and invokes actions. Discovery is off by default.

Must I use Bun, Hono or Drizzle?

No. Choose Bun's native server, or the Hono adapter on Bun or Node.js. Bring your own database and data access; the Drizzle helpers are optional.