Server code
Server code in Droplets follows SvelteKit’s conventions. It never sees Hono:
everything is a web-standard Request in and Response out, so the same code
runs on Node and on Workers.
src/hooks.server.ts
Section titled “src/hooks.server.ts”Runs on the server, per request. Its browser counterpart,
src/hooks.client.ts, runs once
per page before any droplet starts.
handle
Section titled “handle”Runs for every request except the health check and the files: fill
event.locals, answer early without calling resolve, or change the
response. A redirect() thrown here is resolved against event.host and
answered only on the server’s own origin, its location’s, a
trustedOrigins entry or host of the config, the bound every redirect a
droplet answers passes (Security); any
other target answers 400.
/index.js, /index.css, /env.js and every path under /assets/ (the bundles’ chunks,
stylesheets, imported files and public/ at /assets/public/) are answered
without calling handle, on every adapter and in vite dev, as SvelteKit
serves its static files. Fragments, _data, actions and /api/* all run
through it. /droplets/<id>/client.js and style.css do on Node, Bun and
Deno; on Cloudflare they are files of the build that the static assets
answer before the Worker runs. So handle cannot guard a file: everything
under /assets/ is public to whoever has its URL. A file
only some users may see belongs behind an endpoint that checks who asks, in
src/api/, or on a storage service that hands out signed URLs, and the
droplet links to that.
import type { Handle } from "$droplets/server";
declare module "@dropletsjs/droplets/server" { interface Locals { requestId: string; user: { id: string } | null; }}
export const handle: Handle = async ({ event, resolve }) => { event.locals.requestId = crypto.randomUUID().slice(0, 8); event.locals.user = await readSession(event.cookies.get("session"));
const response = await resolve(event); response.headers.set("x-request-id", event.locals.requestId); return response;};Whatever lands in event.locals reaches droplet server loads and +server.ts
handlers. locals are never serialized into a fragment. sequence(a, b, c)
from $droplets/server chains several handle functions.
The event:
type RequestEvent = { request: Request; url: URL; // the request's path and query under the public location, prefix included host: URL; // where the droplet renders: the host page; handle may replace it params: Record<string, string>; // API route parameters locals: Locals; platform: { env?: unknown; context?: unknown }; cookies: Cookies; // see Cookies below fetch: typeof fetch; // see event.fetch below};On Workers platform.env holds the bindings (KV, D1, R2…) and
platform.context the execution context.
handleError
Section titled “handleError”The last stop for unexpected errors leaving the server: handle,
+server.ts, the import map, a droplet that cannot show its error page. Log
the error and choose the message the answer carries; returning nothing keeps
“Internal Server Error”.
import type { HandleServerError } from "$droplets/server";
export const handleError: HandleServerError = ({ error, event, status, message }) => { report(error, event.url); return { message: "Something broke; we are on it." };};Errors inside a droplet’s loads go to the droplet’s own handleError first;
see Errors.
event.host is the page a droplet renders on, the host page, as a URL.
handle, a droplet’s loads, transform and its actions get it. It is not
where the droplet itself is served from: that is the droplet
location
(x-droplet-location on the server, the URL /index.js came from in the
browser, droplet.url() from $droplets/drop). The fragment’s own URL is
request.url.
Where it comes from
Section titled “Where it comes from”On the server, first match wins:
hostin a render request’s JSON body:{ "host": "https://shop.example/product/mug", "props": { … } };Origin;- the origin of the droplet location.
- Only
http:andhttps:URLs count; a value that is not one is skipped for the next source. Origincarries an origin only, so the path is/unless the body gave one.- With
trustedOriginsset, a host page outside it (and not this server) becomes the droplet location’s origin. - With
hostindroplets.config.ts,event.hostis that origin, with the body’s path and query when the body names a page on it;Originis not read.
Taking the page from Referer
Section titled “Taking the page from Referer”handle in src/hooks.server.ts sees event.host first and may replace
it; loads, transform and the context sent to the browser get what
handle left. A host page’s server that sends the page’s URL as Referer
(or X-Forwarded-Uri) gives the droplet the full path too:
import { hostFrom, type Handle } from "$droplets/server";
export const handle: Handle = ({ event, resolve }) => { event.host = hostFrom(event.request.headers.get("referer")) ?? event.host; return resolve(event);};hostFrom checks a candidate the way the default is checked: an http: or
https: URL without credentials or hash, and, with trustedOrigins set,
one of them or this server. Anything else, a missing or malformed header
included, gives null. handle may still set any URL it likes;
hostFrom is the safe way to take one from a request.
In the browser
Section titled “In the browser”The universal load’s host is the page itself (window.location, without
its #hash), read when the droplet mounts. It does not follow a
single-page app’s navigation afterwards. A universal load that renders from
host.pathname hydrates cleanly only when the server got the same path.
While prerendering, see host at build.
Never for access
Section titled “Never for access”host comes from the request: any client can send any value. Render with
it; never decide from it who may see what. Embedding a droplet also tells
its server the page’s URL; see Who sees what.
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:
import type { LoadEvent } from "$droplets/server";
export const load = async ({ props, setHeaders }: LoadEvent) => { setHeaders({ "cache-control": "public, max-age=60" }); return { products: await db.products(props.category) };};- Each header once. As in SvelteKit,
setHeadersthrows when a header is set a second time. An action shares it with the load that renders after it. - Plain strings, no cookies. Names and values are strings without line
breaks, and
set-cookieis refused: cookies are set inhandle,+server.tsor an action. - Only on what rendered. The headers go out when the droplet renders or loads; an error answer, or a load that failed and shows its error page, carries none of them.
- Prerendered renders keep theirs. A render made at build is served with the headers its load set at build.
handlehas the last word. It sees the response after and may change any of them. Avarythe load sets is kept, and the headers the location andhostcome from are added to it.transformand the universal load have nosetHeaders.
Cookies
Section titled “Cookies”event.cookies works as in SvelteKit, on the event of handle and
+server.ts handlers. A droplet’s server load and transform get cookies to
read only (get and getAll, the ReadonlyCookies type): a droplet renders
as a host page’s server asked for it, and what it set would reach the
browser only if that server passed it on. cookies.set() and cookies.delete() throw there; set
cookies in handle or +server.ts.
import { timingSafeEqual } from "node:crypto";import { error, json, type RequestHandler } from "$droplets/server";import { env } from "$droplets/env/private";
const same = (a: string, b: string) => { const [x, y] = [Buffer.from(a), Buffer.from(b)]; return x.length === y.length && timingSafeEqual(x, y);};
export const POST: RequestHandler = async ({ request, cookies }) => { const expected = env.ADMIN_PASSWORD; // declared in src/env.ts: ADMIN_PASSWORD: {} const form = await request.formData(); if (!expected || !same(String(form.get("password") ?? ""), expected)) error(401, "Wrong password"); cookies.set("session", await sign("admin"), { path: "/", maxAge: 60 * 60 * 8 }); return json({ ok: true });};ADMIN_PASSWORD is declared in src/env.ts (see
Environment variables); a runtime variable may be
unset, so the handler refuses everyone without it. Compare secrets in
constant time (timingSafeEqual on Node, Bun and Deno;
crypto.subtle.timingSafeEqual on Workers), and store a hash, not the
password, in anything real.
| Method | Does |
|---|---|
get(name, { decode? }) |
The value, or undefined. Sees what this request set or deleted. |
getAll({ decode? }) |
[{ name, value }], the request’s and this request’s own. |
set(name, value, options) |
Records a Set-Cookie for the response. |
delete(name, options) |
Expires it (Max-Age=0); path and domain must match the ones it was set with. |
serialize(name, value, options) |
The Set-Cookie value, for a response you build yourself. |
options.path is required, and absolute ("/", "/admin"): the response
may reach the browser through a host page’s server, under its URLs. Defaults:
httpOnly: true, sameSite: "lax", and secure: true except over plain
HTTP to localhost or a loopback address (the dev server), judged by the
server’s public location.
sameSite: "none" without secure: true throws: browsers drop such a
cookie. Values are encodeURIComponented unless you pass encode. Setting
the same name, domain and path twice sends the last one.
Whatever answers the request carries the cookies: the fragment, _data,
the endpoint’s response (even one with immutable headers, such as
Response.redirect()), an error() or redirect(), or a response handle
returns without resolving. A fragment the host page’s server fetches hands its
Set-Cookie to that server; see
Cookies in the Security model for how cookies
reach the browser (same origin, or a host page’s server that forwards them, never their
Domain).
Cookies do not exist at build: using them while prerendering throws
CookiesInPrerenderError and stops the build, as reading
host beyond its tokens does.
handle runs for build-time renders too, so skip cookies there when
building from $droplets/env is true.
event.fetch
Section titled “event.fetch”Every server event (handle, +server.ts handlers, a droplet’s server
load, transform and form actions) carries fetch, as SvelteKit’s
does. A URL on this server is answered in-process, with no network hop;
any other URL goes to the global fetch. entries runs before any
request and has no event.
import type { LoadEvent } from "./$types";
export const load = async ({ fetch }: LoadEvent) => { const res = await fetch("/api/testimonials?max=10&random=true"); return { testimonials: await res.json() };};Which URLs are this server’s
Section titled “Which URLs are this server’s”A URL is answered in-process when it is:
- relative, resolved against
request.url, the request as the server received it:/api/xis the route/api/xwhatever prefix a proxy adds; - absolute on the request’s own origin;
- absolute under the droplet
location,
prefix included: with the server at
https://shop.example/mfe,https://shop.example/mfe/api/xis/api/x, whilehttps://shop.example/otheris another site and goes to the network.
Such a request is dispatched into the app as a request of its own, exactly
as one from outside: the location is resolved again, the Origin check and
the body limits apply, handle runs (with locals of its own), and the
route is matched. /api/*, the /droplets/* routes and the files the app
serves all answer this way; a path no route matches answers 404 from the
app, never from the network.
Being internal grants nothing: a location header on it is trusted only
against trustedOrigins, a redirect() it answers passes the same bound,
and a form token is checked the same way.
What it carries
Section titled “What it carries”From the request it runs for, each unless init sets that header itself:
cookieandauthorization, except withcredentials: "omit";- the headers the location and
hostcome from:x-droplet-location,Forwarded,X-Forwarded-Host,X-Forwarded-Proto,X-Forwarded-Port,X-Forwarded-PrefixandOrigin. The internal request resolves the same location andhost, and a form post passes theOrigincheck when the outer request did. One made from a request without anOriginsetsheaders: { origin: event.url.origin }.
Nothing else of the incoming request: not its body, not any other header.
A request to another origin gets only what init says, never the
incoming cookies or authorization, nor any header you did not set.
Limits
Section titled “Limits”- Cookies stay on the answer. A
Set-Cookiean internal answer carries stays on thatResponse(response.headers.getSetCookie()); it does not reach the outer response, for the reason a load cannot set cookies: a droplet’s answer may be fetched by a host page’s server. Set it yourself where cookies can be set. - Four levels deep. A request that fetches itself, directly or through
other routes, stops at four nested internal requests: the fifth throws an
Errornaming the URL, which the outermost request answers as500throughhandleError. Call the code a route runs rather than the route when the two are in the same server. - At build. While prerendering there is no incoming request: an
internal request carries no cookies, and an endpoint that reads
cookiesanswers the build’s500(CookiesInPrerenderErrorin its body) rather than stopping the build;handleruns for it as for any build-time render. A fetch to another origin at build goes to the network and its result is stored with the render. vite devbehaves exactly as a built server does.
API routes
Section titled “API routes”+server.ts files under src/api (the apiFolder option) answer under
/api/:
src/api/ health-report/+server.ts → /api/health-report greet/[name]/+server.ts → /api/greet/Ana files/[...path]/+server.ts → /api/files/a/b/c (admin)/users/+server.ts → /api/users (a group: not in the URL)import { error, json, type RequestHandler } from "$droplets/server";
export const GET: RequestHandler<{ name: string }> = ({ params, locals }) => { if (params.name.length > 40) error(400, "That name is too long."); return json({ greeting: `Hello ${params.name}!`, requestId: locals.requestId });};Export one function per method (GET, POST, PUT, PATCH, DELETE,
OPTIONS, HEAD), or fallback for every method the module does not
export, a non-standard one included, as in SvelteKit. HEAD without its
own export runs GET and drops the body. A method with neither its own
export nor fallback answers 405 with Allow listing the exported
methods (omitted when there is none). An export of any other name
(CONFIG, say) is never called as a method. A path no route matches
answers 404 { "message": "Not Found" }, and a handler that returns no
Response a 500.
A folder in brackets is a parameter ([name]) or the rest of the path
([...path]), and one in parentheses ((admin)) adds nothing to the URL.
A parameter’s value is the path segment percent-decoded, %2F included:
/api/greet/a%2Fb gives params.name === "a/b", one segment still, and
[...path] joins its decoded segments with /. Treat a parameter as the
input it is: check its length and shape before it names anything.
Any other bracket form ([[optional]], matchers), a repeated parameter
name, a segment after [...rest], or two routes of the same shape
(a/[id] and a/[slug]) fail vite dev and vite build. Routes are
matched most specific first. +server.ts and +server.js are the only
names read.
$droplets/server provides json(), text(), error(), redirect(),
fail(), sequence(), hostFrom() and the event types; the full list is
in the API reference.
A redirect() from a handler is resolved against event.url, the
request’s URL on the droplet location. It is answered only when its target
is on this server, its location, a
trusted origin or the configured
host; any other answers 400
{ "message": "Bad Request: the endpoint redirects off this site" }
(Redirects).
Calling a route from a droplet
Section titled “Calling a route from a droplet”A droplet runs inside someone else’s page, so a relative fetch("/api/…")
in the browser reaches the host page’s server, not yours. $droplets/drop
knows the droplet location, in the browser and during server rendering:
// src/lib/api.ts: neutral, any droplet in any framework can import itimport droplet from "$droplets/drop";
export async function bumpCounter(by = 1): Promise<number> { const response = await fetch(droplet.url("/api/counter"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ by }), }); return (await response.json()).count;}droplet.url()joins the path todroplet.origin, the droplet location with its path prefix: in the browser the URL/index.jswas loaded from, on the server the request’s location.- Cross-origin calls need
corson the droplets server, as the bundles do. - Send JSON with its content type. A cross-site
POSTwith a string body and no content type goes out astext/plain, which theOrigincheck answers403unless the page’s origin is trusted. - A host page that proxies the droplets server under its own origin proxies
/api/*too. - In a server load, use
event.fetchinstead: it answers this server’s routes in-process.
See $droplets/drop.
Environment variables
Section titled “Environment variables”Declare every variable once, in src/env.ts:
import { defineEnvVars } from "@dropletsjs/droplets/env";
export const variables = defineEnvVars({ API_TOKEN: {}, // private, read at runtime FEATURE_X: { static: true }, // private, inlined at build PUBLIC_BANNER: { public: true }, // reaches the browser, read at runtime PUBLIC_SITE_NAME: { public: true, static: true }, // reaches the browser, inlined at build});
declare module "@dropletsjs/droplets/env" { interface Register { variables: typeof variables; }}Then read them, typed:
import { env } from "$droplets/env/private"; // server code onlyimport { env } from "$droplets/env/public"; // anywhereLike SvelteKit, a variable is private and dynamic unless it says otherwise:
| Declaration | Reaches | Value from |
|---|---|---|
{} |
the server | its environment, per request |
{ static: true } |
the server | the build, inlined |
{ public: true } |
server and browser | the server’s environment at runtime |
{ public: true, static: true } |
server and browser | the build, inlined into every bundle |
- Runtime values come from
.envfiles in dev and while prerendering, the process environment on Node, Bun and Deno, and the bindings on Workers (.envfiles are a build input only there). - A static variable without a value fails
vite build, and only warns undervite dev. - A dynamic public variable changes with a restart, not a rebuild. The server
answers
/env.jswith the current values, keyed by element name and build, and/index.jsimports it before the entry, so the browser has them beforeinit()runs and any droplet mounts; they never appear in a droplet bundle./env.jsis sent withcache-control: public, max-age=600: a page picks up a new value within ten minutes.DROPLETS_ENV_MAX_AGEsets the seconds (read at runtime,0sendsno-store); an invalid value keeps600, with a warning undervite dev. Only{ public: true }variables withoutstaticare in it, and the route reads nothing from the request. Without such a variable,/env.jsanswers404and/index.jsdoes not import it. $droplets/env/privateand$droplets/servercan only be imported from server files (*.server.*names,+server.*routes, files under aserver/folder).- Server files themselves never reach the browser: a
*.server.*file (db.server.ts,+droplet.server.ts), a+server.*route or anything under aserver/folder (src/lib/server/db.ts) that client code reaches, directly or through other modules, fails the build and is refused by the dev server, with the import chain in the message. Case does not matter:src/lib/Server/db.tsanddb.SERVER.tsare server files too, and so is one reached as a file (new URL(…, import.meta.url), a CSSurl(), a?urlor?rawimport): inlined or emitted, it fails the build, and the dev server answers 403 when the browser fetches it. Keep connection strings and keys in those files and read them from+droplet.server.ts; a universal+droplet.tsruns in the browser and cannot import them. - Never return a private value from a load: load results are inlined into the page. See Server-only code.
Import maps
Section titled “Import maps”A large library several droplets use can stay out of every droplet bundle and
load once from an import map: declared external in the Vite config, mapped
per request in src/importmap.server.ts, and included by the host page
through /importmap or /importmap.js before /index.js. See
Shared libraries (import maps).