npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ynode/squirrellyify

v1.11.0

Published

Fastify 5 plugin for rendering Squirrelly templates with layout support, partials, and scoped configuration.

Readme

@ynode/squirrellyify

Copyright (c) 2025 Michael Welter [email protected]

npm version License: MIT

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.
  • 🧬 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.

Installation

You need to install squirrelly and fastify alongside this plugin.

npm install @ynode/squirrellyify squirrelly fastify

Basic Usage

  1. Register the plugin.
  2. 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.js

views/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:

  1. reply.context
  2. reply.locals
  3. reply.view(..., data) (highest precedence)

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 global mode they modify shared helpers/filters/partials.
  • In scoped mode 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 .sqrl tags 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.

Use check mode in CI to verify committed generated artifacts without replacing them:

squirrellyify-client --check build/squirrelly-client.config.mjs

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):

  1. 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 });
    });
  2. 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.

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: {
            capitalize: (str) => {
                return str.charAt(0).toUpperCase() + str.slice(1);
            },
        },
        filters: {
            truncate: (str, len) => {
                return str.length > len ? str.substring(0, len) + "..." : str;
            },
        },
    },
});

License

This project is licensed under the MIT License.