Skip to content

Writing droplets

A droplet is one folder: a component, and the code that loads its data. This page covers what goes in that folder and how the pieces connect. Styling covers its CSS and files, Actions its forms, and Server code what runs around it on the server.

One folder per droplet, under dropletsFolder (src/droplets by default):

src/droplets/<name>/
+droplet.<ext> # required: the component (.svelte, .vue, .tsx, .hbs…)
+droplet.ts # optional: load, props schema, handleError; server and browser
+droplet.server.ts # optional: load, handleError, entries, transform, actions; server only
+error.<ext> # optional: the error page, in the same framework

djs add <name> writes one, asking for the framework, the target and the optional files (see djs add).

  • The folder name is the droplet’s id, served under /droplets/<id>. It must be lowercase kebab-case (^[a-z0-9]+(-[a-z0-9]+)*$): hello-world/ works. A folder named otherwise (HelloWorld/, hello_world/) is not a droplet: vite dev and vite build skip it and warn once, listing such folders. No id is reserved.
  • The component’s extension picks the renderer that builds it. +Droplet.vue with a capital D works too. One component per folder: a +droplet.svelte next to a +droplet.vue is an error that says which one to keep.
  • Anything else is imported as usual, from the folder or anywhere in the project. A component several droplets share lives wherever you like; the dev server tracks which droplets depend on it.

Instead of a component, a droplet can be plain browser code: a +droplet.script.ts (see Script droplets).

Three flags decide how a droplet is delivered. They live in the droplet’s component, +droplet.<ext>, and nowhere else: <script module> in Svelte, a plain <script> in Vue, named exports in React, Preact, Solid, Hono JSX and Lit, the opening comment in Handlebars. Each renderer’s page shows where.

<script module lang="ts">
export const ssr = true; // false: nothing rendered on the server
export const hydrate = true; // false: no JavaScript; "visible" | "interactive": later
export const prerender = false; // true: rendered at build for `entries`
</script>
ssr hydrate Result
true true Server-rendered, then hydrated. The default.
true false Server-rendered only: HTML and CSS, no bundle built or served.
false true Client-only. The server load still runs and its data comes inline.
false false Nothing reaches the page: the fragment is an empty element, and no bundle is built. With prerender = true, the render made at build is served instead.
true "visible" Server-rendered; hydrates when it is about to scroll into view.
true "interactive" Server-rendered; hydrates on the first interaction with it.

"visible" and "interactive" are lazy hydration; a host page can also override hydrate per element with data-droplet-hydrate.

Side by side, with prerendering: what the host page receives in each mode, and when the droplet’s JavaScript loads.

The render modes side by sideClient-only (ssr = false): the server runs the load only; the fragment carries the data and no markup; the browser mounts the droplet at once. SSR + hydrate, the default: the server renders per request; the fragment carries the markup and the data; the browser hydrates it at once, when visible or on the first interaction. SSR only (hydrate = false): the server renders; the fragment carries the markup only; no JavaScript and no bundle. Prerendered (prerender = true): rendered at build for the props entries lists, other props live; the fragment carries the stored markup and data; the browser does as the hydrate flag says.Client-onlyssr = falseruns the load onlydata, no markupmounts at onceSSR + hydratethe defaultrenders per requestmarkup + datahydrates: at once,when visible or oninteractionSSR onlyhydrate = falserenders per requestmarkup onlyno JavaScript, nobundlePrerenderedprerender = truerendered at build forentries; other propslivestored markup + dataas its hydrate flagsaysThe render modes side by sideClient-only (ssr = false): the server runs the load only; the fragment carries the data and no markup; the browser mounts the droplet at once. SSR + hydrate, the default: the server renders per request; the fragment carries the markup and the data; the browser hydrates it at once, when visible or on the first interaction. SSR only (hydrate = false): the server renders; the fragment carries the markup only; no JavaScript and no bundle. Prerendered (prerender = true): rendered at build for the props entries lists, other props live; the fragment carries the stored markup and data; the browser does as the hydrate flag says.Client-onlyssr = falseruns the load onlydata, no markupmounts at onceSSR + hydratethe defaultrenders per requestmarkup + datahydrates: at once,when visible or oninteractionSSR onlyhydrate = falserenders per requestmarkup onlyno JavaScript, nobundlePrerenderedprerender = truerendered at build forentries; other props livestored markup + dataas its hydrate flag says
What the server does, what the fragment brings the host page, and what the browser does, per mode.

The demo server renders the same list of testimonials with five droplets, one per combination of flags, all sharing one Svelte component.

Each tab says what its droplet’s flags make the server and the browser do, and the console under it lists what this page asks the demo for.

Examples

Opens when the tab does.

Network, from this page

    What this page asks the demo server for: the fragments and API calls (fetch), and the modules and stylesheets the droplets load. A server load's event.fetch never shows here: it runs on the demo server, inside the request for the fragment.

    Rules for the flags:

    • Literal values, top-level export const. The flags decide how the droplet is built, so they are read from the component’s source before anything is compiled. ssr and prerender take true or false; hydrate takes true, false, "visible" or "interactive".
    • Anything else keeps the default, with a warning under vite dev and vite build: another value, or another form (export const ssr = !dev, export let, export { x as ssr }). A commented-out // export const ssr = false or a flag inside a string is no flag.
    • Only the component counts. An ssr, hydrate or prerender exported from +droplet.ts or +droplet.server.ts changes nothing.
    • One set of flags per droplet. +error.*, the droplet’s error boundary, follows the droplet’s flags: it renders on the server when the droplet does, hydrates when the droplet does and ships in the droplet’s bundle. Flags declared in the error page are ignored, with a warning.

    A script droplet has no flags: it is always client only.

    +droplet.ts props (a Standard Schema) server, and browser when no server rendered
    ↓ validated props
    +droplet.server.ts load({ request, host, locals, platform, cookies, fetch, setHeaders, droplet, props }) server only
    ↓ the result is inlined into the fragment
    +droplet.ts load({ host, props, data }) server and browser
    ↓ the result is the component's `data`
    +droplet.<ext> data

    The server load in +droplet.server.ts runs once per request, on the server. Its result is inlined into the fragment, so hydration needs no second round trip. Read secrets, databases, locals and cookies here; cookies are read only in a load.

    src/droplets/hello/+droplet.server.ts
    import { error, type LoadEvent } from "$droplets/server";
    export const load = async ({ props, locals }: LoadEvent) => {
    const who = typeof props.who === "string" ? props.who : "world";
    if (who.length > 40) error(404, "Nobody with a name that long lives here.");
    return { who, requestId: locals.requestId };
    };

    The universal load in +droplet.ts runs after it: on the server while rendering, and again in the browser before hydrating or mounting. It receives { host, props, data }, where data is what the server load returned (undefined without one), and shapes it into the component’s data.

    src/droplets/hello/+droplet.ts
    import type { load as serverLoad } from "./+droplet.server.ts";
    type ServerData = Awaited<ReturnType<typeof serverLoad>>;
    export const load = ({ data }: { data: ServerData }) => ({
    ...data,
    greeting: `Hello ${data.who}!`,
    });

    Keep it pure: it has to produce the same result on both sides, or the hydrated markup will not match what the server rendered.

    Both files are optional. With neither, data is undefined and the component simply renders. Both return a plain object, or nothing. A Response (from json(), say) is refused: responses belong in +server.ts.

    • error(status, message) from $droplets/server stops a server load: the fragment answers with that status, and no component renders.
    • redirect(status, location) answers the fragment request with a redirect, for the browser or the host page’s server to follow. A relative target is resolved against host.
    • The target must be on this server, its droplet location, a trusted origin or the configured host. Any other target answers 400 (Bad Request: the droplet redirects off this site), with a line in the server log.
    • The element never follows a redirect. When the _data request it sends is answered with one, it logs <id>: _data answered opaqueredirect and renders nothing.
    • Anything else a load throws goes to the error page.

    host in a load’s event is the page the droplet renders on, as a URL: the host page. It is not where the droplet itself is served from; that is its droplet location (droplet.url() from $droplets/drop).

    On the server it comes from the request (a render body’s "host", else Origin), so any client can send any value: render with it, never decide from it who may see what. In the browser it is window.location, read when the droplet mounts. host on the server has where it comes from, how handle can take the full page URL from Referer with hostFrom(), and what the configured host changes; while prerendering, see host at build.

    setHeaders in a server load sets headers on the droplet’s answers, the fragment and _data. Fragments are sent cache-control: private, no-store, no-transform unless the load says otherwise (no-transform stays on whatever it sets), so a droplet that is the same for everyone opens itself to caches here:

    export const load = async ({ props, setHeaders }: LoadEvent) => {
    setHeaders({ "cache-control": "public, max-age=60" });
    return { products: await db.products(props.category) };
    };

    Each header can be set once, and set-cookie is refused. setHeaders in Server code has the rules.

    Props are how a caller parameterizes a droplet: which product, which page. Where they come from depends on the request:

    • A GET (a fragment or _data): the query string, /droplets/hello?who=Ana giving props.who === "Ana". Query values are strings, and a repeated key gives its first value. Without any non-reserved key in the query, the x-droplet-props header, base64-encoded JSON, for props too large or too structured for a URL; else {}.
    • A POST with a JSON body: props of the body, { "props": { … } }, or { "host": "…", "props": { … } } to also say where the droplet renders. The query and x-droplet-props are not read.
    • A form post to an action: the action URL’s query, else x-droplet-props; never the form body.

    The component never receives props directly: they reach it through a load.

    Props are client input, as host is: anyone can send any props. Check them with a schema and never trust them for access; see Request input.

    Limits and reserved names:

    • A malformed x-droplet-props is ignored (with a warning under vite dev); one over 8 KB answers 431.
    • c, t, __cb, noSSR, clientOnly and __droplet_return are reserved query keys, as are a key that starts with / (an action’s name, ?/add) and any __droplet_form_* key: they never become props.

    export const props in +droplet.ts validates props with any Standard Schema library (zod, valibot, arktype…):

    src/droplets/article/+droplet.ts
    import * as z from "zod/mini";
    export const props = z.object({
    page: z._default(z.coerce.number().check(z.int(), z.positive()), 1),
    });
    • It runs before every load: on the server before +droplet.server.ts, in the browser when no server rendered the droplet.
    • Its output replaces the props, so ?page=2 from a URL and { page: 2 } from a POST body meet as the same value.
    • Props it refuses answer 400 before any load runs.
    • It may be async: it can ask a server whether page 2 exists before anything renders.

    The library is yours: Droplets calls the schema’s ~standard.validate and nothing else, and ships no validator of its own. A droplet that loads in the browser carries its schema there, so its size counts.

    The same schema in valibot and arktype

    Each gives { page: number } to the load and to ./$types:

    // valibot
    import * as v from "valibot";
    export const props = v.object({
    page: v.optional(v.pipe(v.unknown(), v.transform(Number), v.integer(), v.minValue(1)), 1),
    });
    // arktype
    import { type } from "arktype";
    export const props = type({
    page: type("string.integer.parse | number.integer").pipe(type("number >= 1")).default(1),
    });
    A JSON Schema as the props schema

    A JSON Schema describes props without checking them; a validator does that. Wrapped once as a Standard Schema, it works like the others:

    src/lib/json-schema.ts
    import { Validator } from "@cfworker/json-schema";
    import type { FromSchema, JSONSchema } from "json-schema-to-ts";
    // The validator applies no `default`, so a defaulted property stays optional.
    type Output<S extends JSONSchema> = FromSchema<S, { keepDefaultedPropertiesOptional: true }>;
    /** Errors that only point at a nested one. */
    const SUMMARIES = new Set(["properties", "false"]);
    /** A JSON Schema as a Standard Schema, the shape `props` in +droplet.ts takes. */
    export function jsonSchema<const S extends JSONSchema>(schema: S) {
    const validator = new Validator(schema as object, "2020-12");
    return {
    "~standard": {
    version: 1 as const,
    vendor: "json-schema",
    validate(value: unknown) {
    const { valid, errors } = validator.validate(value);
    if (valid) return { value: value as Output<S> };
    return {
    issues: errors.filter((e) => !SUMMARIES.has(e.keyword)).map((e) => ({
    message: e.error,
    path: e.instanceLocation.split("/").slice(1),
    })),
    };
    },
    types: undefined as unknown as { input: unknown; output: Output<S> },
    },
    };
    }
    src/droplets/article/+droplet.ts
    import { jsonSchema } from "../../lib/json-schema.ts";
    export const props = jsonSchema({
    type: "object",
    properties: { page: { type: "integer", minimum: 1 } },
    additionalProperties: false,
    });
    • json-schema-to-ts gives ./$types the props’ type ({ page?: number } here).
    • @cfworker/json-schema runs without eval, so it works on Workers and under a strict Content Security Policy; ajv compiles schemas with new Function and does not.
    • A JSON Schema checks values; it does not convert them. ?page=2 arrives as the string "2" and fails type: "integer", and no default is filled in. It fits props that callers send as JSON: a POST body or x-droplet-props.

    Every droplet gets a generated ./$types, typed from its own files. Its component never repeats what the server load returns:

    src/droplets/article/+droplet.server.ts
    import type { LoadEvent } from "./$types";
    // `props.page` is a number: the schema in +droplet.ts says so.
    export const load = async ({ props }: LoadEvent) => ({ page: props.page, items: await list(props.page) });
    src/droplets/article/+droplet.svelte
    <script lang="ts">
    import type { DropletProps } from "./$types";
    let { data }: DropletProps = $props(); // { page: number; items: … }
    </script>
    Type What it is
    Props The caller’s props after the props schema; Record<string, unknown> without one.
    LoadEvent, ServerLoad load in +droplet.server.ts, with Props.
    ServerData What that load returns; undefined without one.
    DropletLoadEvent, Load load in +droplet.ts: Props and ServerData.
    Data What the component gets: the +droplet.ts load’s result, else ServerData.
    DropletProps The component’s props, with the framework’s children and form.
    ActionEvent, Actions actions in +droplet.server.ts, with Props (satisfies Actions).
    DropletActions Each action by name, with what form gets after it (its result or fail() data); {} without actions. For actionUrl<DropletActions>() and the enhance options.
    ActionData What form can be: each action’s result or fail() data, or undefined; just undefined without actions.
    ErrorData, DropletErrorProps The error page’s: what handleError returns.
    DropletScript A script droplet’s default export: (data: Data, el: HTMLElement) => void | (() => void). Only in script droplets’ ./$types.

    Annotate a load’s parameter (({ props }: LoadEvent) => …) or use satisfies ServerLoad, never const load: ServerLoad: an annotation would replace the return type the component’s Data is read from. The same goes for handleError (satisfies HandleDropletError, from $droplets/server).

    Where the files live and how TypeScript finds them:

    • They are written to .droplets/types/, mirroring the droplet folders. .droplets/tsconfig.json maps them next to the droplets with rootDirs: extend it from your tsconfig.json.
    • It also lists, under files, each +droplet.tsx that sits next to a +droplet.ts: TypeScript’s include globs keep only the .ts of two files with the same name, so without it the component would never be checked. Your own files replaces that list, so leave files out of your tsconfig.json.
    • vite dev rewrites them as droplets come and go, vite build writes them too, and djs sync writes them without either, for a type check on a fresh checkout ("prepare": "djs sync").

    Outside a droplet folder (a shared component, say), or before the project has ./$types, each renderer exports the generic form, which you fill in by hand: DropletProps<Data, Form> from @dropletsjs/renderer-svelte (and the other renderers), and LoadEvent from $droplets/server:

    import type { DropletProps } from "@dropletsjs/renderer-svelte";
    type Props = DropletProps<{ who: string }>;

    Every example in these docs uses ./$types.

    A load may return a promise, or an object whose fields are promises:

    export const load = ({ props }: LoadEvent) => ({
    user: db.user(props.id), // a promise
    posts: db.posts(props.id), // another one
    });

    On the server, and when the browser hydrates, those fields are settled before rendering: the component gets plain values, and the inline payload and _data carry them settled. A field that rejects fails the load with that error, so error() and redirect() inside a field still count.

    A droplet mounted in the browser from scratch (client-only, no server markup, a dev remount) mounts at once with data as a promise of what _data and +droplet.ts answer. Read it the framework’s way; the renderer pages have the pattern for each one. Svelte without experimental.async and Handlebars wait for the data instead, so data.x works everywhere.

    A droplet can render content the host page puts inside it. Each renderer hands the component a children value; where it renders, the host page’s content appears:

    <script lang="ts">
    import type { DropletProps } from "./$types";
    let { data, children }: DropletProps = $props();
    </script>
    <section>
    <h2>{data.title}</h2>
    {@render children?.()}
    </section>

    The host page writes its content in one <div data-droplet-slot> inside the element; see Host children for the browser side and the rules.

    Every droplet gets the shared stylesheet (src/app.css by default) and its own: <style> blocks, imported CSS, CSS modules. Both are linked inside the droplet’s element as /droplets/<id>/style.css, and every selector is scoped to the element, so a droplet’s CSS never restyles the host page. Styles belong to the component: CSS reached from +droplet.ts or +droplet.server.ts fails the build. Styling has the details: scoping, theming from the host page, Tailwind, each renderer, and images, fonts and public/.

    Some droplets are no component at all: an analytics tracker, a third-party widget, a vanilla UI. A script droplet is a +droplet.script.ts (or .js) whose default export runs in the browser with the droplet’s data and its element, (data, el) => void | cleanup, with the same loads as any droplet. It is always client only: the server renders nothing for it, it runs as soon as the element connects, it is never prerendered, and a flag it exports warns and is ignored. No renderer is needed: it is built in. Plain script has the details, a live one and an example.

    Every file sits on one side of a line the build enforces. Server code stays on the droplets server; the browser gets the component and what a load returned, never the code that produced it:

    What runs whereOn the droplets server: +droplet.server.ts, hooks.server.ts, +server.ts endpoints, any *.server.* file or server/ folder, and $droplets/env/private, which only the server runs; and the component +droplet.<ext>, +droplet.ts and $droplets/env/public, which the server renders and the browser runs again. Between the server and the browser is a line the build enforces: server code that browser code reaches fails vite build and the vite dev import. What crosses is data: the props and the load's result, as JSON in the fragment. In the browser: the component, +droplet.ts, $droplets/env/public and hooks.client.ts.Droplets server+droplet.server.tshooks.server.ts+server.ts*.server.*server/$droplets/env/private+droplet.<ext>+droplet.ts$droplets/env/publicserver code: the build failsprops and load data,as JSON in the fragmentBrowser+droplet.<ext>+droplet.ts$droplets/env/publichooks.client.tsin both bundles: rendered on the server, run again in the browserWhat runs whereOn the droplets server: +droplet.server.ts, hooks.server.ts, +server.ts endpoints, any *.server.* file or server/ folder, and $droplets/env/private, which only the server runs; and the component +droplet.<ext>, +droplet.ts and $droplets/env/public, which the server renders and the browser runs again. Between the server and the browser is a line the build enforces: server code that browser code reaches fails vite build and the vite dev import. What crosses is data: the props and the load's result, as JSON in the fragment. In the browser: the component, +droplet.ts, $droplets/env/public and hooks.client.ts.Droplets server+droplet.server.tshooks.server.ts+server.ts*.server.*server/$droplets/env/private+droplet.<ext>+droplet.ts$droplets/env/publicserver code:the build failsprops and loaddata, as JSON inthe fragmentBrowser+droplet.<ext>+droplet.ts$droplets/env/publichooks.client.tsin both bundles: rendered on the server, run again inthe browser
    Server code never crosses the line; the props and what a load returns do, as JSON in the fragment.
    • Server files are names with .server. in them, any extension (+droplet.server.ts, hooks.server.ts, db.server.tsx…), +server.* routes, and files under a folder named server/, in any case.
    • Only server files may import $droplets/server and $droplets/env/private.
    • No server file reaches a browser bundle. One that client code reaches, through any import chain, fails vite build and the vite dev import, naming the chain.

    Server-only code has the full rules, Environment variables the secrets.

    $droplets/env exports three booleans, usable anywhere:

    Export true when
    browser running in the browser
    dev running under vite dev
    building vite build is prerendering