Nerak is a declarative framework for building asynchronous web applications in C.
* **No build configuration.** Compilation, hot code reloading, and HMR are handled by the framework. No build scripts, package managers, or ORMs. SQL and HTML assets are discovered automatically.
* **Memory, concurrency, and I/O managed by the framework.** Application code does not call `malloc`/`free` or manage threads, mutexes, or locks. Queries run as prepared statements. Pipeline steps emit OpenTelemetry spans, logs, and errors automatically.
* **Durable tasks and events.** Both are persisted. After a crash, incomplete tasks resume at the step where they stopped and undelivered events replay on the next boot.
* **Bundled modules.** Datastar, HTMX, Tailwind, DaisyUI, SQLite, Postgres, MySQL, Redis/Valkey, DuckDB, and auth. Multi-tenant database support is built in.
---
## Table of Contents
* [Quick Start](#quick-start)
* [Philosophy](#philosophy)
* [Guide](#guide)
* [Reference](#reference)
* [Architecture](#architecture)
* [Tooling](#tooling)
* [Built With](#built-with)
* [License](#license)
---
## Quick Start
Everything runs in Docker. No other local dependencies.
# Includes file watching, auto compilation, hot code reloading, HMR
docker compose up
```
Create `app.c` with the example below. Nerak watches for changes and hot-reloads on save. Use your own editor, or attach to the built-in TUI with `docker compose attach nerak` for an integrated editor, LSP, and console.
A module is any `.c` file declaring `config(name){...}`; `app.c` declares the `app` module. `config(app)` runs once at boot. `context()` registers a named template inline; `resource()` declares the `home` endpoint mapping `/` to a GET pipeline that renders that template. See the [Guide](#guide) for a step-by-step walkthrough.
---
## Philosophy
An application is a data transformation: input arrives, gets transformed, leaves as output.
All assets and tooling are standard: raw SQL, JSON, Markdown, and HTML/CSS/JS via Mustache templates, business logic is plain C, lldb for debugging, Playwright and Criterion for testing, OpenTelemetry for observability. Nerak arranges these into pipelines: ordered lists of steps that turn a request into a response.
### Everything is a String
The web is text: HTTP, HTML, JSON, SQL. The pipeline context stores and passes data as strings. There is no intermediate parsing or serialization layer. Strings are interpolated into SQL, templates, and URLs with `{{context_key}}`.
### CLAD
Four principles:
* **(C)omposable:** small, independent steps chain into feature pipelines.
* **(L)ocality of Behavior:** behavior is apparent from reading the code. SQL, templates, and logic for a feature live together, not spread across model, view, and controller trees.
* **(A)utonomous:** modules are self-contained: own schemas, migrations, seeds, routes, UI, and logic. The compiler enforces boundaries.
* **(D)omain Based:** each module owns one slice of the app. A `todos` module defines everything related to todos and nothing else.
* [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour)
---
## Guide
Builds a todo app one concept at a time. See the [Reference](#reference) for full options on each step, helper, and field. Nerak discovers assets automatically and seeds each into the context of the module that owns it, based on file location (see [Assets](#assets)). Steps 1–6 use a single module, `app.c`; step 7 adds `todos` and `activity` modules.
* [1. Pages and Templates](#1-pages-and-templates)
* [2. Show Data](#2-show-data)
* [3. Accept Input](#3-accept-input)
* [4. Nested Data](#4-nested-data)
* [5. Calling APIs](#5-calling-apis)
* [6. Tasks](#6-tasks)
* [7. Modules and Events](#7-modules-and-events)
### 1. Pages and Templates
Each `resource(...)` declares a named URL endpoint; each verb pipeline is a list of steps. `mustache("home", "home_s")` renders the template asset `home` into context key `home_s`, and `respond("home_s")` sends it. Reference resources by name with `{{url:...}}`.
Both pages share a layout, so `home` doubles as the layout: it declares the nav and a `{{$body}}` block whose default is the welcome page. The `todos` page extends it with `{{< home}}...{{/home}}`, overriding that block. Any template that declares a `{{$block}}` can be a parent; there is no special layout type.
Bring in SQLite with `#include <sqlite.h>`, declare a database with `sqlite_config(...)`, and read with `sqlite_query()`. SQL files are assets like templates: `get_todos.sql` becomes the asset `get_todos`.
Query parameters: database name, SQL asset, context key for the result table (`todos_data`). The template walks the result with `{{#todos_data}}...{{/todos_data}}`. Migrations and seeds run on first connection. See [Databases](#databases) and [query](#query).
### 3. Accept Input
Add a `.post` verb that validates, inserts, and redirects (POST-redirect-GET). A resource-scoped `.errors` handler re-renders the form on validation failure.
`input()` validates and promotes `title` to app scope; the `{{title}}` in `create_todo.sql` binds as a prepared-statement parameter. On failure, `n_bad_request` triggers the handler, which `reroute`s back into the GET pipeline in-process. The `input:` and `error:` scopes survive the reroute, so the form repopulates with `{{input:title}}` and shows `{{error_message:title}}`. See [input](#input), [Error and Repair Pipelines](#error-and-repair-pipelines), and [redirect and reroute](#redirect-and-reroute).
Link each list item to its detail page. `{{url:todo}}` resolves to the `todo` resource's pattern (`/todos/:id`) and fills `:id` from the current row, so no argument is needed:
Both queries in one `sqlite_query()` call run concurrently. `join()` lifts `comments` inside each `todo_data` record, so the template reaches `{{#comments}}` from within `{{#todo_data}}`. `.err_on_empty = true` returns 404 when the id matches nothing. See [join](#join) and [query](#query).
`fetch()` calls external HTTP services like a query calls a database. JSON parses into context tables; multiple items in one `fetch()` run concurrently.
Both requests run concurrently under one `fetch()` call. The JSON parses into context tables the template walks with `{{#quote}}` and `{{#weather}}`. `fetch()` also supports other verbs, headers, request bodies, and interpolated URLs. See [fetch](#fetch).
A task is a named, reusable pipeline. Define it once with optional `.cron`; dispatch durable background runs with `dispatch("name")` (from `dispatch.h`).
`.cron` and `dispatch(...)` both run the task on a task reactor, off the request reactors, so the POST returns immediately. Dispatched tasks are durable: a crash mid-task resumes on the next boot. To hand values to a task, list them under `.accepts`; `notify_new_todo` pulls in `title` that way. `dispatch()` comes from `dispatch.h`. See [Task Pipelines](#task-pipelines).
Split features into modules that talk through pub/sub events. A module is any `.c` file declaring `config(name){ ... }`, registering that module's resources, databases, tasks, and subscribers. Nerak discovers every `config(...)` on disk. A module's assets live in its `name/` folder and are private to it; assets at the project root are shared across modules (see [Assets](#assets)).
This step moves todos into its own module and adds an `activity` module that records an entry whenever a todo is created. `app.c` keeps just the `home` resource; `home.html` stays at the project root, shared across modules:
When the POST calls `emit("todo_created")`, Nerak propagates the keys named in `publish(...).with` (`title`) to every subscriber. The `activity` module writes its row with no direct link to the publisher. Events are durable: undelivered ones replay after a crash. Adding a third subscriber is a new module with its own `subscribe(...)`; the publisher does not change. See [Modules and Composition](#modules-and-composition) and [Event Pipelines](#event-pipelines).
---
## Reference
* [Context](#context)
* [Templates](#templates)
* [Assets](#assets)
* [Databases](#databases)
* [Resource Pipelines](#resource-pipelines)
* [Error and Repair Pipelines](#error-and-repair-pipelines)
* [Event Pipelines](#event-pipelines)
* [Task Pipelines](#task-pipelines)
* [Pipeline Steps](#pipeline-steps)
* [Imperative API](#imperative-api)
* [Conditionals](#conditionals)
* [Iteration](#iteration)
* [Modules and Composition](#modules-and-composition)
* [Additional Modules](#additional-modules)
* [Static Files](#static-files)
* [External Dependencies](#external-dependencies)
### Context
Pipelines read from and write to a shared, scoped key-value store that lives for one request. Every step draws inputs from context and writes outputs back.
Three scopes: `input:xxx` for raw request parameters, `error:xxx` for validation/error data, and unprefixed names for app scope (query results, validated inputs, computed values). `input()` promotes values from `input:` to app scope.
### Templates
Nerak uses Mustache and MDM (Mustache + Markdown) templates. The full Mustache base spec is supported except dot notation: `{{a.b}}` does not work; use `{{#a}}{{b}}{{/a}}`.
Base-spec features:
- **Interpolation**: `{{name}}` (HTML-escaped), `{{{name}}}` or `{{&name}}` (unescaped).
- **Sections**: `{{#name}}...{{/name}}` renders when truthy and iterates over arrays.
- **Inverted sections**: `{{^name}}...{{/name}}` renders when falsy or empty.
- **Comments**: `{{! ignored }}`.
- **Set delimiters**: `{{=<% %>=}}`.
- **Partials**: `{{> name }}` inlines the asset `name`, rendered against the current scope.
- **Layout inheritance**: `{{< parent}}{{$block}}override{{/block}}{{/parent}}` renders `parent` with each `{{$block}}default{{/block}}` block replaced by the override. Any asset declaring blocks can be a parent.
Built-in helpers use `{{helper:args}}` syntax. Arguments are colon-separated, in order; each can be a literal or a context key.
**`{{precision:field:N}}`**: format a numeric value with N decimal places.
<a href='{{url:todo}}'>{{title}}</a> <!-- /todos/:id, filled per row -->
{{/todos_data}}
{{#todo}}
<a href='{{url:todo}}'>{{title}}</a> <!-- /todos/:id, from a single record -->
{{/todo}}
```
**`{{asset:filename}}`**: resolve a file in `public/` to a cache-busted URL (content checksum + immutable cache headers). See [Static Files](#static-files).
**`{{csrf:param}}`**: emit a CSRF token for URL query strings. Generates a random hash, sets it on an httponly/secure/samesite cookie, outputs `csrf=<token>` inline.
**`{{http_verb:param}}`**: emit an `http_method` override for URL query strings, letting a link reach a non-GET verb. One per verb: `{{http_get:param}}`, `{{http_post:param}}`, `{{http_put:param}}`, `{{http_patch:param}}`, `{{http_delete:param}}`, `{{http_sse:param}}`; each outputs `http_method=<verb>`. See [Resource Pipelines](#resource-pipelines).
**`{{http_verb:input}}`**: emit a hidden `<input>` carrying the `http_method` override, letting a `<form>` (GET/POST only) reach any verb. One per verb: `{{http_get:input}}`, `{{http_post:input}}`, `{{http_put:input}}`, `{{http_patch:input}}`, `{{http_delete:input}}`, `{{http_sse:input}}`; each outputs `<input type='hidden' name='http_method' value='<verb>'>`.
Every non-`.c` file is an asset. An asset is loaded into context under its name in each module that seeds it (see below), as if `context(name, contents)` had been called there. Common types are Mustache templates (`*.html`), Markdown (`*.md`), and SQL (`*.sql`); the rule is general.
An asset's name is the filename's basename (the part before the first dot). `get_todos.sql` seeds `get_todos`, `todos.html` seeds `todos`, `home.md` seeds `home`. Steps read these like any other context value: `mustache("todos", "todos_s")`, `sqlite_query({"todos_db", "get_todos", "todos_data"})`, and `.migrations`/`.seeds` entries (`{"create_todos_table"}`).
`mustache()`, `mdm()`, and the engine `*_query()` steps read a string from context by key and interpret it as a template or SQL. The step interprets whatever is under the key when it runs.
`context(name, value)` does the same seeding from a string instead of a file. Useful for content too small to warrant its own file:
context("hello", "<h1>Hello, world!</h1>"); // then mustache("hello", "hello_s")
context("ping", "select 1"); // then sqlite_query({"db", "ping"})
```
A module is seeded with every asset from its own folder up to the project root. Assets at the root are shared by all modules; assets inside a module's folder are seen only by that module. The scan runs up the tree, not sideways, so a module never sees another module's folder:
```
.
├── layout.html # → every module
├── 404.html # → every module
├── partials/
│ └── footer.html # → every module (partials/ has no config())
└── todos/
├── todos.c # the "todos" module
├── todos.html # → todos
└── detail/
└── todo.html # → todos (detail/ has no config())
```
In dev, the scan is live: editing an asset reloads that file into every module holding it, and saving a `.c` file recompiles and reloads that module alone. A production build runs the scan once and compiles each module's assets into its binary; see [Deployment](#deployment).
Each database engine is a module: `#include` its header (e.g. `#include <sqlite.h>`) to activate it, then register one or more databases with `<engine>_config(...)`. Migrations and seeds are forward-only and index-based: they run in array order, each applied once, with new ones appended to the end. Both are tracked in a `nerak_meta` table.
Nerak is resource-based, not route-based. Each `resource(...)` defines a named URL endpoint with HTTP verb pipelines. `{{url:name}}`, `redirect()`, and `reroute()` all take only the resource name; `:params` are read from the current scope by matching key names. Path specificity is automatic: exact matches (`/todos/active`) take priority over parameterized matches (`/todos/:id`) regardless of definition order.
Clients select a verb via the request method, or by passing `http_method` as a query/form parameter. This lets HTML forms (limited to GET/POST) reach any verb, and gives SSE a connection path: `/todos?http_method=sse`. Templates emit it via `{{http_verb:input}}` / `{{http_verb:param}}` (see [Templates](#templates)).
**Resource name *(by order)***: identifier used by `{{url:name}}`, `redirect()`, and `reroute()`.
When a step fails, execution halts and Nerak looks for a handler matching the error code. It checks the resource's own `.errors`/`.repairs` first, then the `error()`/`repair()` handlers in that resource's module, and uses the first match. A resource handler overrides the module's for the same code.
Errors are terminal: the handler sends a response and ends the request. Repairs are resumable: they fix the context and resume the original pipeline at the step after the failure. Repairs resolve first; if no matching repair is found, resolution falls through to errors. Unhandled errors fall through to Nerak's internal handler, which looks for a context template named after the error code, otherwise renders the error message as `text/plain` with the error code as the HTTP status, and surfaces in the TUI console and telemetry.
The `error` scope is shared across `input()` failures and `err_set()` calls: `{{error:name}}`, `{{error_code:name}}`, `{{error_message:name}}`. The raw input value remains in `input:name` for re-rendering forms.
**Built-in error codes:**`n_bad_request` (400), `n_not_authorized` (401), `n_not_found` (404), `n_error` (500). Any integer works; the `m_*` constants are convenience names. Define your own for domain-specific errors, e.g. `#define err_quota_exceeded 723`.
Internal pub/sub for cross-module communication. The publisher does not know who listens; the subscriber does not know who emits. Adding a subscriber means adding a new module with a `subscribe(...)` call; the publisher does not change. Activate with `#include <pubsub.h>` in any module that publishes or subscribes.
Events are durable. When a publisher is declared, Nerak creates a `nerak_events` database to track delivery. If the process crashes, undelivered events replay on the next boot.
**`publish(event, .with = {...})`**: declares an outbound event contract. First value is the event name; `.with` lists context keys to pass along.
**`.errors` / `.repairs`** *(per subscriber)*: each `subscribe(...)` can declare its own handlers, resolved the same way as resource pipelines (the subscriber's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines).
A task is a named, reusable pipeline, defined inside a module with `task(name, { pipeline }, ...)`. Registration and invocation are separate. `run_task("name")` runs a task inline as a step in the calling pipeline, for reusable pipelines composed into workflows. `dispatch("name")` runs it as a durable background job and returns immediately; requires `#include <dispatch.h>`. `.cron` runs it in the background on a schedule, no caller.
Dispatched tasks are durable: the dispatch module creates the persistent task tables and checkpoints context after each step, so a crash mid-task resumes at the step where it stopped on the next boot.
**`.errors` / `.repairs`** *(per task)*: each task can declare its own handlers, resolved the same way as resource pipelines (the task's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines).
Steps are the units of work in a pipeline. Each receives the current context, acts on it, passes control to the next. All steps accept `.if_ctx`/`.not_ctx` for [conditional execution](#conditionals), and `.map`/`.map_key` for concurrent fan-out across rows of a context table (see [Iteration](#iteration)).
Checks request parameters (query string, form body, URL params) against regex patterns. On success, each value is promoted from `input:name` to app scope. On failure, errors land in `error:name` and a `400 Bad Request` triggers the nearest [error/repair pipeline](#error-and-repair-pipelines). All validations in one call complete before the error fires, so all errors are available together for form re-rendering.
Each engine provides its own query step: `sqlite_query()`, `postgres_query()`, `mysql_query()`, `redis_query()`, `duckdb_query()`. All share the same `query_c` shape. By order: first value is the database name (the `.nm` it was registered with), second is the context key holding the SQL, third is the `.ctx_key` for the result table (even single-row results are tables). Multiple items in one step run **concurrently**. Queries use prepared statements; interpolated `{{values}}` are bound, not spliced. For transactions, put `BEGIN`/`COMMIT`/`ROLLBACK` in the SQL.
Nests records from one context table into each matching record of another, like a SQL JOIN in memory. Useful when records come from separate databases or queries. After the step, each outer record gains a new field holding its matched inner records.
**Full context example.** Concurrent query → `join()` → `mustache()`: fetch parent and children from separate queries, render as one nested structure. Blog + comments, single database:
// Fetch both concurrently: one query() call, two items
sqlite_query(
{"blog_db", "get_blog", "blog"},
{"blog_db", "get_comments", "comments"}
),
// Nest each comment into its matching blog record
join("blog", "id", "comments", "blog_id"),
// Enter {{#blog}} first; after join(), comments lives INSIDE each blog record
mustache("blog", "blog_s"),
respond("blog_s")
}
);
```
Context shape at each step:
```
after query(): { blog: [{id, title, content}],
comments: [{id, blog_id, body}, ...] } // two sibling tables
after join(): { blog: [{id, title, content,
comments: [{id, blog_id, body}, ...]}] } // nested inside blog
```
#### fetch
Makes one or more HTTP requests and stores responses in context. JSON parses into tables and records (nested tables for nested JSON); plain-text responses are stored as strings. Like `query()`, multiple items in one step run **concurrently**.
`run()` calls a C function or block inline on the reactor, with access to context via the [Imperative API](#imperative-api). It is where business logic and data shaping lives: enriching query results, aggregating, transforming data between steps, setting flags for [conditional](#conditionals) downstream steps. For short, non-blocking work; call `err_set()` to trigger an error/repair pipeline. Use `run_worker()` instead when the body would stall the reactor.
**Block *(by order)***: inline block, for short logic specific to this pipeline. Here, attaching each challenger's opponent id so the template can render two voting forms with the right winner/loser pairing:
Inside blocks and `.call` functions, context, memory, errors, tables, and records are manipulated through the [Imperative API](#imperative-api).
#### run_worker
`run_worker()` takes the same block or `.call` as `run()` but is for blocking or CPU-bound work: external C libraries, blocking I/O, heavy computation. The work is dispatched to the shared thread pool, releasing the reactor; the pipeline resumes on the original reactor when the call returns. Use it when the body would stall a request reactor.
**Block *(by order)***: inline block, run on the shared thread pool. Here, rendering Markdown through an external C library and freeing its buffer when the request completes:
Triggers an internal pub/sub event. Subscribers in other modules react in their `subscribe()` pipelines, with no direct dependency on the emitter. See [Event Pipelines](#event-pipelines).
**Event name *(by order)***: name of the event to publish.
Runs a named task inline as a step in the calling pipeline; control returns to the next step when it finishes. For reusable pipelines composed into workflows. The task must be defined with `task(name, { ... })`. See [Task Pipelines](#task-pipelines).
**Task name *(by order)***: name of a defined task.
Enqueues a named task as a durable background job; the calling pipeline continues immediately. Task reactors pick up queued jobs and execute their pipelines. The task is checkpointed after each step, so a crash mid-task resumes where it stopped. Requires `#include <dispatch.h>`, which provides the persistent task tables. The task must be defined with `task(name, { ... })`. See [Task Pipelines](#task-pipelines).
**Task name *(by order)***: name of a defined task.
Pushes a Server-Sent Event. With `.chan`, the event broadcasts to all clients on that channel. Without it, the event returns to the requesting client. See [Resource Pipelines](#resource-pipelines).
Renders a template into the pipeline context. `mustache()` renders Mustache; `mdm()` renders Markdown-with-Mustache; `json()` renders JSON. All take the same `render_c`.
`redirect()` returns a 302 to the client, causing the browser to navigate. `reroute()` re-enters the router server-side, executing another resource's pipeline within the same request. Both take only the target resource name. `:params` in the target's URL pattern are read from the current context by matching key names.
**Resource name *(by order)***: target resource name. Required `:params` are read from context by name.
Functions called from `run()`/`run_worker()` blocks and `.call` functions to read and write context, allocate memory, raise errors, and manipulate tables and records.
* [context](#context-1)
* [memory](#memory)
* [errors](#errors)
* [tables](#tables)
* [records](#records)
#### context
Read, write, and test context keys, and resolve `{{interpolation}}` against the current scope.
**`get(name)`**: returns the value stored under `name`, or `nullptr` if absent. The returned pointer is whatever was stored: a `string` for scalars, a `table` for query and fetch results.
auto raw = third_party_render_md(get("markdown"));
defer_free(raw);
set("html", raw);
})
```
#### errors
Raise field-scoped errors from `run()` to trigger error/repair pipelines. Keys land in the `error:name` scope, visible to templates as `{{error:name}}`, `{{error_code:name}}`, and `{{error_message:name}}`.
Records are name-value bags, the shape of one row from `query()` or one object from `fetch()`. All values are strings; see [Everything is a String](#everything-is-a-string).
Every step accepts `.if_ctx` and `.not_ctx`, naming a context variable. They work for any context value: validated inputs, query results, framework flags like `is_htmx`, or flags set from `run()`.
`.map` and `.map_key` run a step once per row of a context table, all rows **concurrently**, like multiple items in `query()` or `fetch()`. With a `.ctx_key`, results are collected into a table aligned with the input, one entry per row. They differ in how each row reaches the step body: `.map` puts the row's fields in scope as bare `{{interpolations}}`; `.map_key` binds the row as a single-row table under a named key.
A module is declared with `config(name)` in a `name.c` file, usually inside a matching `name/` folder that holds its assets. A module owns its own resources, databases, migrations, tasks, event contracts, and middleware. Nerak scans the project for `config(...)` declarations and loads every module it finds.
A module is seeded with the assets in its folder and every asset up to the project root, at startup. See [Assets](#assets) and [Context](#context).
**`middleware(steps)`**: registers shared steps that run on every request to a resource in the same module. Cross-cutting setup like session loading or tenant resolution lives here.
**`error(...)` / `repair(...)`**: module-scoped error and repair handlers (see [Error and Repair Pipelines](#error-and-repair-pipelines)). They cover resources in the same module; a resource's own `.errors`/`.repairs` override them for the same code.
**Pipeline composition.** A request runs the resource's `.all` steps first, then the module's `middleware()`, then the verb pipeline.
For `GET /todos/5` the executed order is: `input({"id", ...})` (resource `.all`), `logged_in()`, `session()` (module `middleware`), then the verb pipeline `sqlite_query({"get_todo", ..., .err_on_empty = true})`, `mustache("todo", "todo_s")`, `respond("todo_s")`.
Activate with `#include <htmx.h>`. Serves the htmx runtime as the `{{> htmx }}` partial, and sets the `is_htmx` context flag on requests carrying the `HX-Request` header. Pair the flag with `.if_ctx`/`.not_ctx` to return a fragment to htmx and a full page to a direct visit, or use `hx-boost` to upgrade ordinary links and forms into AJAX swaps.
Activate with `#include <datastar.h>`. Serves the Datastar runtime as the `{{> datastar }}` partial and provides `datastar()` for pushing reactive fragment and signal patches over an SSE channel. A page opens an SSE connection (a resource `.sse` channel); pipelines push patches to that channel, and Datastar applies them in the DOM.
Worked example: a create, an update, and a delete, each pushing a patch to every client on the channel. Queries use `RETURNING` so the changed row comes back for rendering. This mirrors the shipped `app.c`.
Activate with `#include <tailwind.h>`. Compiles Tailwind utility classes used across the project's templates and serves the stylesheet as the `{{> tailwind }}` partial. Use Tailwind classes directly in templates; no build step or config file required.
<h1 class='text-3xl font-bold text-center mb-8'>Vote for which is roundest</h1>
</body>
```
#### daisyui
Activate with `#include <daisyui.h>`. Compiles DaisyUI classes used across the project's templates and serves the stylesheet as the `{{> daisyui }}` partial. Use DaisyUI classes directly in templates; no build step or config file required.
Activate with `#include <session_auth.h>`. Cookie-based authentication as pipeline steps. `session()` loads the current `user` record into context from the session cookie; run it as `middleware()` in each module whose pipelines need to know who is signed in. `logged_in()` guards a resource, redirecting anonymous visitors to the login page. `login()`, `logout()`, and `signup()` perform the corresponding actions. The login page template is the asset named `login`.
**`session()`**: loads the current user into context from the session cookie. Use as middleware.
Each engine is its own module: `#include` its header, then use `<engine>_config(...)` to register and `<engine>_query({...})` as a pipeline step. They share `db_c` and `query_c` from [Databases](#databases) and [query](#query); only `.conn` is engine-specific.
Files in `public/` are served directly. Reference them in templates with `{{asset:filename}}`, which resolves to a content-checksummed, cache-busted URL with immutable cache headers. Updates invalidate caches automatically; unchanged files cache forever.
This differs from assets like SQL and HTML templates, which are embedded from files anywhere in the project and seeded into context for steps to read by key (see [Assets](#assets) and [Context](#context)). `public/` holds opaque files served to the browser.
### External Dependencies
Drop third-party C libraries into `/vendor`; Nerak compiles and links them with the app. Call into them from `run()`/`run_worker()` steps. Memory returned by a library that must be freed manually is registered with `defer_free()` so it is reclaimed when the request completes (see [memory](#memory)).
auto html = cmark_markdown_to_html(md, strlen(md), 0);
defer_free(html); // library-owned pointer
set("html_content", html);
});
}
```
For dependencies that aren't plain source (system packages, build tooling), provide a custom `Dockerfile`. Nerak builds from it instead of the default image.
Each module's `config(name)` runs once at boot. Registration calls (`resource()`, `sqlite_config()`, `task()`, `middleware()`, `publish()`, etc.) are processed into an execution graph with precompiled pipelines, queries, and templates. Each incoming request executes its matching pipeline as a sequence of pre-warmed steps.
A `run_worker()` step dispatches work to the shared pool, releasing the reactor; the pipeline resumes on the original reactor when the call completes. `run()` runs inline on the reactor for short, non-blocking logic. `run_task()` runs a named task inline as part of the pipeline. `dispatch()` adds a durable job to the task database, picked up by task reactors. Any pipeline or task can call all four.
Each reactor maintains a pool of arena allocators. When a request arrives, the pipeline is assigned an arena, and all allocations draw from it. When the pipeline completes, the arena is cleared and returned to the pool. Application code does not call `malloc` or `free` (use `alloc()` and `defer_free()` from the [Imperative API](#memory) for raw buffers), avoiding leaks, double-frees, and use-after-free.
All framework data structures (tables, records, strings) enforce bounds checking. Out-of-bounds reads and missing context values return `nullptr` rather than faulting. Pipelines exceeding their memory limit (default 5MB, configurable in `compose.yml`) abort with a 500, mitigating OOM denial-of-service.
#### SQL Injection Prevention
Interpolations like `{{user_id}}` inside a query's SQL (whether the SQL comes from a `.sql` file or a `context()`-registered string) are bound as parameters in prepared statements, preventing SQL injection at the framework level.
#### XSS Prevention
The `mustache()` and `mdm()` steps auto-escape context values, so malicious input is rendered as text. Raw HTML requires explicit opt-in via Mustache's standard unescape syntax: `{{{field}}}` or `{{&field}}`.
#### CSRF Prevention
State-changing requests are verified against a per-session CSRF token. Emit the token with `{{csrf:input}}` (hidden form field) or `{{csrf:param}}` (value for query strings); Nerak sets it on an httponly, secure, samesite cookie and rejects requests whose token does not match. See [Templates](#templates).
Pipeline-aware commands. Halt on individual pipeline steps, step through execution, and inspect the full pipeline context including nested tables and records.
Nerak deploys as a standard Docker container. It does not terminate TLS; production deployments place Nerak behind a reverse proxy or load balancer (Nginx, Caddy, AWS ALB) to handle HTTPS.
app_build # outputs a minimal production Docker image
```
`app_build` runs each module's asset scan once (see [Assets](#assets)) and compiles the results into that module's binary. The production image excludes the file watcher and `/app_info`.
### Observability
Each pipeline step emits OpenTelemetry spans. Logs, traces, errors, and auto-profiling are visualized on the telemetry server at port 4000. No manual instrumentation required.
### Project Management
Ships with integrated infrastructure: source control, issue tracking, wiki, forum, and a project website.
### Built With
| | |
|---|---|
| [C](https://en.cppreference.com/w/c/23) | Language standard |
| [Docker](https://www.docker.com/) | Development environment, production images, stack orchestration |