| | |

Svelte 62 ๐Ÿงก Named Form Actions and Multi-Form Handling on a Single Page

โฑ๏ธ Estimated read: 8 min | |

In many real-world applications, a single page acts as a hub for multiple operations. For example, a “User Settings” page might contain distinct forms to update a profile name, change a password, and manage notification preferences. SvelteKitโ€™s form actions system handles this via “Named Actions.” By allowing you to define multiple discrete functions within the actions object of your +page.server.ts, SvelteKit eliminates the need to create separate API endpoints or manage complex state for different submission types.

This chapter explores how to define and trigger named actions, how to differentiate between multiple form responses in your frontend, and the best practices for structuring forms so that your server-side logic remains modular and scalable. You will learn how the form propโ€”automatically provided to your page componentsโ€”can be used to handle specific validation results even when multiple actions exist on the same route.

Key point: Named actions allow you to host multiple distinct server-side handlers in a single +page.server.ts file; you trigger them by appending ?/actionName to the form’s action attribute, and SvelteKit routes the request to the specific function, returning the result to the page’s form prop.


Why exists

The Endpoint Explosion Problem. Without named actions, every form would require its own separate route (e.g., /api/update-name, /api/update-password). Named actions exist to keep the directory tree clean by keeping related submission logic colocated with the page that consumes it.

The State Separation Problem. Handling multiple forms often leads to conflicting validation state. Named actions exist to provide distinct return objects, allowing the page to differentiate which form succeeded or failed without complex conditional logic on the client.

The Modularity Problem. Developers often need to handle different business logicโ€”like updating a database versus sending an emailโ€”within the same user workflow. Named actions exist to isolate these logic blocks, ensuring that an error in one action doesn’t interfere with the logic of another.

The Progressive Enhancement Problem. Because named actions rely on standard HTML POST requests, they maintain support for progressive enhancement. Named actions exist to allow the server to distinguish intents even when JavaScript is disabled, by simply looking at the URL’s query segment.

The Context Management Problem. Forms on the same page often need the same locals or params context. Named actions exist to share the context of the page request while providing different handling paths based on the form being submitted.


a. Defining the Actions Object

The actions export in +page.server.ts is an object where keys are the action names and values are the functions. The default key is a special caseโ€”it is triggered if no name is specified. All other keys act as named actions that can be addressed directly from your templates.

// src/routes/settings/+page.server.ts
export const actions = {
  updateProfile: async ({ request }) => {
    // Logic for updating profile
  },
  changePassword: async ({ request }) => {
    // Logic for changing password
  }
};

Each function receives the RequestEvent, just like a standard action. This means you have access to request, locals, params, and cookies. Because these are independent functions, you can import different services or repository methods for each, keeping your +page.server.ts tidy and performant.


b. Triggering via Action Attributes

To target a specific action, you use the action attribute on your HTML form. SvelteKit parses the ?/ syntax to route the request to the corresponding key in your actions object. This is a native browser capability that works even if the SvelteKit runtime has not finished loading.

<!-- src/routes/settings/+page.svelte -->
<form method="POST" action="?/updateProfile" use:enhance>
  <input name="username" />
  <button>Save Name</button>
</form>

<form method="POST" action="?/changePassword" use:enhance>
  <input type="password" name="password" />
  <button>Change Password</button>
</form>

When either form is submitted, the request is sent to the current page URL with the action name appended as a query parameter. The server handles the request, executes only the targeted function, and redirects or returns data to the form prop, which is specific to that submission event.


c. Error Handling and the form Prop

When an action returns data (e.g., return { success: true } or return fail(400, { error: 'Invalid' })), this result is available in the form prop of your +page.svelte. When multiple forms exist, the form prop contains the result of the most recent submission.

<!-- src/routes/settings/+page.svelte -->
<script>
  let { form } = $props();
</script>

{#if form?.success}
  <p>Action completed successfully!</p>
{:else if form?.error}
  <p>Error: {form.error}</p>
{/if}

If you need to handle multiple forms and maintain independent UI states for each, it is best to use distinct validation keys in your return objects (e.g., return { profileError: '...' } vs return { passwordError: '...' }). This allows you to check for specific keys in your template and update the correct form’s feedback area independently.


Complete Example Session

// ============================================
// PART 1: MULTIPLE ACTIONS
// ============================================
// src/routes/settings/+page.server.ts
export const actions = {
  profile: async ({ request }) => { /* ... */ },
  security: async ({ request }) => { /* ... */ }
};

// ============================================
// PART 2: TARGETED SUBMISSION
// ============================================
// <form action="?/profile" ...>

// ============================================
// PART 3: INDEPENDENT FAILURES
// ============================================
// return fail(400, { profileError: "Name taken" });

// ============================================
// PART 4: FRONTEND FEEDBACK
// ============================================
// {#if form?.profileError} ... {/if}

// ============================================
// PART 5: INDEPENDENT SUCCESS
// ============================================
// {#if form?.securitySuccess} ... {/if}

// ============================================
// PART 6: CONCURRENT SUBMISSIONS
// ============================================
// use:enhance handles each independently

// ============================================
// PART 7: DATA SERIALIZATION
// ============================================
// Returns are serialized back to the page

// ============================================
// PART 8: NAMED ACTIONS TYPING
// ============================================
// import type { Actions } from './$types';

// ============================================
// PART 9: THE DEFAULT ACTION
// ============================================
// Triggered if action="?" (no name provided)

// ============================================
// PART 10: FORM DATA ACCESS
// ============================================
// const formData = await request.formData();

The steps above illustrate how to define, trigger, and respond to multiple actions from a single server-side controller.


Quick Reference

Trigger Syntax

Form ActionDestination
action="?"Default action
action="?/name"Named action (name)

Return Patterns

PatternEffect
return { key: val }Success response in form prop
return fail(4xx, obj)Error response in form prop
throw redirect(...)Redirects instead of updating form

Best Practices

โœ… Do This:

// Explicitly name your actions for clarity
export const actions = { login, register };               // โœ…

// Use namespaced return keys for independent UI
return fail(400, { loginError: 'Fail' });                 // โœ…

// Always use use:enhance for multi-form pages
<form action="?/name" use:enhance>                        // โœ…

// Keep actions logic small and delegated
const result = await userService.update(data);            // โœ…

โŒ Don’t Do This:

// Don't use a catch-all 'default' for everything
// It makes form identification impossible                 // โŒ

// Don't overwrite the same 'error' key
// Use specific keys like 'loginError' and 'regError'      // โŒ

// Don't put massive functions in actions
// Delegate to services in $lib/server                     // โŒ

// Don't ignore form return values in UI
// Users won't know if the action succeeded                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Action not foundWrong action stringCheck ?/actionName
UI state collisionShared key in returnsNamespace error/success keys
Form resetForgot enhanceAdd use:enhance
Logic leakageShared local varsKeep action scopes pure

Real-World Examples

1. Define named actions

export const actions = { update: async (...), delete: async (...) };

2. Triggering specific action

<form action="?/update" method="POST" use:enhance>

3. Error handling with namespace

return fail(400, { updateError: 'Failed' });

4. Conditional UI feedback

{#if form?.updateError} <p>{form.updateError}</p> {/if}

5. Handling default action

<form action="?" ...>

6. Redirect from action

throw redirect(303, '/dashboard');

7. Service delegation

await profileService.update(request);

8. Parsing specific form

const data = await request.formData();

9. Multiple success states

{#if form?.success} <p>Saved!</p> {/if}

10. Typed actions

import type { Actions } from './$types';

Visual

Action Routing

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Form -> action="?/profile"          โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚  SvelteKit Router                    โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚  +page.server.ts -> actions.profile()โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Response Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Action: return { profileError: 'X' }โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚  SvelteKit: Serializes data          โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚  Page: form.profileError === 'X'     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Named Action?/name
Default Action?
Frontend Storeform prop
Validationfail() helper
ProgressiveNative POST

Key takeaways:

  • Named actions are your gateway. They allow you to host multiple submission handlers in one file, keeping your logic colocated and organized.
  • Use namespaces. To handle multiple forms on one page, ensure your return objects use unique keys to avoid state collisions.
  • use:enhance is mandatory for UX. Always use this directive on multi-form pages to ensure the UI feels snappy and responsive without page reloads.
  • Keep it modular. Don’t write massive logic inside an action. Delegate to services in $lib/server to maintain testability.
  • Forms are the contracts. Each form target (via action) should be treated as a distinct endpoint contract, handled cleanly by your action functions.

Remember: Named actions are the most idiomatic way to handle complex pages in SvelteKit. By giving every form a specific target and every return value a specific namespace, you create a robust, error-resistant interface that handles multiple intents within the same route, all while maintaining the safety of native HTML submissions.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!