API Reference

Syntax, APIs, and behavior details for ZX templates and Ziex's routing and tooling.

Expressions

Use curly braces {expression} to embed any Zig expression. Values are automatically formatted based on their type and HTML-escaped for safety.

pub fn Expressions(allocator: zx.Allocator) zx.Component {
    const name = "Alice";
    const count: u32 = 42;
    const price: f32 = 19.99;
    const active = true;
    return (
        <main @allocator={allocator}>
            <p>{name}</p>
            <p>{count}</p>
            <p>${price}</p>
            <p>{active}</p>
        </main>
    );
}
<main><p>Alice</p><p>42</p><p>$19.99</p><p>true</p></main>

Strings

String values ([]const u8) are displayed as text and automatically HTML-escaped to prevent XSS attacks. This is the safe default for displaying user input or any dynamic text content.

const name = "Alice";
// ...
(<p>{name}</p>); // <p>Alice</p>

Integers

Integer types (i32, u64, comptime_int, etc.) are formatted as decimal numbers. The special case u8 is printed as a character if it's a printable ASCII character.

const count: u32 = 42;
// ...
(<p>{count}</p>); // <p>42</p>

Floats

Floating-point types (f32, f64, comptime_float) are formatted as decimal numbers.

const price: f32 = 19.99;
// ...
(<p>${price}</p>); // <p>$19.99</p>

Booleans

Boolean values are displayed as the literal strings "true" or "false".

const active = true;
// ...
(<p>{active}</p>); // <p>true</p>

Enums

Enum values are displayed as their tag name. This is useful for displaying status values, categories, or any enumerated type.

const Status = enum { pending, approved, rejected };
const status = Status.approved;
// ...
(<p>{status}</p>); // <p>approved</p>

Optionals

Optional values (?T) are automatically unwrapped and rendered if present. If the value is null, nothing is rendered. This makes it easy to conditionally display content.

const maybe_name: ?[]const u8 = "Bob";
// ...
(<p>{maybe_name}</p>); // <p>Bob</p>

const no_name: ?[]const u8 = null;
// ...
(<p>{no_name}</p>); // <p></p> (empty)

Null

The null value renders nothing, producing no output in the final HTML.

Components

A zx.Component value is rendered directly. This allows you to embed components returned from functions or stored in variables.

const header = zx.Component{ .text = "Header" };
// ...
(<div>{header}</div>); // Renders the Header component

Component Arrays

Arrays or slices of components ([]zx.Component) are rendered as a fragment containing all the components in sequence.

const items: []const zx.Component = &.{ zx.Component{ .text = "A" }, zx.Component{ .text = "B" } };
// ...
(<ul>{items}</ul>); // Renders both Item components

Control Flow

ZX supports conditional rendering and iteration using familiar Zig control flow constructs. These expressions allow you to conditionally render components or iterate over collections to build dynamic UIs.

If Statements

Use if expressions to conditionally render components based on boolean conditions. The else branch is optional and can render alternative content when the condition is false.

const ControlIfProps = struct { is_admin: bool };
pub fn ControlIf(
    allocator: zx.Allocator,
    props: ControlIfProps,
) zx.Component {
    return (
        <div @{allocator}>
            {if (props.is_admin) (
                <span>Admin</span>
            ) else (
                <span>Member</span>
            )}
        </div>
    );
}
<div><span>Admin</span></div>

Switch Statements

Use switch expressions to match against enum values or other types. Each case can return either a string literal or a component. Switch expressions are particularly useful for rendering different UI based on state or user roles.

const Role = enum { admin, member, guest };
const ControlSwitchProps = struct { role: Role };
pub fn ControlSwitch(allocator: zx.Allocator, props: ControlSwitchProps) zx.Component {
    return (
        <div @{allocator}>
            {switch (props.role) {
                .admin => (<span>Admin</span>),
                .member => (<span>Member</span>),
                else => (<span>Guest</span>),
            }}
        </div>
    );
}
<div><span>Member</span></div>

For Loops

Use for loops to iterate over arrays, slices, or strings and render a component for each item. The loop variable can be used within the component body to display item-specific content. This is ideal for rendering lists, tables, or any repeating UI patterns.

const ControlForProps = struct { items: []const []const u8 };
pub fn ControlFor(allocator: zx.Allocator, props: ControlForProps) zx.Component {
    return (
        <ul @{allocator}>
            {for (props.items) |item| (<li>{item}</li>)}
        </ul>
    );
}
<ul><li>Alice</li><li>Bob</li><li>Charlie</li></ul>

While Loops

Use while loops for conditional iteration with a continuation expression. The syntax follows Zig's while loop pattern: while (condition) : (continue_expr) (body). This is useful for generating numbered sequences or iterating until a condition is met.

pub fn ControlWhile(allocator: zx.Allocator) zx.Component {
    var i: usize = 0;
    return (
        <ul @{allocator}>
            {while (i < 3) : (i += 1) (<li>Item {i + 1}</li>)}
        </ul>
    );
}
<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>

Optional Capture

Use payload capture syntax to unwrap optional values in if and while expressions:

const user_name: ?[]const u8 = "Alice";
// ...
if (user_name) |name| (<p>Welcome, {name}!</p>);

// With else branch:
if (user_name) |name| (<p>Hello, {name}</p>) else (<p>Guest</p>);

// While with capture (iterator pattern):
var maybe_item: ?[]const u8 = "item";
while (maybe_item) |item| : (maybe_item = null) (<li>{item}</li>);

If the optional is null, the body is skipped (or the else branch runs if provided).

Error Capture

Capture errors from error unions using else |err| syntax:

const parsed = std.fmt.parseInt(u32, "42", 10);

// If with error capture:
if (parsed) |value| (<p>Value: {value}</p>) else |err| (<p>Error: {@errorName(err)}</p>);

// While with error capture:
var first = true;
while (parseOnceRefInline(&first)) |value| (<li>{value}</li>) else |err| (<p>Iteration ended: {@errorName(err)}</p>);

This works with both if and while expressions for handling fallible operations.

Components

Components are reusable functions that return zx.Component. They allow you to encapsulate UI logic and create modular, maintainable code. Components can accept props (properties) to customize their behavior and appearance.

Component Function Signatures

A component takes an allocator (optionally followed by props), or a single context pointer. Any form can return !zx.Component to propagate errors:

pub fn Divider(allocator: zx.Allocator) zx.Component
pub fn Badge(allocator: zx.Allocator, props: BadgeProps) zx.Component
pub fn Panel(ctx: *zx.ComponentContext) zx.Component
pub fn Tooltip(ctx: *zx.ComponentCtx(TooltipProps)) zx.Component
pub fn Price(ctx: *zx.ComponentCtx(PriceProps)) !zx.Component

ComponentContext

Use zx.ComponentContext when your component needs access to children but has no custom props:

pub fn Container(ctx: *zx.ComponentContext) zx.Component {
    return (
        <div @allocator={ctx.allocator}>
            {ctx.children}
        </div>
    );
}

ComponentCtx with Props

Use zx.ComponentCtx(Props) when you need both custom props and children access:

pub const CardProps = struct { title: []const u8 };
pub fn Card(ctx: *zx.ComponentCtx(CardProps)) zx.Component {
    return (
        <article @allocator={ctx.allocator}>
            <h2>{ctx.props.title}</h2>
            {ctx.children}
        </article>
    );
}

Fields of zx.ComponentCtx(Props):

FieldTypeDescription
propsPropsThe component's props; void for zx.ComponentContext.
allocatorstd.mem.AllocatorAllocator for this render. On the server it is the request arena, so it is freed after the response.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.
children?zx.ComponentContent passed between the component's tags, or null.

Defining Components

To create a component, define a function that returns a zx.Component. The simplest form takes an allocator as its only parameter. If your component needs configuration, add a props struct as the second parameter:

const ButtonProps = struct { label: []const u8 };
pub fn Button(
    ctx: *zx.ComponentCtx(ButtonProps),
) zx.Component {
    return (
        <button @allocator={ctx.allocator}>
            Click {ctx.props.label}
        </button>
    );
}
<div><button>Click Click Me</button></div>

Props Coercion

ZX automatically coerces the attributes you pass to a component into the expected props struct. Missing required fields will result in a compile-time error, while fields with default values are optional. This provides type safety while keeping component usage flexible.

Fragments

Fragments allow you to return multiple elements from a component without adding an extra wrapper element to the DOM. Use the empty tag syntax <>...</> to create a fragment:

pub fn Fragment(
    allocator: zx.Allocator,
) zx.Component {
    return (
        <fragment @{allocator}>
            <span>One</span>
            <>
                <p>Two</p><p>Three</p>
            </>
        </fragment>
    );
}
<span>One</span><p>Two</p><p>Three</p>

The fragment's children are rendered directly without any containing element.

Children Props

Components can accept child elements through a children prop, enabling wrapper and container patterns. Any elements between the opening and closing tags are passed as the children prop:

const CardChildrenProps = struct { title: []const u8, children: zx.Component };
pub fn CardDemo(allocator: zx.Allocator) zx.Component {
    return (
        <main @allocator={allocator}>
            <Card title="Welcome">
                <p>This content is passed as children.</p>
            </Card>
        </main>
    );
}

fn Card(allocator: zx.Allocator, props: CardChildrenProps) zx.Component {
    return (
        <div @allocator={allocator} class="card">
            <h2>{props.title}</h2>
            <div>{props.children}</div>
        </div>
    );
}
<main><div class="card"><h2>Welcome</h2><div><p>This content is passed as children.</p></div></div></main>

Attribute Syntax

ZX provides convenient syntax for working with attributes beyond simple static values.

Spread Attributes

Use {..struct} to spread all fields of a struct as attributes on an element. This is useful for passing groups of attributes or forwarding props:

const form_attrs = .{
    .class = "form-control",
    .@"data-validate" = "true",
};
const input_props = .{ .name = "email", .value = "[email protected]" };
// ...
(
    <form {..form_attrs}>
        <input type="text" {..input_props} />
    </form>
);

Spread attributes can be combined with explicit attributes. Explicit attributes take precedence when there are conflicts.

Shorthand Attributes

When the attribute name matches the variable name, use the shorthand syntax {variable}:

const class = "btn-primary";
const disabled = true;
const @"data-id" = "123";
(<button {class} {disabled} {@"data-id"}>Click</button>);
// Renders: <button class="btn-primary" disabled data-id="123">Click</button>

This is equivalent to writing class={class} but more concise.

Template Attributes

Use backticks (`) for string interpolation in attribute values. Embed expressions with {expr} inside the template:

const count = 42;
const name = "John";
// ...
(
    <div class=`item-{count}` data-user=`user-{name}`>
        <a href=`/users/{name}/profile`>Profile</a>
    </div>
);
// Renders:
//<div class="item-42" data-user="user-John">
//  <a href="/users/John/profile">Profile</a>
//</div>

Template attributes are useful for building dynamic URLs, class names, or data attributes that combine static text with dynamic values.

Builtin Attributes

ZX provides special builtin attributes that control component behavior and memory management. These attributes are prefixed with @ to distinguish them from regular HTML attributes.

@allocator

The @allocator attribute is required to be passed to the topmost component. All child components will inherit the allocator from the parent component. It is available to all child components and expressions within that component tree.

Why is @allocator needed?

ZX components can allocate memory for various purposes:

  • Storing text content (which is HTML-escaped and allocated)
  • Copying child component arrays
  • Copying attribute arrays
  • Formatting expressions that allocate formatted strings

Usage:

pub fn AllocatorDemo(ctx: zx.PageContext) zx.Component {
    const message = "Allocator is inherited by children";
    return (
        <main @allocator={ctx.arena}>
            <section>
                <h2>{message}</h2>
                <p>Use ctx.arena for request-scoped allocations.</p>
            </section>
        </main>
    );
}
<main><section><h2>Allocator is inherited by children</h2><p>Use ctx.arena for request-scoped allocations.</p></section></main>

Best Practices:

  • Always use ctx.arena in page components (it's automatically freed after the request)
  • Pass the allocator parameter to custom components and use it in the @allocator attribute
  • Set @allocator on the root element of each component that needs memory allocation
  • Child components inherit the allocator from their parent component, so you don't need to pass it explicitly to every nested component

@escaping

The @escaping attribute controls how text content is escaped within an element. By default, all text is HTML-escaped to prevent XSS attacks.

Values:

  • .html - Standard HTML escaping (default behavior)
  • .none - No escaping; outputs raw HTML. Use with caution for trusted content only.
pub fn RawHtml(allocator: zx.Allocator) zx.Component {
    const trusted = "<strong>Trusted HTML</strong>";
    return (
        <main @allocator={allocator}>
            <div>{trusted}</div>
            <div @escaping={.none}>{trusted}</div>
        </main>
    );
}
<main><div>&lt;strong&gt;Trusted HTML&lt;/strong&gt;</div><div><strong>Trusted HTML</strong></div></main>

Warning: Only use @escaping={.none} for content you trust completely. User-provided content should always use the default escaping.

@client

The @client attribute enables client-side rendering for interactive components, compiling the component to WebAssembly. It takes no value. Without it, all components render server-side only and event handlers are not active in the browser.

Client-side Zig rendering

Write <Counter @client /> to make a component interactive. The component is server-rendered for the initial HTML, then hydrated and re-rendered client-side on state changes. Only the marked component is managed client-side; the rest of the page stays server-rendered.

pub fn Page(ctx: zx.PageContext) !zx.Component {
    return (
        <main @allocator={ctx.arena}>
            <Counter @client />
        </main>
    );
}
pub fn Counter(ctx: *zx.ComponentCtx(void)) zx.Component {
    const count = ctx.state(i32, 0);
    return (
        <div @allocator={ctx.allocator} class="counter">
            <button onclick={ctx.bind(increment)}>
                Click Me: {count}
            </button>
        </div>
    );
}
fn increment(e: *zx.client.Event.Stateful) void {
    const count = e.state(i32);
    count.set(count.get() + 1);
}
<!--$c607f97--><div class="counter"><button>Click Me: 0</button></div><!--/$c607f97-->

Managing state

Client components that need reactive state must use zx.ComponentCtx(Props) (or zx.ComponentCtx(void) when there are no props). The context provides ctx.state(T, initial) to declare a piece of state:

  • ctx.state(T, initial_value) - declares a reactive value of type T. Returns a State(T) handle that persists across re-renders.
  • state.get() - read the current value. Can be used directly in markup as {count}.
  • state.set(new_value) - update the value and trigger a re-render.
  • state.update(fn(T) T) - update via a transform function.

State is stored per-component-instance and survives re-renders. On the server (SSR), ctx.state() always returns the initial value.

Event handlers

Ziex provides three ways to attach event handlers to client components:

1. Simple handler - for reading the event without touching state:

fn handleInput(event: zx.client.Event) void {
    const value = event.value() orelse "";
    zx.log.info("Input: {s}", .{value});
}
// Attach: oninput={handleInput}

The handler receives a zx.client.Event value. Useful methods:

  • event.value() - returns ?[]const u8 with event.target.value (for inputs and selects).
  • event.key() - returns ?[]const u8 with the pressed key name (for keyboard events).

2. Stateful handler via ctx.bind() - for reading or writing component state:

pub fn Counter(ctx: *zx.ComponentCtx(void)) zx.Component {
    const count = ctx.state(i32, 0);
    return (
        <div @allocator={ctx.allocator}>
            <button onclick={ctx.bind(increment)}>{count}</button>
        </div>
    );
}
fn increment(e: *zx.client.Event.Stateful) void {
    const count = e.state(i32); // same order as ctx.state()
    count.set(count.get() + 1);
}

The handler receives *zx.client.Event.Stateful. Call e.state(T) in the same order as ctx.state() in the component to access each piece of state.

3. State transform via state.bind() - the simplest option when the update is a pure function of the current value:

pub fn Counter(ctx: *zx.ComponentCtx(void)) zx.Component {
    const count = ctx.state(i32, 0);
    return (
        <div @allocator={ctx.allocator}>
            <button onclick={count.bind(increment)}>{count}</button>
        </div>
    );
}
fn increment(value: i32) i32 {
    return value + 1;
}

The transform function takes the current value and returns the new value. No event object is needed.

Form actions

Form submissions use the action attribute with an Action handler. Unlike event handlers, actions parse posted fields into a typed struct with data(T).

Client actions run in the browser via zx.client.Action:

pub fn ContactForm(ctx: *zx.ComponentCtx(void)) zx.Component {
    return (
        <form @allocator={ctx.allocator} action={ctx.bind(onSubmit)}>
            <input type="text" name="message" />
            <button type="submit">Send</button>
        </form>
    );
}

fn onSubmit(a: *zx.client.Action.Stateful) void {
    const data = a.data(struct { message: []const u8 });
    zx.log.info("message: {s}", .{data.message});
}

Handler signatures. Use the Stateful form with ctx.bind() to read component state via a.state(T):

fn onSend(a: zx.client.Action) void
fn onSendStateful(a: *zx.client.Action.Stateful) void

Server actions Experimental run on the server via zx.server.Action. They also expose request, response, and arena:

pub fn LoginForm(allocator: zx.Allocator) zx.Component {
    return (
        <form @allocator={allocator} action={onLogin}>
            <input type="text" name="username" />
            <button type="submit">Log in</button>
        </form>
    );
}

fn onLogin(a: zx.server.Action) void {
    const data = a.data(struct { username: []const u8 });
    zx.log.info("username: {s}", .{data.username});
}

Handler signatures. Use the Stateful form with ctx.bind() to update bound component state on the server:

fn onSave(a: zx.server.Action) void
fn onSaveStateful(a: *zx.server.Action.Stateful) void

Supported data(T) field types include []const u8, integers, floats, bools, optionals, []const []const u8 for multi-value fields, and on the server zx.http.File / ?zx.http.File for multipart uploads.

Server events Experimental

Bind a DOM event to a handler that runs on the server with ctx.bind(). The handler receives the element's value via e.value(); the Stateful form can also read and update bound component state:

fn onRefresh(e: *zx.server.Event) void
fn onRefreshStateful(e: *zx.server.Event.Stateful) void

Syntax Features

ZX supports additional Zig syntax features within templates.

Multiline Strings

Use Zig's multiline string syntax (\\) to embed formatted text blocks:

// Multiline strings use Zig's \\ syntax:
(
    <pre>
        {
        \\const x = 1;
        \\const y = 2;
        \\const sum = x + y;
    }
    </pre>
);

Each line prefixed with \\ is concatenated. This is useful for code snippets, preformatted text, or ASCII art.

Comments

Single-line comments are supported within ZX templates:

// Single-line comments are supported in ZX:
(
    <div>
        // This is a comment
        <p>Visible content</p>
        // Another comment
    </div>
);

Comments are stripped from the output and do not appear in the rendered HTML.

Importing

ZX supports importing components and modules from various sources. You can import ZX components from other files, and standard Zig modules. You can't import a .zx file into a standard .zig file. If you need to, rename the .zig file to .zx (for example, route.zx) so you can import from a .zx file.

pub fn ImportDemo(allocator: zx.Allocator) zx.Component {
    return (
        <main @allocator={allocator}>
            <ControlIf is_admin={true} />
            <ControlSwitch role={Role.member} />
        </main>
    );
}
<main><div><span>Admin</span></div><div><span>Member</span></div></main>

Routing

Ziex provides a file-based routing system that maps URL paths to page components. Routes can be nested, and layouts can be applied hierarchically to wrap pages with common UI elements.

Pages

Pages are the main content components for each route. A page function must:

  • Accept a zx.PageContext as its only parameter
  • Return a zx.Component or !zx.Component
  • Be exported as pub fn Page
pub fn Page(
    ctx: zx.PageContext,
) zx.Component {
    return (
        <div @allocator={ctx.arena}>
            <h1>Home</h1>
        </div>
    );
}
<div><h1>Home</h1></div>

Layouts

Layouts wrap pages with common UI elements like headers, footers, or navigation. A layout function must:

  • Accept a zx.LayoutContext as the first parameter
  • Accept a zx.Component (the page content) as the second parameter
  • Return a zx.Component
  • Be exported as pub fn Layout
pub fn Layout(
    ctx: zx.LayoutContext,
    children: zx.Component,
) zx.Component {
    return (
        <html @allocator={ctx.arena}>
            <body>
                {children}
            </body>
        </html>
    );
}
pub fn Page(
    ctx: zx.PageContext,
) zx.Component {
    return (
        <div @allocator={ctx.arena}>
            <h1>Home</h1>
        </div>
    );
}
<html><body>Hello, World!</body></html>

PageContext and LayoutContext

zx.PageContext and zx.LayoutContext have the same fields:

FieldTypeDescription
requestzx.http.RequestIncoming request: headers, cookies, query, route params, and body.
responsezx.http.ResponseOutgoing response: status, headers, cookies, and body.
allocatorstd.mem.AllocatorApp-lifetime allocator. Nothing is freed for you; prefer arena unless the memory must outlive the request.
arenastd.mem.AllocatorRequest-scoped allocator, freed after the response is sent. Use it for most allocations.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.
datazx.PageDataRequest-scoped key/value store (ctx.data.set / ctx.data.get). Pages run first, so they can set values such as the title for layouts to read.

Dynamic Routes

Ziex supports dynamic route segments using bracket notation in folder names.

Creating Dynamic Routes

Create a folder with brackets around the parameter name:

  • app/pages/user/[id]/page.zx โ†’ /user/:id
  • app/pages/blog/[slug]/page.zx โ†’ /blog/:slug
  • app/pages/[category]/[item]/page.zx โ†’ /:category/:item

Accessing Route and Query Parameters

Use ctx.request.params.get("name") to access dynamic route parameters and ctx.request.query("name") for query strings:

pub fn Page(ctx: zx.PageContext) zx.Component {
    const id = ctx.request.params.get("id");
    return (
        <section @allocator={ctx.arena}>
            <h1>User {id}</h1>
        </section>
    );
}
<section><h1>User </h1></section>

Both methods return ?[]const u8, so use orelse to provide a default value.

File Conventions

Routing is driven by file names inside app/pages/ (and app/routes/). Each directory is a URL segment; these files give it behavior:

FileExportsApplies to
page.zxPage, optionsThis path
layout.zxLayout, optionsThis path and everything below it
notfound.zxNotFound, optionsUnmatched paths at or below this directory
error.zxErrorErrors from pages and routes below this directory
route.zigGET, POST, ..., Route, Socket*, optionsThis path
proxy.zigProxy, PageProxy, RouteProxyProxy: this path and below; the others: this path only

Every file in a directory is optional. Files that contain ZX markup use .zx; a plain-Zig file can use .zig instead (for example page.zig).

page.zx

Renders the page for the directory's path. Return !zx.Component to propagate errors to error.zx.

pub fn Page(ctx: zx.PageContext) zx.Component
pub const options = zx.PageOptions{ .methods = &.{ .GET, .POST } };
FieldTypeDefaultDescription
rendering?zx.PageOptions.RenderingnullHow the route renders: .prerendered, .request, .streamed, or individual fields. Pages inherit it from the nearest layout when null.
caching?zx.BuiltinAttribute.CachingnullCache the rendered output, for example .{ .ttl = .fromSeconds(300) }. See Caching.
methods[]const zx.PageOptions.Method&.{ .GET }HTTP methods the page answers. Add .POST for pages that handle form actions.
static?zx.StaticFnnullFunction that lists the params of a dynamic route to pre-render with --static or --prerender.

layout.zx

Wraps every page at or below its directory. Layouts nest: the root layout wraps the nested one, which wraps the page.

pub fn Layout(ctx: zx.LayoutContext, children: zx.Component) zx.Component
FieldTypeDefaultDescription
rendering?zx.PageOptions.RenderingnullDefault rendering for every page below this layout. A page's own setting wins.
caching?zx.BuiltinAttribute.CachingnullCache the rendered output, for example .{ .ttl = .fromSeconds(300) }. See Caching.

notfound.zx

Rendered with status 404 when no route matches. Ziex uses the closest notfound.zx above the requested path and wraps it in that path's layouts. Without one, the response is a plain-text 404 Not Found.

pub fn NotFound(ctx: zx.NotFoundContext) zx.Component
FieldTypeDefaultDescription
caching?zx.BuiltinAttribute.CachingnullCache the rendered output, for example .{ .ttl = .fromSeconds(300) }. See Caching.

error.zx

Rendered with status 500 when a page or route handler returns an error. ctx.err holds the error; the other fields match PageContext.

pub fn Error(ctx: zx.ErrorContext) zx.Component
FieldTypeDescription
requestzx.http.RequestIncoming request: headers, cookies, query, route params, and body.
responsezx.http.ResponseOutgoing response: status, headers, cookies, and body.
allocatorstd.mem.AllocatorApp-lifetime allocator. Nothing is freed for you; prefer arena unless the memory must outlive the request.
arenastd.mem.AllocatorRequest-scoped allocator, freed after the response is sent. Use it for most allocations.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.
erranyerrorThe error returned by the page or route handler.
datazx.PageDataRequest-scoped key/value store (ctx.data.set / ctx.data.get). Pages run first, so they can set values such as the title for layouts to read.

route.zig

Handles raw HTTP requests. Export a function per method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, or any other all-uppercase name for a custom method), or Route as a catch-all. A route.zig next to a page.zx can't define a method the page handles (see PageOptions.methods). Handlers can return void or !void.

pub fn GET(ctx: zx.RouteContext) !void
pub fn POST(ctx: zx.RouteContext) !void
pub fn Route(ctx: zx.RouteContext) !void

WebSocket handlers live in the same file. See WebSockets.

pub fn Socket(ctx: zx.SocketContext) !void
pub fn SocketOpen(ctx: zx.SocketOpenContext) void
pub fn SocketClose(ctx: zx.SocketCloseContext) void
FieldTypeDefaultDescription
rendering?zx.PageOptions.RenderingnullOnly prerender and dynamic apply. Not inherited from layouts.
caching?zx.BuiltinAttribute.CachingnullCache the rendered output, for example .{ .ttl = .fromSeconds(300) }. See Caching.
static?zx.StaticFnnullFunction that lists the params of a dynamic route to pre-render with --static or --prerender.

proxy.zig

Runs before handlers, like middleware. Proxy runs for this path and every path below it; PageProxy runs only before this directory's page and RouteProxy only before its route.zig. Call ctx.abort() to stop the chain and send the response as it is; otherwise the request continues.

pub fn Proxy(ctx: *zx.ProxyContext) !void
pub fn PageProxy(ctx: *zx.ProxyContext) !void
pub fn RouteProxy(ctx: *zx.ProxyContext) !void
FieldTypeDescription
requestzx.http.RequestIncoming request: headers, cookies, query, route params, and body.
responsezx.http.ResponseOutgoing response: status, headers, cookies, and body.
allocatorstd.mem.AllocatorApp-lifetime allocator. Nothing is freed for you; prefer arena unless the memory must outlive the request.
arenastd.mem.AllocatorRequest-scoped allocator, freed after the response is sent. Use it for most allocations.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.

API and WebSockets

Ziex allows you to create server-side APIs and WebSocket handlers by adding a route.zig file to any route directory. This is similar to page.zx but for handling raw HTTP requests and real-time communication.

API Routes

To create an API route, define a route.zig file and export functions for the HTTP methods you want to handle (GET, POST, PUT, DELETE, etc.).

routes/api/route.zig
pub fn GET(ctx: zx.RouteContext) !void {
    try ctx.response.json(.{ .status = "ok" }, .{});
}

pub fn POST(ctx: zx.RouteContext) !void {
    const Data = struct { id: u32 };
    const data =
        try ctx.request.json(Data, .{});

    try ctx.response.json(.{
        .id = if (data) |d| d.id else 0,
        .created = true,
    }, .{});
}

RouteContext

All API handlers receive a zx.RouteContext, which provides everything needed to handle the request:

pub fn GET(ctx: zx.RouteContext) !void {
    _ = ctx.request; // Request details
    _ = ctx.response; // Set headers, body, json, etc.
    _ = ctx.socket; // WebSocket upgrade and pub/sub
    _ = ctx.arena; // Request-scoped allocator
}
FieldTypeDescription
requestzx.http.RequestIncoming request: headers, cookies, query, route params, and body.
responsezx.http.ResponseOutgoing response: status, headers, cookies, and body.
socketzx.SocketWebSocket handle: upgrade, send, subscribe, unsubscribe, publish.
allocatorstd.mem.AllocatorApp-lifetime allocator. Nothing is freed for you; prefer arena unless the memory must outlive the request.
arenastd.mem.AllocatorRequest-scoped allocator, freed after the response is sent. Use it for most allocations.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.

WebSockets

Ziex has first-class support for WebSockets. You can upgrade an API request to a WebSocket connection and handle real-time messages with simple lifecycle hooks.

routes/ws/route.zig
pub fn GET(ctx: zx.RouteContext) !void {
    try ctx.socket.upgrade({});
}

pub fn Socket(ctx: zx.SocketContext) !void {
    try ctx.socket.send(ctx.message);
}

pub fn SocketOpen(ctx: zx.SocketOpenContext) !void {
    try ctx.socket.send(.{ .text = "Opened!" });
}

Lifecycle Handlers

  • Socket: Called when a message is received. This is the main handler for WebSocket logic.
  • SocketOpen: Called when the connection is established.
  • SocketClose: Called when the connection is closed.
  • SocketError: Called when an error occurs on the connection.

SocketContext

Message handlers receive a zx.SocketContext (or others like SocketOpenContext):

pub fn Socket(ctx: zx.SocketContext) !void {
    _ = ctx.socket; // WebSocket interface
    _ = ctx.message; // Received message (.text or .binary)
    _ = ctx.data; // Custom data from upgrade
    _ = ctx.arena; // Message-scoped allocator
}
FieldTypeDescription
socketzx.SocketWebSocket handle: upgrade, send, subscribe, unsubscribe, publish.
messagezx.WebSocket.MessageThe received message: .text or .binary.
datavoidThe value passed to ctx.socket.upgrade(data). Use zx.SocketCtx(T) to type it.
allocatorstd.mem.AllocatorApp-lifetime allocator. Nothing is freed for you; prefer arena unless the memory must outlive the request.
arenastd.mem.AllocatorAllocator freed after this message is handled.
iostd.IoThe app's std.Io, for files, networking, sleeping, and timers.

Pub/Sub and Broadcasting

The ctx.socket interface provides a powerful pub/sub system for broadcasting messages to multiple clients:

  • subscribe(topic): Join a topic.
  • unsubscribe(topic): Leave a topic.
  • publish(topic, message): Send a message to all subscribers of a topic.

Caching Experimental

Ziex provides built-in caching for components, pages, and layouts to improve performance. Cached content is persisted on disk and served directly without re-rendering.

Enabling

Caching is disabled by default. Enable it in build.zig by passing features to your ziex.init call:

build.zig
try ziex.init(b, app_exe, .{
    .app = .{
        .features = .{
            .cache = .enabled,
        },
    },
});

Overview

Caching can be applied at three levels:

  • Component caching - Cache individual components using the @caching attribute
  • Page caching - Cache entire pages using PageOptions.caching
  • Layout caching - Cache layouts using LayoutOptions.caching

Component Caching

Use the @caching attribute on any component to cache its rendered HTML output. The syntax is <duration> or <duration>:key.

Time Units

UnitDescriptionExample
sSeconds"10s" = 10 seconds
mMinutes"5m" = 300 seconds
hHours"2h" = 7200 seconds
dDays"1d" = 86400 seconds

Basic Usage

// Cache for 10 seconds
(<header @caching="10s" />);

// Cache for 5 minutes
(<aside @caching="5m" />);

// Cache for 1 hour
(<footer @caching="1h" />);

// Cache for 1 day
(<section @caching="1d" />);

Custom Cache Keys

Add a custom key after the duration with a colon (:) separator. Keys are useful for manual cache invalidation:

// Cache with a custom key for manual invalidation
(<section @caching="10m:user-profile" />);

// Cache navigation with key
(<nav @caching="1h:main-nav" />);

The cache key is prefixed with cmp: internally, so "10m:user-profile" creates a key cmp:user-profile.

Page Caching

Enable page-level caching by exporting a options constant with caching settings:

page.zx
pub fn Page(ctx: zx.PageContext) zx.Component {
    return (
        <div @allocator={ctx.arena}>
            <h1>Cached Page</h1>
            <p>This page is cached for 5 minutes.</p>
        </div>
    );
}

// Enable page-level caching
pub const options = zx.PageOptions{
    .caching = .{ .ttl = .fromSeconds(300) }, // 5 minutes
};

Page caching stores the entire rendered response including headers. The server adds ETag and Cache-Control headers automatically.

Layout Caching

Layouts can also be cached using LayoutOptions:

layout.zx
pub fn Layout(ctx: zx.LayoutContext, children: zx.Component) zx.Component {
    return (
        <html @allocator={ctx.arena}>
            <body>
                {children}
            </body>
        </html>
    );
}

// Cache the entire layout for 1 hour
pub const options = zx.LayoutOptions{
    .caching = .{ .ttl = .fromSeconds(3600) },
};
Note: Layout caching caches the entire layout including children. Use with caution as it may cache dynamic page content unintentionally.

Cache Invalidation

Manually invalidate cache entries using zx.cache functions:

// Delete a specific cache entry by key
zx.cache.delete("cmp:user-profile") catch false;

// Delete all entries matching a prefix
// Useful for invalidating related content
zx.cache.deletePrefix("cmp:user") catch 0;

Available functions:

  • zx.cache.delete(key) - Delete a specific cache entry by exact key. Returns !bool, true if the entry existed.
  • zx.cache.deletePrefix(prefix) - Delete all entries matching a prefix. Returns !usize, the count of deleted entries.
  • zx.cache.get(allocator, key) - Get cached HTML by key. Returns !?[]u8, owned by allocator.

Best Practices

  • Cache static content aggressively - Headers, footers, navigation, and other rarely-changing content benefit most from caching.
  • Use custom keys for related content - Group related cache entries with a common prefix for easy bulk invalidation.
  • Be careful with user-specific content - Don't cache components that display user-specific data without including user identity in the cache key.
  • Start with short TTLs - Begin with shorter cache durations and increase as you verify correctness.
  • Invalidate on data changes - Call zx.cache.delete() or zx.cache.deletePrefix() when underlying data changes.
Performance tip: Component caching is most effective for expensive-to-render components with stable output.

Command Line Interface

Ziex comes with a built-in CLI tool to help you create, develop, and deploy your projects.

Installation

Install the Ziex CLI using one of the following methods:

curl -fsSL https://ziex.dev/install | bash
powershell -c "irm ziex.dev/install.ps1 | iex"

version

Show CLI version

$ zx version

init

Initialize a new Ziex project in the current directory

$ zx init [path] [flags]

Arguments

  • [path] - Path to initialize the project in (default: current directory)

Flags

  • --template, -t <template> - Template to use: a builtin (starter, docker) or any github:ziex-dev/template-<name> (cloudflare, vercel, node, railway, render) (default: "starter")
  • --force, -f - Force initialization even if the directory is not empty (default: false)
  • --existing - Initialize Ziex in an existing project (default: false)

app

App build helpers

$ zx app

dev

Start the app in development mode with rebuild on change

$ zx dev [flags]

Flags

  • --bin-path, -b <bin-path> - Path to the app executable (default: from <install-prefix>/manifest/app.zon) (default: "")
  • --build-args, -a <build-args> - Additional arguments appended to zig build (default: "")
  • --zig-path <zig-path> - Path to the zig executable (falls back to ZIEX_ZIG_PATH, then PATH) (default: "zig")
  • --install-prefix, -i <install-prefix> - Install prefix for the app (default: zig-out) (default: "zig-out")
  • --port, -p <port> - Port to listen on (default: PORT env, or 3000). Uses the next free port if busy (default: 0)
  • --incremental - Enable incremental build (-fincremental of zig build) (default: false)
  • --tui-progress - Show full build progress output from zig build (default: true)
  • --tui-init-time-report - Show initial build duration before the server address (default: false)
  • --tui-underline - Show underlined status messages (default: true)
  • --tui-spinner - Show spinner for status messages (default: false)
  • --tui-clear - Clear the terminal before every restart (default: false)
  • --manifest <manifest> - App manifest path (contains transpile_dir for `.zx` remap; default: <install-prefix>/manifest/app.zon) (default: "")

serve

Run the server

$ zx serve [flags]

Flags

  • --port, -p <port> - Port to listen on (sets PORT; default: PORT env, or 3000) (default: 0)
  • --bin-path, -b <bin-path> - Path to the app executable (default: from <install-prefix>/manifest/app.zon) (default: "")
  • --zig-path <zig-path> - Path to the zig executable (falls back to ZIEX_ZIG_PATH, then PATH) (default: "zig")
  • --install-prefix, -i <install-prefix> - Install prefix for the app (default: zig-out) (default: "zig-out")
  • --release <release> - Release mode passed to zig build as --release=<mode> (fast, safe, small; empty for debug) (default: "fast")
  • --build-args, -a <build-args> - Additional arguments appended to zig build (default: "")

build

Build the app (equivalent to `zig build`)

$ zx build [flags]

Flags

  • --build-args, -a <build-args> - Additional arguments appended to zig build (default: "")
  • --zig-path <zig-path> - Path to the zig executable (falls back to ZIEX_ZIG_PATH, then PATH) (default: "zig")
  • --bin-path, -b <bin-path> - Path to the app executable (default: from <install-prefix>/manifest/app.zon) (default: "")
  • --install-prefix, -i <install-prefix> - Install prefix for the app (default: zig-out) (default: "zig-out")
  • --target <target> - Zig target triple to build for (e.g. wasm32-wasi, x86_64-linux-musl) (default: "")
  • --release <release> - Release mode passed to zig build as --release=<mode> (fast, safe, small). Default: debug, or small with --static (default: "")
  • --prerender - Also pre-render routes with `.rendering = .prerendered` into <install-prefix>/static next to the app (default: false)
  • --static - Pre-render every route to static HTML in --outdir instead of building a server (can't be combined with --target) (default: false)
  • --outdir, -o <outdir> - Output directory for --static builds (default: dist) (default: "")
  • --prerendered-only - With --static, only pre-render routes with `rendering.prerender` (used by --prerender) (default: false)

transpile

Transpile a .zx file or directory to zig source code.

$ zx transpile <path> [flags]

Arguments

  • <path> - Path to .zx file or directory

Flags

  • --outdir, -o <outdir> - Output directory (default: ".zx")
  • --copy-only - Copy only the files to the output directory (default: false)
  • --verbose, -v - Show verbose output (default: false)
  • --map <map> - Generate source map (default: "none")
  • --dep-file <dep-file> - Write a Make-format dependency file listing all transpiled input files (default: "")
  • --cache-dir <cache-dir> - Persistent transpile cache directory (mtime + Transpile.shape; survives zig-cache invalidation) (default: "")
  • --roots <roots> - File listing route files (one per line, relative to the path) to transpile from; default: scan pages/ and routes/ (default: "")
  • --base-path <base-path> - Base path for the application (e.g., /test) (default: "")
  • --manifest <manifest> - Centralized app manifest path (zig-out/manifest/app.zon) (default: "")
  • --build-injections <build-injections> - Build-managed injections to merge into the app manifest (default: "")
  • --exe-path <exe-path> - Path to the executable (default: "")
  • --client-dir <client-dir> - Directory of module client component lists (default: "")

fmt

Format .zx files or directories.

$ zx fmt [paths] [flags]

Arguments

  • [paths] - Paths to .zx files or directories (default: <empty>)

Flags

  • --stdin - Read from stdin and write formatted output to stdout (default: false)
  • --stdout - Write formatted output to stdout instead of disk (default: false)

diagnose

Pretty-print zig build errors read from stdin

$ zx diagnose

env

Print Ziex environment information

$ zx env [flags]

Flags

  • --format <format> - Output format: zon (default) or json (default: zon)

lsp

Start the Ziex language server

$ zx lsp [flags]

Flags

  • --message, -m <message> - JSON-RPC LSP message to process (repeatable; disables stdio mode) (default: <empty>)
  • --zx-module <zx-module> - Path to the zx module root (src/root.zig); overrides ZIEX_MODULE_PATH (default: "")

bundle

Bundle the built app and its static assets for native deployment

$ zx bundle [flags]

Flags

  • --outdir, -o <outdir> - Output directory (default: "bundle")
  • --bin-path, -b <bin-path> - Path to the app executable (default: from <install-prefix>/manifest/app.zon) (default: "")
  • --install-prefix, -i <install-prefix> - Install prefix for the app (default: zig-out) (default: "zig-out")

update

Update the version of the Ziex dependency

$ zx update [flags]

Flags

  • --version <version> - Version to update to (default: "latest")
  • --canary - Update to the latest commit on the main branch instead of the latest release (default: false)
  • --zig-path <zig-path> - Path to the zig executable (falls back to ZIEX_ZIG_PATH, then PATH) (default: "zig")

upgrade

Upgrade the version of the Ziex CLI

$ zx upgrade [flags]

Flags

  • --version <version> - Version to upgrade to (default: "latest")