Actions
A droplet takes form posts with actions in +droplet.server.ts: a plain
object of functions, default for a form with no name, the others named by
a query key that starts with /.
import { fail, redirect } from "$droplets/server";import type { Actions, LoadEvent } from "./$types";
export const load = async ({ props }: LoadEvent) => ({ entries: await db.entries(props.book) });
export const actions = { // POST /droplets/guestbook?book=1 default: async ({ request, props, cookies }) => { const name = (await request.formData()).get("name"); if (typeof name !== "string" || name === "") return fail(422, { missing: "name" }); await db.sign(props.book, name); cookies.set("signed", "1", { path: "/" }); return { signed: name }; }, // POST /droplets/guestbook?/leave&book=1 leave: () => redirect(303, "/bye"),} satisfies Actions;<script lang="ts"> import { actionUrl } from "$droplets/form"; import type { DropletActions, DropletProps } from "./$types";
let { data, form }: DropletProps = $props(); const sign = actionUrl<DropletActions>(); const leave = actionUrl<DropletActions>("leave");</script>
<form method="post" action={sign}> <input name="name" /> {#if form?.missing}<p>A name, please</p>{/if} {#if form?.signed}<p>Thanks, {form.signed}</p>{/if}</form><form method="post" action={leave}><button>Leave</button></form>The action’s event is a load’s, with full cookies (an action may set
them) and its request with the body unread: the action reads it, as
formData() or otherwise, and checks each field. props come from the
action URL’s query (or x-droplet-props) through the schema, never from
the form; nothing of the body is merged into anything.
What an action returns
Section titled “What an action returns”- A plain JSON object, or nothing: success, status
200. fail(status, data?): a failure with a400–599status (any other throws), and data for the form to show.redirect(), thrown or returned: a303to where it points. The target must be on this server, its droplet location, a trusted origin or the configuredhost; anywhere else answers400(Redirects).error(): answered as a load’serror().
Then the droplet renders again: its load runs, and the component gets the
result as form ({{form.…}} in Handlebars), undefined on any other
render. That render is always live, also for a prerendered droplet.
- The returned data must be plain JSON (object literals, arrays, strings,
finite numbers, booleans,
null): aDate, a class instance or a function answers500. setHeadersis shared with the load that follows: a header both set throws, as two loads would.- In
./$types,Actionstypes the object,DropletActionsmaps each action to whatformgets after it (its result or itsfail()data), andActionDatais whatformcan be: any of them, orundefined.
How the result reaches the page depends on the request, not the URL. An enhanced form asks for JSON and renders the result in place; a form posted without JavaScript is sent back to its page with the result (Post/Redirect/Get). The HTTP contract has every status.
Where a form posts
Section titled “Where a form posts”A droplet renders inside someone else’s page, so <form method="post">
without an action would post to the host page. actionUrl(name?) from
$droplets/form gives the URL of the droplet’s action name (default
without one) on the droplets server. In Handlebars it is
action="{{action "add"}}", action="{{action}}" for default.
import { actionUrl } from "$droplets/form";import type { DropletActions } from "./$types";
actionUrl<DropletActions>("add");// https://drops.example/droplets/cart?/add&productId=p1&__droplet_return=https%3A%2F%2Fshop.example%2Fproduct%2FmugactionUrl("add", { droplet: "cart", props: { productId: "p1" } }); // the same, from anywhere- It is on the droplet location, as for
$droplets/drop: the configuredlocation, else a trusted location header, else the request’s own origin; in the browser, the URL the page loaded/index.jsfrom. An untrusted location never reaches an action URL. - It carries the props that are strings, numbers or booleans, so the action and the render after it get them. Other props do not travel in the URL.
- It ends with the page the form is on, its origin and path, as
__droplet_return: where a form posted without JavaScript is sent back to. That isevent.hoston the server andwindow.locationin the browser, without query or hash. - It is the same string everywhere: on the server, in the browser and in a prerender, so hydration finds the same markup. A prerendered render fills in the location and the page per request.
- With
DropletActionsit takes only the namesactionsexports (and no name only when there is adefault).
actionUrl() knows the droplet that renders now, and throws outside a
render unless given { droplet } (and { props }). In the browser it
knows the render only while the component renders synchronously, so call it
as the component sets up: in a Svelte or Vue script, a Solid body,
useState(() => actionUrl("add")) in React, Preact and Hono JSX (a React
re-render, or a mount after an await, is no longer inside the render), or
pass { droplet, props }.
Without anything else, a form posts as any form does: the browser navigates to the action on the droplets server. That works before the page’s JavaScript runs, or without it, and the answer takes the browser back to the host page.
Without JavaScript: Post/Redirect/Get
Section titled “Without JavaScript: Post/Redirect/Get”With DROPLETS_SECRET set, a form posted
natively (its accept does not prefer JSON, as a browser’s text/html, …
does not) is answered with a 303, never with the droplet’s fragment as a
page of its own:
- success or
fail(): back to the page the form was on, with the result signed in the query:https://shop.example/product/mug?ref=1&__droplet_form_cart_36a187=eyJzd…Q.hT0…. The page loads again, the host page renders the droplet as always, and the droplet renders withform; redirect(): to where it points.
A reload then never posts again. The round trip, for a host page whose
server fetches fragments, with DROPLETS_SECRET set:
The page to go back to comes from __droplet_return in the action URL,
with the page’s own query (?ref=1) when the browser’s Referer is that
same page. It must be on this server (its droplet location included), a
trusted origin or the configured host, and never one of the droplets
routes; else the post answers 400 and its action does not run. The
HTTP contract has how the page
is picked and what the signed value holds.
For the droplet to see the result, its host must be the page’s URL with
its query. The browser sends it with _data on its own; a host page’s
server passes it as "host" in a render request’s body, or as Referer
for a handle that reads it with
hostFrom.
A form in a droplet prerendered for
the configured host returns to the page the render was made for, not the
visitor’s: the path is filled in per request, the query is not (see
A fixed host).
Setup: DROPLETS_SECRET
Section titled “Setup: DROPLETS_SECRET”The result is signed with DROPLETS_SECRET: 32 or more random bytes
(openssl rand -base64 32), read at runtime, the same on every instance
serving a build, kept as a secret. Rotating it voids the results of the
last five minutes and nothing else. Without it, or shorter, a native post
gets the droplet’s fragment rendered with form as its answer, a page of
its own, and vite dev says so once.
Deployment shows how to set it on
each platform.
Enhancing a form
Section titled “Enhancing a form”The demo’s poll, a Vue droplet, has an enhanced form. Its ?/vote action
checks the answer against a Map, fail()s with a code (vote without
picking one) or echoes the vote, and the droplet renders again in place.
It stores nothing.
poll · Vue
The server checks the vote and echoes it back; it keeps nothing.
The post goes from this page to the demo’s origin: the demo lists the
docs’ origin in cors (for the fetch and the _data refresh) and in
trustedOrigins (for the Origin check),
and this page’s Content-Security-Policy allows that origin in
connect-src and form-action. Without JavaScript the vote still posts
and comes back (Post/Redirect/Get),
but this page is static, built once: it cannot render the result its URL
carries, as a host page rendered on each request would.
Opt in per form, and its submit goes by fetch and the result shows in
place. Each renderer’s /form subpath wraps the same
enhanceDropletForm(form, options?) of $droplets/form:
<!-- Svelte: an action --><script lang="ts"> import { actionUrl } from "$droplets/form"; import { enhanceDropletForm } from "@dropletsjs/renderer-svelte/form"; import type { DropletActions } from "./$types";
const add = actionUrl<DropletActions>("add");</script>
<form method="post" action={add} use:enhanceDropletForm={{ action: "add" }}>…</form>// React (and Preact or Hono JSX, from @dropletsjs/renderer-preact/form or// @dropletsjs/renderer-hono-jsx/form, with their own hooks)import { useRef, useState } from "react";import { actionUrl } from "$droplets/form";import { useEnhanceDropletForm } from "@dropletsjs/renderer-react/form";import type { DropletActions } from "./$types";
export default function Cart() { const [add] = useState(() => actionUrl<DropletActions>("add")); const ref = useRef<HTMLFormElement>(null); useEnhanceDropletForm<DropletActions>(ref, { action: "add" }); return <form method="post" action={add} ref={ref}>…</form>;}<!-- Vue: a composable --><script setup lang="ts">import { ref } from "vue";import { actionUrl } from "$droplets/form";import { useEnhanceDropletForm } from "@dropletsjs/renderer-vue/form";import type { DropletActions } from "./$types";
const add = actionUrl<DropletActions>("add");const form = ref<HTMLFormElement | null>(null);useEnhanceDropletForm<DropletActions>(form, { action: "add" });</script>
<template><form ref="form" method="post" :action="add">…</form></template>// Solid: a directiveimport { actionUrl } from "$droplets/form";import { enhanceDropletForm } from "@dropletsjs/renderer-solid/form";import type { DropletActions } from "./$types";
void enhanceDropletForm; // `use:` needs it in scope
export default function Cart() { const add = actionUrl<DropletActions>("add"); return <form method="post" action={add} use:enhanceDropletForm={{ action: "add" }}>…</form>;}{{!-- Handlebars: an attribute, bound by /index.js --}}<form method="post" action="{{action "add"}}" data-droplet-enhance>…</form>What an enhanced form takes over:
- Only a
POSTto its own droplet’s action: exactly<location>/droplets/<id>by origin and path, the hosting element’s. Withaction, only that action. - Everything else stays the browser’s: a submit elsewhere (another
droplet, the host page, another origin, a
javascript:formaction), aGET, atext/plainform, or one with atargetother than_self. - What it sends:
new FormData(form, submitter)(the submitter’sformactionandformenctypecount) withaccept: application/json.
Then:
- success or failure: the droplet renders again with
formand fresh data, its loads run as a_datarefresh. Ahydrate = falsedroplet (Handlebars, or any that does not render in the browser) gets its fragment, rendered withformby the server (a JSON render that carriesform), swapped in. Its props and page come from the form’s action URL, as for a form posted without JavaScript: the propsactionUrl()wrote in its query (strings, numbers and booleans, read back as strings) and the page in__droplet_return. Either way focus goes back to the control in the same place; - redirect: the page goes there (
location.assign), to the absolutehttp:orhttps:URL the server answers, already checked against its own origins andtrustedOrigins; a relative, protocol-relative (//…),javascript:or credentialed location is never followed; droplets:actionis dispatched onwindow, with{ droplet, action, type, status, data }, for the rest of the page;- an answer that is no result (an
error(), a network failure) is logged and applies nothing.
The rest of the page listens for the event:
addEventListener("droplets:action", (event) => { const { droplet, action, type, status, data } = event.detail; if (droplet === "product-card" && action === "add" && type === "success") refreshCart();});data is a copy of what the action returned or fail()ed with, as plain
JSON; undefined for a redirect. A second submit while one is in flight is
ignored. A form among the host page’s
children, or in a nested droplet,
belongs to them, not to the droplet around it. The options:
useEnhanceDropletForm<DropletActions>(ref, { action: "add", // Before anything is sent: change formData, or cancel(). onSubmit: ({ form, formData, cancel }) => {}, // In place of the default: data is typed by the action. onResult: async ({ type, status, data, update }) => { if (type === "success") showCart(data); else await update(); },});The default update renders the component again, so state the component
keeps for itself starts over; onResult can apply the result without it.
enhanceDropletForm(form, options) itself returns the function that
removes it, for a form outside these wrappers.
Limits you will hit
Section titled “Limits you will hit”A form posted without JavaScript carries its result in the page’s URL. That shapes what an action should return:
-
2 KB at most. A result over 2 KB keeps
statusandactionand dropsdata, with a warning undervite dev:formis thenundefined. Return field names and short messages, not documents. -
Readable by anyone who holds the URL. The secret signs the result; it does not hide it. The JSON is base64url, readable without the secret, and it rides in the URL: in history, logs and
Referers. Return field names and message codes, never the submitted values, secrets or anything used for authorization:// Bad: the address, the reason and a session id, readable by anyone with the URL.return fail(422, { email, error: `No account for ${email}`, session: locals.sessionId });// Good: which field, and a code the component turns into a message.return fail(422, { field: "email", code: "unknown_account" }); -
Display only. Anyone who posts the form can make a URL that shows its result to someone else for five minutes, and a result minted for one page shows on that page only. Never use
formto decide what someone may do. -
It shows again on reload. For five minutes a no-JavaScript user who reloads the page (or goes back to it) sees the result again: it is in the URL. Do not hang one-shot effects on
form(a toast that counts, an analytics event, “clear the cart now”): what must happen once happens in the action. -
Every instance shows it. Repeated instances of one droplet on a page all render with the result.
-
No posts from a
no-referrerpage. UnderReferrer-Policy: no-referrerthe browser sendsOrigin: nullwith a form post, which theOrigincheck answers403, even with the droplets routes proxied under the host page’s own origin. Give the page<meta name="referrer" content="strict-origin-when-cross-origin">(or that header), the browsers’ default:__droplet_returnthen carries the path.
Form actions without JavaScript in the Security model lists the signed value’s properties.