Form actions handle mutations to safely change data on the server when a user submits a form. This keeps your app organized and secure.
Why form actions handle mutations in Svelte
export const actions = { default: async ({ request }) => { const formData = await request.formData(); // process formData and perform mutation return { success: true }; } };
The actions object defines functions that run when a form is submitted.
Each function receives the form data and can update the server or database.
export const actions = { default: async ({ request }) => { const data = await request.formData(); const name = data.get('name'); // save name to database return { success: true }; } };
export const actions = { updateProfile: async ({ request }) => { const data = await request.formData(); const email = data.get('email'); // update user email in database return { updated: true }; } };
This SvelteKit example uses a form in +page.svelte and a default action in +page.server.js to handle the form submission. When the user submits the username, the action reads it and returns a success message, which is displayed on the page after re-render.
<!-- +page.svelte --> <script> export let data; </script> <form method="POST"> <label for="username">Username:</label> <input id="username" name="username" required /> <button type="submit">Save</button> {#if data?.message} <p>{data.message}</p> {/if} </form> <!-- +page.server.js --> export const actions = { default: async ({ request }) => { const formData = await request.formData(); const username = formData.get('username'); // pretend to save username return { success: true, message: `Saved username: ${username}` }; } };
Form actions run on the server, so they can safely change data without exposing logic to the browser.
Using form actions helps keep your app secure and organized by separating data changes from UI code.
Form actions handle data changes when users submit forms.
They run on the server to keep data safe and app organized.
Use them to process, validate, and save form data smoothly.