Skip to content

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 /.

src/droplets/guestbook/+droplet.server.ts
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;
src/droplets/guestbook/+droplet.svelte
<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.

  • A plain JSON object, or nothing: success, status 200.
  • fail(status, data?): a failure with a 400–599 status (any other throws), and data for the form to show.
  • redirect(), thrown or returned: a 303 to where it points. The target must be on this server, its droplet location, a trusted origin or the configured host; anywhere else answers 400 (Redirects).
  • error(): answered as a load’s error().

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): a Date, a class instance or a function answers 500.
  • setHeaders is shared with the load that follows: a header both set throws, as two loads would.
  • In ./$types, Actions types the object, DropletActions maps each action to what form gets after it (its result or its fail() data), and ActionData is what form can be: any of them, or undefined.

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.

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%2Fmug
actionUrl("add", { droplet: "cart", props: { productId: "p1" } }); // the same, from anywhere
  • It is on the droplet location, as for $droplets/drop: the configured location, else a trusted location header, else the request’s own origin; in the browser, the URL the page loaded /index.js from. 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 is event.host on the server and window.location in 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 DropletActions it takes only the names actions exports (and no name only when there is a default).

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.

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 with form;
  • 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:

A form action, Post/Redirect/GetWithout JavaScript: one, the browser posts the form to the droplets server at /droplets/cart?/add, with __droplet_return naming the page. The droplets server checks the Origin and runs the action. Two, it answers 303 back to the host page, the result signed with DROPLETS_SECRET in a __droplet_form_cart_<build> query key, valid five minutes. Three, the browser loads the page again, with that query. Four, the host fetches the droplet with the page's URL and query as host. The droplets server verifies the signature and renders with the result as form. Five, it answers the fragment. Six, the page shows the result; a reload never posts again.BrowserHostDroplets server① POST /droplets/cart?/add__droplet_return: the pageOrigin check, the actionruns② 303 to the page, the result signed in?__droplet_form_cart_<build>=…③ GET the page, with that query④ GET /droplets/carthost: the page's URLverifies it, renders withform⑤ the fragment⑥ the page, result shownA form action, Post/Redirect/GetWithout JavaScript: one, the browser posts the form to the droplets server at /droplets/cart?/add, with __droplet_return naming the page. The droplets server checks the Origin and runs the action. Two, it answers 303 back to the host page, the result signed with DROPLETS_SECRET in a __droplet_form_cart_<build> query key, valid five minutes. Three, the browser loads the page again, with that query. Four, the host fetches the droplet with the page's URL and query as host. The droplets server verifies the signature and renders with the result as form. Five, it answers the fragment. Six, the page shows the result; a reload never posts again.BrowserHostDroplets server① POST /droplets/cart?/add__droplet_return: the pageOrigin check,the actionruns② 303 to the page, the result signed in?__droplet_form_cart_<build>=…③ GET the page, with that query④ GET /droplets/carthost: the page's URLverifies it,renders withform⑤ the fragment⑥ the page, result shown
Posted without JavaScript, the form lands back on the host page, its result signed in the URL.

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

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.

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

Which framework would you write your next droplet in?

The server checks the vote and echoes it back; it keeps nothing.

This is a live droplet served by apps/demo: the vote posts to its server, from this page's origin.

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 directive
import { 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 POST to its own droplet’s action: exactly <location>/droplets/<id> by origin and path, the hosting element’s. With action, only that action.
  • Everything else stays the browser’s: a submit elsewhere (another droplet, the host page, another origin, a javascript: formaction), a GET, a text/plain form, or one with a target other than _self.
  • What it sends: new FormData(form, submitter) (the submitter’s formaction and formenctype count) with accept: application/json.

Then:

  • success or failure: the droplet renders again with form and fresh data, its loads run as a _data refresh. A hydrate = false droplet (Handlebars, or any that does not render in the browser) gets its fragment, rendered with form by the server (a JSON render that carries form), swapped in. Its props and page come from the form’s action URL, as for a form posted without JavaScript: the props actionUrl() 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 absolute http: or https: URL the server answers, already checked against its own origins and trustedOrigins; a relative, protocol-relative (//…), javascript: or credentialed location is never followed;
  • droplets:action is dispatched on window, 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.

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 status and action and drops data, with a warning under vite dev: form is then undefined. 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 form to 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-referrer page. Under Referrer-Policy: no-referrer the browser sends Origin: null with a form post, which the Origin check answers 403, 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_return then carries the path.

Form actions without JavaScript in the Security model lists the signed value’s properties.