Svelte logo

SvelteKit by Example: Form Actions

Form actions provide server endpoint for form submissions in SvelteKit. Since actions are called by submitting forms, actions progressively enhance te user experience as they'll still run when JavaScript is disabled.

In this example, we'll set up a form action to create a simple subscription form.

Actions are exported from the +page.server.js file. Actions have access to the form data passed through the request.

Actions can be called through forms in Svelte components. When calling the the default action of a page, an action attribute is not required.

src/routes/newsletter/+page.server.js
export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const data = { email: formData.get('email') };

    await fetch('https://mailcoach.app/api/…', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },
};
src/routes/newsletter/+page.svelte
<form method="POST">
  <label>Email</label>
  <input type="email">
</form>

Actions can be named to support multiple actions from the same endpoint.

To call a named action, specify it in the query string of the form's action URL.

src/routes/newsletter/+page.server.js
export const actions = {
  subscribe: async ({ request }) => {
    // …
  },
  unsubscribe: async ({ request }) => {
    // …
  },
};
src/routes/newsletter/+page.svelte
<form method="POST" action="?/subscribe">
  <!-- … -->
</form>