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.
Structure
Section titled “Structure”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 frameworkdjs 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 devandvite buildskip it and warn once, listing such folders. No id is reserved. - The component’s extension picks the renderer that
builds it.
+Droplet.vuewith a capital D works too. One component per folder: a+droplet.sveltenext to a+droplet.vueis 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 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.
Opens when the tab does.
Opens when the tab does.
Opens when the tab does.
Opens when the tab does.
The element above is all there is: the fragment the server answers, with no markup in it and no script to fill it.
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.ssrandprerendertaketrueorfalse;hydratetakestrue,false,"visible"or"interactive". - Anything else keeps the default, with a warning under
vite devandvite build: another value, or another form (export const ssr = !dev,export let,export { x as ssr }). A commented-out// export const ssr = falseor a flag inside a string is no flag. - Only the component counts. An
ssr,hydrateorprerenderexported from+droplet.tsor+droplet.server.tschanges 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.
The load chain
Section titled “The load chain”+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> dataThe 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.
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.
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.
When a load stops
Section titled “When a load stops”error(status, message)from$droplets/serverstops 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 againsthost.- The target must be on this server, its droplet location, a
trusted origin or the configured
host. Any other target answers400(Bad Request: the droplet redirects off this site), with a line in the server log. - The element never follows a redirect. When the
_datarequest it sends is answered with one, it logs<id>: _data answered opaqueredirectand 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
Section titled “setHeaders”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=Anagivingprops.who === "Ana". Query values are strings, and a repeated key gives its first value. Without any non-reserved key in the query, thex-droplet-propsheader, base64-encoded JSON, for props too large or too structured for a URL; else{}. - A
POSTwith a JSON body:propsof the body,{ "props": { … } }, or{ "host": "…", "props": { … } }to also say where the droplet renders. The query andx-droplet-propsare 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-propsis ignored (with a warning undervite dev); one over 8 KB answers431. c,t,__cb,noSSR,clientOnlyand__droplet_returnare reserved query keys, as are a key that starts with/(an action’s name,?/add) and any__droplet_form_*key: they never become props.
A props schema
Section titled “A props schema”export const props in +droplet.ts validates props with any
Standard Schema library (zod, valibot,
arktype…):
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=2from a URL and{ page: 2 }from a POST body meet as the same value. - Props it refuses answer
400before 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:
// valibotimport * 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),});// arktypeimport { 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:
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> }, }, };}import { jsonSchema } from "../../lib/json-schema.ts";
export const props = jsonSchema({ type: "object", properties: { page: { type: "integer", minimum: 1 } }, additionalProperties: false,});json-schema-to-tsgives./$typesthe props’ type ({ page?: number }here).@cfworker/json-schemaruns withouteval, so it works on Workers and under a strict Content Security Policy;ajvcompiles schemas withnew Functionand does not.- A JSON Schema checks values; it does not convert them.
?page=2arrives as the string"2"and failstype: "integer", and nodefaultis filled in. It fits props that callers send as JSON: a POST body orx-droplet-props.
Types: ./$types
Section titled “Types: ./$types”Every droplet gets a generated ./$types, typed from its own files. Its
component never repeats what the server load returns:
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) });<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.jsonmaps them next to the droplets withrootDirs: extend it from yourtsconfig.json. - It also lists, under
files, each+droplet.tsxthat sits next to a+droplet.ts: TypeScript’sincludeglobs keep only the.tsof two files with the same name, so without it the component would never be checked. Your ownfilesreplaces that list, so leavefilesout of yourtsconfig.json. vite devrewrites them as droplets come and go,vite buildwrites them too, anddjs syncwrites 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.
Data may be a promise
Section titled “Data may be a promise”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.
Children
Section titled “Children”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.
Styles
Section titled “Styles”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/.
Script droplets
Section titled “Script droplets”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.
Where code runs
Section titled “Where code runs”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:
- 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 namedserver/, in any case. - Only server files may import
$droplets/serverand$droplets/env/private. - No server file reaches a browser bundle. One that client code
reaches, through any import chain, fails
vite buildand thevite devimport, 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 |