@ynode/squirrellyify
v1.11.2
Published
Fastify 5 plugin for rendering Squirrelly templates with layout support, partials, and scoped configuration.
Maintainers
Readme
@ynode/squirrellyify
Copyright (c) 2026 Michael Welter [email protected]
A simple and fast plugin for using the Squirrelly template engine with Fastify.
Features
- 🐿️ Modern Templating: Full support for Squirrelly v9 features.
- ⚡ High Performance: Template caching is enabled by default in production.
- 📁 Layouts & Partials: Built-in support for layouts and shared partials.
- 🧩 Composable Rendering:
reply.renderView()returns HTML without sending a response. - 🧬 Encapsulation-Aware: Supports Fastify encapsulation with scoped template settings.
- 🛡️ Secure: Protects against path traversal attacks in template names.
- 🔧 Extensible: Easily add custom Squirrelly helpers and filters.
- 🌐 Client Modules: Precompiles named partials into self-contained, CSP-friendly browser ES modules.
Node.js support
This package requires Node.js 20.19.0 or newer. CI exercises the exact 20.19.0, 22.13.0, and 24.0.0 boundaries. Node.js 20 remains tested only to preserve the current major-version contract even though upstream support has ended; use Node.js 22 or 24 for supported production deployments. A newly released Node.js major is not considered supported until it is added to CI, even when the open engines range admits it.
Installation
You need to install squirrelly and fastify alongside this plugin.
npm install @ynode/squirrellyify squirrelly fastifyBasic Usage
- Register the plugin.
- Use the
reply.view()decorator in your routes.
By default, the plugin looks for templates in a views directory in your project's root.
File structure:
.
├── views/
│ └── index.sqrl
└── server.jsviews/index.sqrl
<h1>Hello, {{ it.name }}!</h1>server.js
import Fastify from "fastify";
import squirrellyify from "@ynode/squirrellyify";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const fastify = Fastify({
logger: true,
});
fastify.register(squirrellyify, {
templates: path.join(__dirname, "views"),
});
fastify.get("/", (request, reply) => {
return reply.view("index", { name: "World" });
});
fastify.listen({ port: 3000 }, (err) => {
if (err) throw err;
});Request-Scoped View Data
reply.view(template, data) automatically merges request-scoped values from reply.locals and reply.context into the template data:
fastify.addHook("preHandler", async (request, reply) => {
reply.locals = { appName: "YNode", greeting: "Welcome" };
});
fastify.get("/", (request, reply) => {
// Route-level values win over locals/context on key conflicts.
return reply.view("index", { greeting: "Hello" });
});Merge precedence is:
reply.contextreply.locals- Explicit
datapassed toreply.view()orreply.renderView()(highest precedence)
Render Without Sending
Use reply.renderView(template, data) when a route needs the complete page-and-layout HTML as a string before deciding how to respond:
fastify.get("/preview", async (request, reply) => {
const html = await reply.renderView("index", { name: "Preview" });
return { html };
});renderView() uses the same request context, locals, scoped template directories, layout precedence, partials, and cache as view(). It does not set the content type, change the status, or call send(). Rendering failures reject normally, so an awaited or returned call flows through Fastify's configured error handler. Missing resources use the path-safe codes ERR_SQUIRRELLYIFY_TEMPLATE_NOT_FOUND and ERR_SQUIRRELLYIFY_LAYOUT_NOT_FOUND. In production, all failures use the generic ERR_SQUIRRELLYIFY_RENDER wrapper and retain the original error as cause for logging or explicit handlers.
reply.view() remains the send-oriented convenience method: it calls the same renderer, sets text/html; charset=utf-8, and sends the HTML. Its existing production-safe error response and development error delegation behavior are unchanged.
Configuration Options
You can pass an options object when registering the plugin.
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| templates | string \| string[] | path.join(process.cwd(), "views") | The directory or directories to search for page and layout templates. Searched in the provided order. |
| partials | string \| Array<string \| { dir, namespace }> | [] | The directory or directories for partial templates. All partials are loaded on startup and available by name. Array entries may be { dir, namespace } objects to namespace one directory independently. |
| partialsRecursive | boolean | true | If true, partials are loaded recursively from subdirectories. Names use forward slashes (for example, emails/header). |
| partialsNamespace | boolean \| string | false | Optional namespace prefix for partial names. Use true to prefix with each partials directory basename, or provide a custom string. Entries with their own namespace override this per directory. |
| layout | string | undefined | The name of the default layout file to use (without extension). Can be overridden per-route. |
| defaultExtension | string | "sqrl" | The file extension for all template files. Leading . is optional (for example, "html" or ".html"). |
| cache | boolean | NODE_ENV === "production" | If true, compiled templates and resolved file paths will be cached in memory. |
| sqrl | object | undefined | Squirrelly options. Supports { scope: "global" \| "scoped", config, helpers, filters }. |
Runtime API after registration:
fastify.viewHelpers.define(name, fn),fastify.viewHelpers.get(name),fastify.viewHelpers.remove(name)fastify.viewFilters.define(name, fn),fastify.viewFilters.get(name),fastify.viewFilters.remove(name)fastify.viewPartials.define(name, templateOrFn),fastify.viewPartials.get(name),fastify.viewPartials.remove(name)fastify.viewCache.clear(),fastify.viewCache.stats()
These APIs are scope-aware:
- In
globalmode they modify shared helpers/filters/partials. - In
scopedmode they only affect the current plugin registration scope.
The cache API is process-local and lets you invalidate compiled template/path caches at runtime when cache: true is used.
Invalid option types are rejected at plugin registration time with descriptive errors.
Client Render Modules
compileClientModule() turns one or more Squirrelly partials into a self-contained browser ES module. Compilation happens in Node, so generated modules do not use eval, new Function, or a browser Squirrelly dependency. Use buildClientModules() or the CLI in your asset build so no template compilation occurs when the application boots.
Each named template becomes a function on the generated module's frozen render object. Template names must be valid JavaScript identifiers.
import fs from "node:fs/promises";
import { compileClientModule } from "@ynode/squirrellyify";
const source = await compileClientModule({
templates: {
tableBody: { file: "views/client/history/table-body.sqrl" },
summary: { file: "views/client/history/summary.sqrl" },
filterChips: { file: "views/client/history/filter-chips.sqrl" },
},
filters: {
currency(value) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(Number(value));
},
},
});
await fs.writeFile("public/invoice/sqrl/history.js", source, "utf8");For repeatable builds, create a config module such as build/squirrelly-client.config.mjs:
export default {
modules: {
invoiceHistory: {
output: "../public/invoice/sqrl/history.js",
templates: {
tableBody: { file: "../views/client/history/table-body.sqrl" },
summary: { file: "../views/client/history/summary.sqrl" },
filterChips: { file: "../views/client/history/filter-chips.sqrl" },
},
},
},
};Paths in the config resolve from the config file's directory. Add the compiler to the application's normal asset build:
{
"scripts": {
"build:sqrl": "squirrellyify-client build/squirrelly-client.config.mjs"
}
}Each built module emits three artifacts by default:
history.js, the self-contained browser module.history.d.ts, a declaration whose renderer names and sync or async return types match the module.history.js.map, a source map that maps generated template operations back to their original.sqrltags and embeds template source content.
Set declaration: false or sourceMap: false on a module to disable an artifact. A non-empty path writes that artifact to a custom location. Repeated builds compare complete contents and leave unchanged files untouched.
Generated renderer parameters default to Record<string, unknown>. To make selected renderers accept application view-model types, map each template to a named type export and its module specifier:
export default {
modules: {
invoiceHistory: {
output: "../public/invoice/sqrl/history.js",
templates: {
tableBody: { file: "../views/client/history/table-body.sqrl" },
summary: { file: "../views/client/history/summary.sqrl" },
},
declarationTypes: {
tableBody: {
name: "HistoryRowsViewData",
from: "../../../types/invoice-history.js",
},
summary: {
name: "HistorySummaryViewData",
from: "../../../types/invoice-history.js",
},
},
},
},
};The generated declaration uses import type, groups named imports deterministically, and assigns private generated aliases so exports named Record, Promise, or render cannot shadow declaration internals. Module specifiers are authored relative to the generated .d.ts file. Unmapped renderers retain the generic input type. Template names must exist in the module, and imported type names must be JavaScript identifier names.
Use check mode in CI to verify committed generated artifacts without replacing them:
squirrellyify-client --check build/squirrelly-client.config.mjsUse --help for concise usage and --version to identify the installed artifact. Options may be terminated with --, which is required for a config path beginning with -. Invalid usage exits with status 2; build or config failures exit with status 1. Diagnostics omit stack traces by default. Add --debug when a maintainer needs the stack for troubleshooting.
The programmatic equivalent is buildClientModules({ ...config, check: true }). It rejects with ERR_CLIENT_MODULES_OUT_OF_DATE and a stale path list when an artifact differs or is missing.
The programmatic build API accepts the same object and returns metadata for every generated file:
import { buildClientModules } from "@ynode/squirrellyify";
const built = await buildClientModules({
modules: {
invoiceHistory: {
output: "public/invoice/sqrl/history.js",
templates: {
tableBody: { file: "views/client/history/table-body.sqrl" },
},
},
},
});The generated file can be imported as a normal browser module:
import * as history from "/invoice/sqrl/history.js";
tbody.innerHTML = history.render.tableBody(response);
summary.innerHTML = history.render.summary(response.summary);
chips.innerHTML = history.render.filterChips(response.filters);String template values are treated as inline Squirrelly source. File inputs must use an explicit { file } descriptor:
const source = await compileClientModule({
templates: {
inlineMessage: "<p>{{ it.message }}</p>",
tableBody: { file: "views/client/table-body.sqrl" },
},
});Templates in the same module may include one another by name. if, elif, else, try, each, foreach, include, and useScope are available. Use {{# elif(condition) }} for else-if branches; invalid elseif and elf spellings fail the build. Layout inheritance, file includes, useWith, and compiler plugins are intentionally rejected for client modules.
Custom helpers and filters are serialized into the generated module. Normal functions, method shorthand, and arrow functions are supported. They must be pure, browser-safe, and cannot reference Node APIs or closed-over values. Classes, generators, accessors, computed methods, native or bound functions, and built-in runtime overrides are rejected.
Async Client Modules
Async rendering is explicit at the module level. Set config.async: true and use Squirrelly's async marker at every asynchronous call site:
const source = await compileClientModule({
config: { async: true },
templates: {
rows: `
{{@ async each(it.rows) => row }}
<li>{{ row.accountId | async accountName }}</li>
{{/ each }}
`,
},
filters: {
async accountName(accountId) {
const response = await fetch(`/api/accounts/${encodeURIComponent(accountId)}`);
const account = await response.json();
return account.name;
},
},
});Every renderer in an async module consistently returns Promise<string>, including templates that contain no asynchronous operations:
tbody.innerHTML = await history.render.rows(response);Mark async helpers as {{@ async helper(...) /}}. In an async module, includes use {{@ async include("row", data) /}}. A block helper such as each, foreach, or useScope must also be marked async when its body performs async rendering. Missing markers fail compilation with a targeted error instead of producing a browser syntax error or rendering a Promise as text.
Advanced Usage
Layouts
Layouts are wrappers for your page templates. The rendered page content is injected into the body variable within the layout.
views/layouts/main.sqrl
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ it.title }}</title>
</head>
<body>
<header>My Awesome Site</header>
<main>
{{@block("content")}} {{@try}} {{it.body | safe}} {{#catch => err}} Uh-oh, error!
Message was '{{err.message}}' {{/try}} {{/block}}
</main>
</body>
</html>views/about.sqrl
{{@extends("layout", it)}} {{#content}}
<h2>About Us</h2>
<p>This is the about page content.</p>
{{/extends}}You can specify a layout in three ways (in order of precedence):
In the
reply.view()data object:fastify.get("/about", (request, reply) => { const pageData = { title: "About Page" }; // Use `main.sqrl` as the layout for this request return reply.view("about", { ...pageData, layout: "layouts/main" }); }); // To disable the default layout for a specific route: fastify.get("/no-layout", (request, reply) => { return reply.view("some-page", { layout: false }); });You can also pass layout-only data via
layoutData. Its keys are merged over the page data when the layout itself renders; the page template does not see them:fastify.get("/about", (request, reply) => { return reply.view("about", { title: "About Page", layout: "layouts/main", layoutData: { bodyClass: "about" }, }); });layout,layoutData, and the layout's injectedbodyvalue are reserved rendering keys. Build an allowlisted view model instead of spreading request bodies, query strings, or other untrusted objects intoreply.view(): a caller-controlledlayoutcan select any template inside the configured template roots. Path validation prevents traversal outside those roots, but it cannot decide which in-root layouts your application intends to expose.As a default plugin option:
fastify.register(squirrellyify, { templates: "views", layout: "layouts/main", // All views will use this layout by default });
Partials
Partials are reusable chunks of template code. Create a partials directory and place your files there. By default, partials are loaded recursively and registered by forward-slash path from the partials directory root.
partials/user-card.sqrl
<div class="card">
<h3>{{ it.name }}</h3>
<p>{{ it.email }}</p>
</div>views/index.sqrl
<h1>Users</h1>
{{@include('user-card', { name: 'John Doe', email: '[email protected]' })/}}Register the partials directory:
fastify.register(squirrellyify, {
templates: "views",
partials: "partials",
});Nested partials use forward-slash names:
partials/
└── cards/
└── user-card.sqrl{{@include('cards/user-card', { name: 'John Doe', email: '[email protected]' })/}}To disable recursive loading:
fastify.register(squirrellyify, {
templates: "views",
partials: "partials",
partialsRecursive: false,
});To namespace partial names:
fastify.register(squirrellyify, {
templates: "views",
partials: "partials",
partialsNamespace: "shared",
});{{@include('shared/cards/user-card', { name: 'John Doe', email: '[email protected]' })/}}To namespace directories independently, use { dir, namespace } entries. Plain string entries keep following partialsNamespace, so a shared chrome directory can stay bare while each feature directory gets its own prefix:
fastify.register(squirrellyify, {
templates: "views",
partials: [
"views/partials",
{ dir: "invoice/views/partials", namespace: "invoice" },
{ dir: "expense/views/partials", namespace: "expense" },
],
});{{@include('header')/}} {{@include('invoice/history-table', { rows: it.rows })/}}Scoped Configuration (Encapsulation)
This plugin supports Fastify's encapsulation model. You can register it multiple times with different settings for different route prefixes.
import Fastify from "fastify";
import squirrellyify from "@ynode/squirrellyify";
import path from "node:path";
import { fileURLToPath } from "node:url";
const fastify = Fastify();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Register with default settings
fastify.register(squirrellyify, {
templates: path.join(__dirname, "views"),
layout: "layouts/main",
});
fastify.get("/", (req, reply) => {
// Renders from ./views/index.sqrl with layouts/main.sqrl
return reply.view("index", { title: "Homepage" });
});
// Create a separate scope for an "admin" section
fastify.register(
(instance, opts, done) => {
// Override the templates directory and layout for this scope
instance.views = path.join(__dirname, "admin/views");
instance.layout = "layouts/admin";
instance.get("/", (req, reply) => {
// Renders from ./admin/views/dashboard.sqrl with layouts/admin.sqrl
return reply.view("dashboard", { title: "Admin Panel" });
});
done();
},
{ prefix: "/admin" },
);Custom Helpers and Filters
You can extend Squirrelly with custom helper and filter functions via the sqrl option.
Helpers receive a Squirrelly content object — { params, exec } — plus an array of blocks, so they can run their body once per iteration. Plain value transforms such as capitalize belong in filters, which do receive the piped value and any arguments directly.
Use sqrl.scope to choose registration mode:
global(default): helpers, filters, and partials are shared across plugin registrations.scoped: helpers, filters, and partials are isolated to each plugin registration.
You can also add/remove helpers and filters at runtime via fastify.viewHelpers and fastify.viewFilters.
fastify.register(squirrellyify, {
templates: "views",
sqrl: {
helpers: {
// {{@repeat(3) => index}}<li>Row {{index}}</li>{{/repeat}}
repeat: (content) => {
const [count] = content.params;
let result = "";
for (let index = 0; index < count; ++index) {
result += content.exec(index);
}
return result;
},
},
filters: {
// {{ it.name | capitalize }}
capitalize: (str) => str.charAt(0).toUpperCase() + str.slice(1),
// {{ it.name | truncate(3) }}
truncate: (str, len) => (str.length > len ? `${str.substring(0, len)}...` : str),
},
},
});License
This project is licensed under the MIT License.
