Skip to content

Views (.kick templates) ​

@forinda/kickjs-view renders server-side HTML from .kick templates. ctx.render() works with it on Express, Fastify, h3 and the web fetch entry, including edge platforms with no file system. Values print with and pipes; logic lives in @if / @for blocks.

Experimental

The first releases are 0.x. The template syntax is settled; the format the build emits may still change between minor versions.

kick
{{-- src/views/users/show.kick --}}
@layout('layouts/main')
<h1>{{ user.name | titlecase }}</h1>
@if (user.isAdmin) {
  <admin-badge />
}
<ul>
  @for (post of posts; let i = $index) {
    <li>{{ i + 1 }}. <a href="/posts/{{ post.id }}">{{ post.title }}</a></li>
  } @empty {
    <li>No posts yet</li>
  }
</ul>
ts
@Get('/:id')
async show(ctx: RequestContext) {
  const user = await this.users.find(ctx.params.id)
  await ctx.render('users/show', { user, posts: user.posts })
}

Other template engines (EJS, Pug, Handlebars) keep working through ViewAdapter, and one app can use both.

Setup ​

kick add views does this for you: it installs the package, writes src/views.ts, a layout and a home page, puts the adapter in src/adapters/views.ts (viewsAdapter()) and adds it to bootstrap() in src/index.ts, and prints the line that registers viewCliPlugin in kick.config.ts (for kick check:views and kick fmt:views). By hand:

bash
pnpm add @forinda/kickjs-view
ts
// src/views.ts
/// <reference types="@forinda/kickjs-view/virtual" />
import kickViews from 'virtual:kick-views'
import { createViews } from '@forinda/kickjs-view'

export const views = createViews({ ...kickViews, layout: 'layouts/main' })
ts
// src/index.ts
import { bootstrap } from '@forinda/kickjs'
import { KickView } from '@forinda/kickjs-view'
import { views } from './views'

export const app = await bootstrap({ modules, adapters: [KickView({ views })] })

virtual:kick-views comes from @forinda/kickjs-vite (included in kickjsVitePlugin()):

  • kick build: it checks every template and ships them in the build. A template with an error fails the build.
  • kick dev: it hands over only your pipes, and templates are read from src/views. An edit shows up on the next request.

Without Vite (plain Node, Bun, Deno), createViews() reads src/views itself.

Templates ​

Templates live in src/views/**/*.kick. ctx.render('users/show') renders src/views/users/show.kick. A name is folders and a file name made of letters, digits, - and _. Any other name, including .. or an absolute path, is refused, even when it comes from a request.

Interpolation ​

{{ expression }} prints a value, escaped for where it lands:

valueprints
stringescaped
number, bigint, booleanas text (true)
null, undefinednothing
DateISO string — use | date for display
array, object, Promisenothing, with a warning in dev (an error with strict: true)

{{ html | raw }} prints trusted HTML unescaped. raw must be the whole expression's last pipe, and it isn't allowed in attributes, <title> or <textarea>. Inside <style> it's allowed only as the element's whole content: <style>{{ css | raw }}</style>.

Expressions ​

Templates read data; controllers compute it. An expression can use:

  • property paths: user.name, user?.address?.city, items[0], row[key]
  • literals: 'text', "text", 42, -1.5, true, false, null
  • !, -, +, -, <, >, <=, >=, ==, !=, &&, ||, ??, a ? b : c
  • pipes: price | currency:'KES':'1.2-2'

Calls, assignment, new, * / %, arrow functions and object or array literals are compile errors. Methods and other functions read as undefined, and __proto__ / constructor / prototype are never reachable.

== and != are strict (1 == '1' is false). Truthiness follows JavaScript, so an empty array is truthy: write @if (items.length), or use @for … @empty.

Pipes bind loosest: a ? b : c | upper pipes the whole conditional. A conditional pipe argument needs parentheses.

precedence, low to high
|
? :
??
||
&&
== != === !==
< > <= >=
+ -
! - (unary)
. ?. []

A name the data doesn't have prints nothing and logs a warning in dev. With strict: true it's an error, except on the left of ?? or before ?.: {{ showPositions ?? true }} and {{ fees?.paid }} read a missing name as undefined, so an optional field needs no placeholder in the data. In a chain, {{ a ?? b ?? 'none' }}, only the last fallback must exist.

Control flow ​

kick
@if (user.isAdmin) {
  …
} @else if (user; as u) {
  Hi {{ u.name }}
} @else {
  …
}

@for (item of items; track item.id; let i = $index, last = $last) {
  …
} @empty {
  …
}

@switch (order.status) {
  @case ('paid') {
    Paid
  }
  @case ('due') {
    Due
  }
  @default {
    Unknown
  }
}

@let total = order.subtotal + order.shipping;
  • @for loops over arrays, Sets, strings, and Maps (@for ([key, value] of map)). A plain object needs | entries. null shows @empty.
  • Loop variables: $index, $first, $last, $even, $odd, $count.
  • track is accepted and ignored.
  • A line holding only @if (…) { or } leaves no blank line in the output.

Comments and literal text ​

  • {{-- not in the output --}} is a template comment. HTML comments are kept, and can't contain {{ }}.
  • @ starts a block only before a keyword in text, so hi@example.com and Alpine's @click="…" stay as written.
  • A literal } inside a block is &#125;.
  • @verbatim { … } outputs its content untouched, for pages that ship Vue, Alpine or Handlebars templates to the browser.

Attributes and bindings ​

kick
<a href="/users/{{ user.id }}">profile</a>
<button [disabled]="!canEdit">Save</button>
<li class="item" [class.active]="item.id == current">…</li>
<div [style.width.px]="progress">…</div>
  • [attr]="expr" drops the attribute for null, undefined or false, and writes it bare for true.
  • [class.name] adds a class when the value is truthy.
  • [style.prop] (.px and other units allowed) sets one property. A value that could leave its property (;, url(, quotes) is dropped.
  • class and style themselves can't be interpolated; use the bindings.

Escaping and what's refused ​

where {{ }} landswhat happens
text, <title>, <textarea>HTML-escaped
a quoted attributeHTML-escaped
a URL attribute (href, src, action, srcset, …)also scheme-checked: anything but http, https, mailto, tel or a relative URL becomes #
<script type="application/json">{{ data | json }}</script>JSON escaped so it can't close the script
<style>{{ css | raw }}</style>, as the whole content (CSS inlined for a PDF or an email)printed as is; the render fails if it contains </style
any other <script> / <style> content, on* attributes, style, srcdoc, a refresh <meta>, an HTML comment, an unquoted attribute, a tag or attribute namecompile error

<script src="{{ cdn }}" nonce="{{ cspNonce }}"> is fine: only a script's content is refused.

Layouts ​

kick
{{-- src/views/layouts/main.kick --}}
<!doctype html>
<html>
  <head>
    <slot name="head"><title>My app</title></slot>
  </head>
  <body>
    <slot />
  </body>
</html>
kick
{{-- src/views/about.kick --}}
@layout('layouts/main')
@slot('head') {
  <title>About</title>
}
<h1>About us</h1>

A page renders into its layout's <slot />. @slot('name') { … } fills a named slot, replacing the slot's fallback content. Layouts can declare their own @layout and nest.

Dashboards: layouts by folder, and a base layout ​

ts
createViews({
  ...kickViews,
  layout: {
    admin: 'layouts/admin', // admin/** pages
    'admin/reports': 'layouts/reports', // the longest prefix wins
    seller: 'layouts/seller',
    '': 'layouts/page', // everything else
  },
  baseLayout: 'layouts/base',
})
  • layout mapping: a page that declares no @layout gets the layout of the longest folder prefix matching its name. Each dashboard keeps its own layout without every page repeating it.
  • baseLayout: the HTML shell, with CSS, @assets and SEO tags, wrapped around every page's outermost layout, so the dashboard and page layouts don't each have to include it. A page fills the base's slots (@slot('head') { … }) through whatever layouts sit in between.
  • Precedence:
    1. ctx.render(name, data, { layout: false }) renders no layout at all, for htmx and other partial responses.
    2. { layout: 'layouts/print' } picks one layout for this render.
    3. @layout(none) in the page skips layouts, base included.
    4. @layout('…') in the page.
    5. The mapping.
    6. The base alone.

Components ​

kick
{{-- src/views/components/user-card.kick --}}
@input user
@input compact = false
<div class="card">
  <strong>{{ user.name }}</strong>
  @if (!compact) {
    <p>{{ user.email }}</p>
  }
  <slot>No details</slot>
  <footer><slot name="footer" /></footer>
</div>

{{-- in a page --}}
@for (u of users; track u.id) {
  <user-card [user]="u" compact class="mb-2">
    Joined {{ u.joined | date:'mediumDate' }}
    @slot('footer') {
      <a href="/users/{{ u.id }}">Open</a>
    }
  </user-card>
}
  • A tag with a hyphen that matches src/views/components/<path>.kick is a component. Folders join with -, so components/forms/text-field.kick is <forms-text-field>. The component's content replaces the tag.
  • @input name is required; @input name = value has a default.
    • [name]="expr" passes an expression, name="text" a string, and a bare name true.
    • compact="false" passes the string "false", which is truthy, so write [compact]="false".
    • Kebab-case (user-id="1") binds userId.
    • A missing or unknown input fails the check.
  • class, id, style, role, aria-* and data-* on the tag go to the component's single root element, with classes merged.
  • A component sees only its inputs. Content passed between its tags uses the page's data.
  • Components can include themselves (trees), up to 64 levels deep.

Components with a script ​

A component can carry its own browser code. Pages that render it get one small script for it; pages that don't get none, so a page stays free of JavaScript until it uses such a component.

kick
{{-- src/views/components/flash-toast.kick --}}
@input message
@input timeout = 0
<kick-toast timeout="{{ timeout }}" role="status">
  <p>{{ message }}</p>
  <button data-close aria-label="Dismiss">×</button>
</kick-toast>

<script client>
  class KickToast extends HTMLElement {
    connectedCallback(): void {
      const ms = Number(this.getAttribute('timeout'))
      if (ms > 0) setTimeout(() => this.remove(), ms)
      this.querySelector('[data-close]')?.addEventListener('click', () => this.remove())
    }
  }
  customElements.get('kick-toast') || customElements.define('kick-toast', KickToast)
</script>
kick
@if ($flash.success) {
  <flash-toast [message]="$flash.success" [timeout]="5000" />
}
  • What it is. <script client> holds TypeScript for the browser, usually a custom element that the component's markup uses. The component's file name and the custom element's tag differ (flash-toast renders <kick-toast>): a tag that names a component file is that component.

  • What ships. When a page renders the component, the page gets <script type="module" src="/_kick/c/flash-toast.<hash>.js"> before </body>, once however many times the component renders, and with a nonce when the page data has cspNonce. The hash changes with the code, and the file caches for a year. A component inside a false @if ships nothing.

  • Passing data. Give the element attributes (escaped like any other); for structured data, a <script type="application/json"> child. The script is the same for every render, so it can't use {{ }}.

  • Imports. A script can import your own modules (./format, @/lib/dates, with your Vite aliases) and npm packages:

    ts
    import { relativeTime } from './format'
    import { computePosition } from '@floating-ui/dom'

    kick build bundles every component's script in one browser build: each component gets an entry, and code several components import goes into shared chunks, loaded once and sharing its state. Under kick dev, the scripts go through Vite's dev pipeline, so imports resolve the same way and edits show on the next load. On plain Node without Vite there's no bundler: scripts that import fail with a clear message, and self-contained scripts still work.

    The browser build takes your app's define, mode, .env files and aliases, not its Vite plugins. A script can import CSS too (import './toast.css'): after kick build, a page that renders the component links the stylesheet in its <head> (with the page's nonce), and under kick dev Vite injects it. Images and fonts a script or its CSS imports are inlined as data URIs up to 4 KB; larger ones are files of their own.

  • Types. kick build strips the TypeScript and ships plain JS, which is what edge runtimes serve. Under kick dev, Vite strips it. On plain Node, the server strips self-contained scripts with Node's built-in stripper, which needs Node 22.13 or later. The editor treats the block as TypeScript; it doesn't type-check it yet.

  • Rules. Only in components, at the top level, one per component. Other <script> tags render inline as before.

  • Where the files go. kick build writes every client file (entries, shared chunks, CSS, larger images and fonts) to dist/public/_kick/c/, with the content hash in each name. On Node, KickView serves them from there, cached for a year. On an edge runtime, the platform serves that folder before your worker: kick g deploy sets it up for Netlify and Vercel, and on Cloudflare point assets.directory in wrangler.toml at dist/public. For a host with no static files, kickjs({ views: { clientFiles: 'bundle' } }) keeps everything in the server bundle and inlines every image and font.

  • Serving. KickView serves the scripts on Express, Fastify and h3. On the web fetch entry, call clientScriptResponse ahead of the app: fetch: async (req) => (await clientScriptResponse(views, req)) ?? web.fetch(req). The path is clientScriptPath (default /_kick/c); set it in vite.config.ts (kickjs({ views: { clientScriptPath } })), and ...kickViews passes it to createViews.

  • Swapped HTML. A custom element starts whenever it lands in the page, so components inside HTML swapped in by htmx or Turbo work without extra code.

Toast messages ​

A toast for flash messages, built as a component with a script. Copy it into your app and style it as you like; KickJS doesn't ship UI components.

kick
{{-- src/views/components/flash-toast.kick --}}
@input message
@input kind = 'info'
@input position = 'top-right'
@input timeout = 5000
<kick-toast popover="manual" role="status" kind="{{ kind }}" position="{{ position }}" timeout="{{ timeout }}">
  <p>{{ message }}</p>
  <button type="button" data-close aria-label="Dismiss">×</button>
</kick-toast>

<script client>
  class KickToast extends HTMLElement {
    private timer = 0

    connectedCallback(): void {
      // The popover top layer: above everything, no z-index needed.
      this.showPopover?.()
      this.querySelector('[data-close]')?.addEventListener('click', () => this.remove())
      const ms = Number(this.getAttribute('timeout'))
      if (ms > 0) {
        const pause = () => window.clearTimeout(this.timer)
        // One timer at a time: hover and focus can resume it twice in a row.
        const start = () => {
          pause()
          this.timer = window.setTimeout(() => this.remove(), ms)
        }
        // Readers get time: hovering or focusing it holds the toast.
        this.addEventListener('mouseenter', pause)
        this.addEventListener('mouseleave', start)
        this.addEventListener('focusin', pause)
        this.addEventListener('focusout', start)
        start()
      }
    }
  }
  customElements.get('kick-toast') || customElements.define('kick-toast', KickToast)
</script>

In the layout, one toast per flash kind (info, success, warn, error):

kick
@for ([kind, message] of $flash | entries; track kind) {
  <flash-toast [kind]="kind" [message]="message" />
}
css
kick-toast {
  position: fixed;
  margin: 0;
  inset: auto;
}
kick-toast[position='top-right'] {
  top: 1rem;
  right: 1rem;
}
kick-toast[position='bottom-left'] {
  bottom: 1rem;
  left: 1rem;
}
kick-toast[kind='success'] {
  border-left: 4px solid green;
}
kick-toast[kind='error'] {
  border-left: 4px solid crimson;
}
  • Position and kind are attributes, so CSS places and colours each toast; add the corners you use.
  • The timeout is in milliseconds; [timeout]="0" keeps a toast until it's dismissed. Hover and focus pause it.
  • Several toasts stack in the order they render; give later ones an offset in CSS if they share a corner.
  • Screen readers announce what changes in a role="status" region; a toast already in the page when it loads usually isn't read out. For flash messages after a redirect, fill the <p> from the script after showPopover() (keep the text in an attribute) if announcements matter.
  • Without JavaScript a popover element stays hidden. Leave popover off and position the toast with CSS alone if the message must show without scripts.

Pipes ​

pipeexample
uppercase, lowercase, titlecase{{ name | titlecase }}
date:format:timeZone?{{ at | date:'short' }} — short, medium, long, full, shortDate, mediumDate, longDate, fullDate, shortTime, mediumTime
number:digits{{ n | number:'1.0-2' }} — minInt.minFrac-maxFrac
currency:code:digits?{{ price | currency:'KES' }}
percent:digits?{{ ratio | percent }}
slice:start:end{{ items | slice:0:3 }}
join:separator?{{ names | join:', ' }} — a list as text; ', ' by default
compact{{ addressLines | compact | join:' · ' }} — drops null, undefined, false and '', keeps 0
keys, entries@for ([k, v] of obj | entries) { … }
json{{ data | json }}
urlhref="/search?q={{ term | url }}"
kvRoute:param…href="{{ 'UsersController.show' | kvRoute:user.id }}" — see Links to routes
kvQuery:key:value…href="{{ 'UsersController.list' | kvRoute | kvQuery:'page':page }}" — query parameters, see Links to routes
raw{{ html | raw }}

Dates and numbers use locale (default en-US) and timeZone (default UTC, never the server's zone). Set them in createViews, per request through share, or per call: ctx.render(name, data, { locale: 'sw-KE', timeZone: 'Africa/Nairobi' }).

kvRoute turns a route's name into its URL, the way ctx.urlFor() does in a controller, so a moved route can't leave a link pointing at the old path:

kick
<a href="{{ 'UsersController.show' | kvRoute:user.id }}">{{ user.name }}</a>
<form method="post" action="{{ 'PostsController.update' | kvRoute:user.id:post.slug }}"></form>
<a href="{{ 'UsersController.list' | kvRoute | kvQuery:'page':2 }}">All users</a>
  • The name is 'Controller.method'; the API prefix and version are included.

  • The arguments fill the route's :params in the order its path has them (/users/:id/posts/:slug takes user.id, then post.slug), encoded. A wrong count, or a name no route has, fails the render with the route's own message.

  • Order is what matters, not names: two arguments swapped give a wrong URL, not an error. Keep them in the path's order.

  • An argument is any expression: data, a literal, a ?? b. A conditional needs parentheses, as for any pipe argument: kvRoute:org.slug:(draft ? 'drafts' : 'posts').

  • Query parameters: chain kvQuery with key/value pairs. Values are encoded; null, undefined and '' leave their key out, so optional filters pass straight through; an array repeats the key. It adds to a query the URL already has and keeps a #fragment last, so it works on any URL, not only kvRoute's:

    kick
    <a href="{{ 'UsersController.list' | kvRoute | kvQuery:'page':page + 1:'role':filters.role }}">Next</a>
  • It needs the request: inside ctx.render. For a page rendered elsewhere (an email, a job), build the URLs with ROUTE_URLS and pass them in as data.

Your own pipes ​

Export them from src/views/pipes.ts:

ts
import { safeHtml, withEnv } from '@forinda/kickjs-view'

export const initials = (name: string) =>
  name
    .split(' ')
    .map((p) => p[0])
    .join('')

export function stars(n: number) {
  return safeHtml('★'.repeat(n)) // trusted HTML, printed as is in text
}

export const ago = withEnv(
  ({ locale }) =>
    (date: Date) =>
      new Intl.RelativeTimeFormat(locale).format(
        Math.round((+date - Date.now()) / 86_400_000),
        'day',
      ),
)

Some rules, because the build and the editor read this file without running it:

  • Export each pipe by name: export const, export function, or export { a, b as c }. export *, default exports and re-exports aren't allowed.
  • A pipe can't reuse a built-in's name.
  • Pipes are synchronous. Load data in the controller.

Forms ​

A form post that fails validation goes back to the form with each field's error and what was typed, and a controller can leave a message for the next page:

ts
// src/index.ts
import { bootstrap, formErrorHandler, session } from '@forinda/kickjs'
import express from 'express'

export const app = await bootstrap({
  modules,
  middlewares: [
    // Express only: listing `middlewares` replaces the default pipeline, body
    // parsers included, and forms post urlencoded. Fastify and h3 parse bodies themselves.
    express.urlencoded({ extended: false }),
    session({ secret: env.SESSION_SECRET, store: 'cookie' }),
  ],
  adapters: [KickView({ views })],
  onError: formErrorHandler(), // with Inertia: formErrorHandler(inertiaErrorHandler())
})
ts
import { flash } from '@forinda/kickjs'

@Post('/products', { body: createProductSchema })
async create(ctx: RequestContext) {
  await this.products.create(ctx.body)
  flash(ctx, { success: 'Product saved' })
  ctx.redirect('/products')
}
kick
@if ($flash.success) {
  <p class="notice">{{ $flash.success }}</p>
}
<form method="post" action="/products">
  <input name="title">
  @error('title') {
    <b class="field-error">{{ $message }}</b>
  }
  <textarea name="description"></textarea>
  <button>Save</button>
</form>
  • Going back. When route validation fails on a browser form submit (urlencoded or multipart, asking for HTML, not an Inertia visit), formErrorHandler() stores the errors and the submitted values in the session and redirects (303) to the page the form was on: the last full page a GET rendered in this session, else the Referer when it's this site, else formErrorHandler(fallback, { fallbackUrl }) (default /). fetch() posting FormData, API calls and everything else go to the usual error handler. It needs session(); without it a failed form post gets the usual 422. With Inertia, put Inertia's handler inside: formErrorHandler(inertiaErrorHandler()).

  • In templates. Every template, components included, has $errors (field → first message, form for the body as a whole), $old (what was submitted) and $flash (what flash() set). Each shows on the next page only. @error('field') { … } renders when that field has an error, with the message as $message.

  • Refilling. A named <input>, <textarea>, <select> (its <option>s), checkbox or radio takes its value back from $old by itself. It's left alone when the template sets value, checked or selected, and never refilled for passwords, files, hidden fields, a bound [type], or names that look like secrets (password, pwd, pin, otp, token, secret, card, cvv, csrf). Options and checkboxes compare with their value, written or interpolated (value="{{ c.id }}"). The values ride in the session, so they're capped: a field over 1,000 bytes isn't kept, and over 1,500 bytes in all nothing is (the errors still are), so a cookie session can't overflow.

  • Re-rendering instead. A controller can answer with the form itself; its own $errors and $old win over the session's:

    ts
    import { fieldErrors } from '@forinda/kickjs'
    
    // issues: [{ field: 'title', message: 'Too short' }], the shape route validation uses
    const issues = await this.products.check(ctx.body)
    if (issues.length)
      return ctx.render('products/new', { $errors: fieldErrors(issues), $old: ctx.body })
  • Field names are flat (title, email) for now. Nested names (items[0][name]) and lists of values (a group of checkboxes with one name) aren't refilled yet.

Checking in the browser ​

Add validate to a field for instant feedback, before the form is sent. It writes into the same @error spot the server's message uses:

kick
<input name="email" validate="required | email">
@error('email') {
  <b>{{ $message }}</b>
}
<input name="title" validate="required | minLength:3 | maxLength:120">
@error('title') {
  <b>{{ $message }}</b>
}
  • Validators: required, email, url (http or https), minLength:n and maxLength:n (characters), min:n and max:n (numbers), pattern:'regex' (the whole value), in:'a, b, c'. An empty field passes everything except required. An unknown validator or a wrong argument fails the check.
  • When it runs: when the field loses focus, then as it changes once it has been checked, and on submit. A submit with an invalid field is stopped and the first one gets focus. required on a radio or checkbox passes when any one in the group with that name is checked. The browser's own checks on the same form (a plain required, type="email") still run after these pass; forms without a validate field are left entirely to the browser.
  • Where messages go: @error('field') always renders a <span data-kick-error="field" aria-live="polite"> spot, hidden while there's no error: the server's message in it after a failed submit, the browser's while typing. Because it's a <span>, keep the body inline (text, <b>, <small>); a <p>, <li> or <tr> inside it is invalid HTML, and in a table the browser moves it out. Style it with [data-kick-error]:not([hidden]), so empty spots stay hidden. The field gets aria-invalid and aria-describedby pointing at its message, and setCustomValidity, so :user-invalid works in CSS.
  • What ships: a page with a validate field gets one small validator script (/_kick/c/kick-validate.<hash>.js); pages without one get none.
  • The server still decides. These checks are for quick feedback; route validation in the controller is what counts, and its messages can differ.

Your own validators ​

Rules of your own go in src/views/validators.ts, next to pipes.ts. Each export is a validator, used by its name like the built-ins:

ts
// src/views/validators.ts
export const phone = (value: string) =>
  /^\+?\d{9,15}$/.test(value) ? undefined : 'Enter a phone number'

export const sameAs = (value: string, other: string, form: HTMLFormElement) =>
  value === (form.elements.namedItem(other) as HTMLInputElement | null)?.value
    ? undefined
    : 'Must match'
kick
<input name="phone" validate="required | phone">
@error('phone') {
  {{ $message }}
}
<input name="password" type="password" validate="required | minLength:8">
<input name="confirm" type="password" validate="sameAs:'password'">
@error('confirm') {
  {{ $message }}
}
  • The contract: a validator gets the field's value, then the arguments written in the template (numbers or quoted strings), then the form. It returns the message when the value fails. Anything else passes: undefined, null, false, an empty string, true.
  • Same rules as the built-ins: an empty field skips them (only required checks for one), they run in the order written, and the first message wins. A validator that throws counts as a pass and is logged with console.error, so a bug can't block the form.
  • Checked like pipes: an unknown name fails kick build, kick check:views and the page in kick dev, and the editor marks it. An export named like a built-in fails kick build and kick check:views; kick dev logs a warning and the built-in keeps its meaning. The editor also completes validator names inside validate="…".
  • What ships: the file can import npm packages and your own files, like a component script. kick build bundles it as kick-validators.<hash>.js, loaded after the built-in validator script on pages with a validate field; kick dev serves it through Vite. Running from source without either, it's served as is with its types stripped, and an import fails the page, as it does for component scripts.
  • Browser only. The route's schema still decides on the server; a rule that needs your data is a server check.

Your own checks ​

validate covers the common rules. For anything else, a component with a script can run your own code against the same @error spots. Two recipes cover most needs.

The route's schema, in the browser. A component script can import your files and npm packages, so it can import the schema the route validates with. The rules then live in one file and the messages match the server's:

ts
// src/client/check-form.ts — shared by every form that checks itself
/// <reference lib="dom" />
import type { z } from 'zod'

/** Each field's first message, as route validation reports them. */
function messages(form: HTMLFormElement, schema: z.ZodType): Record<string, string> {
  const result = schema.safeParse(Object.fromEntries(new FormData(form)))
  const out: Record<string, string> = {}
  if (!result.success)
    for (const issue of result.error.issues) out[String(issue.path[0] ?? 'form')] ??= issue.message
  return out
}

/** Fills the form's `@error` spots, for one field or all of them. */
function show(form: HTMLFormElement, errors: Record<string, string>, only?: string): void {
  for (const spot of form.querySelectorAll<HTMLElement>('[data-kick-error]')) {
    const field = spot.dataset.kickError!
    if (only && field !== only) continue
    const message = errors[field] ?? ''
    spot.textContent = message
    spot.hidden = !message
    const input = form.elements.namedItem(field)
    if (input instanceof HTMLElement && 'setCustomValidity' in input) {
      ;(input as HTMLInputElement).setCustomValidity(message)
      input.setAttribute('aria-invalid', String(!!message))
    }
  }
}

/** Checks a field when it loses focus, and every field on submit. */
export function checkWith(form: HTMLFormElement, schema: z.ZodType): void {
  form.noValidate = true
  form.addEventListener('focusout', (e) => {
    const name = (e.target as HTMLInputElement).name
    if (name) show(form, messages(form, schema), name)
  })
  form.addEventListener('submit', (e) => {
    const errors = messages(form, schema)
    show(form, errors)
    const first = Object.keys(errors)[0]
    if (!first) return
    e.preventDefault()
    ;(form.elements.namedItem(first) as HTMLElement | null)?.focus()
  })
}
kick
{{-- src/views/components/task-form.kick --}}
@input categories
<task-form-check>
  <form method="post" action="/tasks">
    <input name="title" placeholder="What needs doing?">
    @error('title') {
      {{ $message }}
    }
    <select name="categoryId">
      <option value="">None</option>
      @for (c of categories; track c.id) {
        <option value="{{ c.id }}">{{ c.name }}</option>
      }
    </select>
    <button>Add</button>
  </form>
</task-form-check>

<script client>
  import { checkWith } from '@/client/check-form'
  import { taskSchema } from '@/modules/tasks/tasks.schemas'

  class TaskFormCheck extends HTMLElement {
    connectedCallback(): void {
      checkWith(this.querySelector('form')!, taskSchema)
    }
  }
  customElements.get('task-form-check') || customElements.define('task-form-check', TaskFormCheck)
</script>
  • Browser types. The server's tsconfig has no DOM types, so a browser file under src/ names them with /// <reference lib="dom" />. Component scripts don't need it.
  • Keep schemas in their own files. Whatever the schema file imports goes to the browser with it. A schema next to a database client, or anything from node:, pulls that into the client build or breaks it. A *.schemas.ts that imports only zod is safe to share.
  • Size. Zod adds about 23 KB gzipped to the component's script, and only pages that render the component load it. For a form that needs only required or minLength, validate is a fraction of that.
  • Content Security Policy. Zod 4 tries new Function once for a faster path. Under a CSP without 'unsafe-eval' the browser reports it as blocked, and Zod carries on without it.
  • Without JavaScript the form posts as usual, and route validation answers with the same messages.

Checks that need the server. Whether an email is already registered, or a name is taken, only the server knows. Give the component a small endpoint to ask, and show the answer in the field's spot:

ts
@Get('/register/email-taken')
async emailTaken(ctx: RequestContext) {
  const email = String(ctx.query.email ?? '').trim().toLowerCase()
  ctx.json({ taken: email !== '' && (await this.users.exists(email)) })
}
kick
<email-check>
  <input name="email" type="email">
  @error('email') {
    {{ $message }}
  }
</email-check>

<script client>
  class EmailCheck extends HTMLElement {
    connectedCallback(): void {
      const input = this.querySelector('input')!
      const spot = this.querySelector<HTMLElement>('[data-kick-error="email"]')!
      input.addEventListener('change', async () => {
        const res = await fetch(`/register/email-taken?email=${encodeURIComponent(input.value)}`)
        const { taken } = (await res.json()) as { taken: boolean }
        spot.textContent = taken ? 'That email is already registered' : ''
        spot.hidden = !taken
      })
    }
  }
  customElements.get('email-check') || customElements.define('email-check', EmailCheck)
</script>

The route that saves the form still checks again, since two people can claim the same email between the check and the submit. Rate-limit an endpoint like this one so it can't be used to list your users.

Shared data ​

ts
import { csrfToken } from '@forinda/kickjs'

createViews({
  ...kickViews,
  share: (ctx) => ({
    user: ctx?.get('user'),
    cspNonce: ctx?.get('cspNonce'),
    csrfToken: csrfToken(ctx),
  }),
})

share runs for every ctx.render, inside the request, and its values sit under the page's own data. Set a CSP nonce in middleware with ctx.set; csrfToken(ctx) is the token csrf() or csrfGuard() issued for this request. Use them in the base layout and in forms:

kick
<meta name="csrf-token" content="{{ csrfToken }}">
<script nonce="{{ cspNonce }}" src="/app.js"></script>

<form method="post" action="/tasks">
  <input type="hidden" name="_csrf" value="{{ csrfToken }}">
</form>

Assets ​

@assets('src/client/main.ts') writes the tags for a Vite entry. Give createViews an assets function:

ts
import { assetTags } from '@forinda/kickjs-view'
import manifest from '../dist/client/.vite/manifest.json' with { type: 'json' }

const mode = import.meta.env.DEV ? { dev: true, base: '/' } : { dev: false, manifest, base: '/' }

createViews({
  ...kickViews,
  assets: (entry, data) => assetTags(entry, mode, data.cspNonce as string),
})

In dev that's the Vite client plus the module. In a build it's the hashed script, its CSS and preload tags, each with the nonce when there is one.

Partials and htmx ​

ts
@Get('/users/rows')
async rows(ctx: RequestContext) {
  await ctx.render('users/rows', { users }, { layout: false })
}

ctx.render also takes status and headers: { status: 422, headers: { 'HX-Retarget': '#form' } }.

Emails, PDFs and tests ​

views.render() works outside a request:

ts
const html = await views.render('emails/welcome', { name: user.name }, { layout: 'layouts/email' })
await mailer.send({ to: user.email, subject: 'Welcome', html })

Error pages ​

ts
bootstrap({
  modules,
  adapters: [KickView({ views })],
  onNotFound: async (req, res) => {
    res
      .status(404)
      .type('text/html; charset=utf-8')
      .send(await views.render('errors/404'))
  },
})

In dev a template error shows its file, line and column. In production the response is a plain 500, and the details go to the log.

Mixing with EJS or Pug ​

With KickView and ViewAdapter both installed (Express), ctx.render(name) renders the .kick template when there is one. Otherwise the name goes to ViewAdapter.

The edge ​

On Workers and Vercel Edge, @forinda/kickjs-view resolves to a build without file access: templates come from virtual:kick-views, checked when you build. Use viewsMiddleware(views) with the web entry:

ts
import kickViews from 'virtual:kick-views'
import { createViews, viewsMiddleware } from '@forinda/kickjs-view'

const views = createViews({ ...kickViews })
export default createWebApp({ h3, modules, middlewares: [viewsMiddleware(views)] })

Formatting and checking ​

Add the plugin to kick.config.ts:

ts
import { viewCliPlugin } from '@forinda/kickjs-view/cli'
export default defineConfig({ plugins: [viewCliPlugin] })
  • kick fmt:views formats every template: {{ x | pipe }} and @if (x) { spacing, indentation by nesting, and a closing tag or } on its own line when its opener is on an earlier one. <pre>, <textarea>, <script>, <style>, @verbatim and comments are left exactly as written. A file is only rewritten if the result means the same template; otherwise it's left alone with a warning.
  • kick fmt:views --check lists the files that would change and exits 1, which suits CI.
  • kick check:views reports every error with its file, line and column, the same checks the build runs: syntax, unknown pipes, component inputs, slots, layouts and unsafe interpolation.

Editor support ​

The KickJS VS Code extension understands .kick files:

  • highlighting for {{ }}, @if / @for / @switch, bindings and comments, on top of HTML;
  • errors as you type, from the same checks as kick check:views, including in unsaved files;
  • snippets for whole blocks — type kick- for kick-page, kick-layout, kick-component, kick-component-script, kick-for, kick-form, kick-field and kick-flash;
  • completion for @ keywords, pipes after |, components and their inputs, layout and slot names, and the names in scope inside {{ }};
  • HTML, CSS and Emmet completion inside templates;
  • hover on a pipe or a component to see its parameters or inputs;
  • go to definition on a component tag, @layout('…') or a pipe;
  • find references to a component, layout or pipe across templates;
  • rename a pipe (its uses and pipes.ts), a component (its tags and file) or a layout (its @layout('…') uses and file), and renaming a template file in the explorer updates its uses, including the ctx.render('…') calls that name it;
  • Format Document, with the same output as kick fmt:views;
  • template names inside ctx.render('…') in your controllers.

In a trusted workspace the editor uses your project's installed @forinda/kickjs-view, so it agrees with your build. If the project has none, it uses its bundled copy and says so once in the output panel.

Settings (relative to the workspace folder):

settingdefault
kickjs.views.dirsrc/views
kickjs.views.componentscomponents
kickjs.views.pipes<dir>/pipes.ts
kickjs.views.layoutnoneas createViews({ layout }): one name, or folder prefix → layout
kickjs.views.baseLayoutnoneas createViews({ baseLayout })
kickjs.views.trace.serveroff

If your createViews maps layouts by folder or sets a baseLayout, give the editor the same values in kickjs.views.layout and kickjs.views.baseLayout. The editor doesn't read your createViews call, so without them it can't tell which layout a page without @layout renders in, and warns that its @slot blocks have no layout to fill.

Other editors (Neovim, Vim, Helix, Emacs, JetBrains IDEs) can run the same language server directly: see .kick in other editors.

Options ​

optiondefault
viewsDir'src/views'
componentsDir'components'inside viewsDir
pipesFile'src/views/pipes.ts'.js also works; without Vite, Node runs a .ts file only when it can strip types (22.18+)
validatorsFile'<viewsDir>/validators.ts'your own validators; read when there is no build
layoutnonea layout name, or folder prefix → layout
baseLayoutnonethe shell around every page's outermost layout
locale'en-US'
timeZone'UTC'
strictfalseunknown names and values that can't print become errors
sharenone(ctx) => data
assetsnone(entry, data) => tags, for @assets
cachetruefalse re-reads every template on every render
devNODE_ENV !== 'production' (with KickView)re-check changed templates on each render
bundle, pipes, clientScriptPath, clientDirfrom virtual:kick-viewspass them all with ...kickViews; without clientDir, files the build wrote to disk aren't served
loaderthe file loader{ list, read, version? } for templates from anywhere else

The Vite plugin's own options, in vite.config.ts as kickjs({ views: { … } }):

optiondefault
viewsDir'src/views'
componentsDir'components'
pipesFile'src/views/pipes.ts'
validatorsFile'<viewsDir>/validators.ts'your own validators
clientScriptPath'/_kick/c'the URL path client files are served under
clientFiles'disk''bundle' keeps client files in the server bundle
publicDir'public'relative to the build's outDir, or absolute; files go to <publicDir><clientScriptPath>/
inlineLimit4096images and fonts up to this many bytes are inlined ('disk' only)

Released under the MIT License. Built with TypeScript — runs on Express, Fastify, or h3.