Form actions in SvelteKit provide seamless integration with the endpoint system, allowing you to work with real HTML forms and enhance them using Svelte actions. In this guide, we will explore how to use form actions in SvelteKit to handle form submissions, process form data, and enhance form interactions.
Before we begin, make sure you have the following:
- Basic knowledge of Svelte and SvelteKit.
- SvelteKit project set up and running.
To get started, let's add a form to your SvelteKit component. Open the page.svelte
file and add the following code:
<script> // Your component's script code goes here</script>
<form method="POST"> <!-- Form fields go here --> <input name="email"/> <button type="submit">Submit</button></form>
Ensure that each form element has a name
attribute to identify them. The name
attribute is essential for processing user inputs on the server.
To handle the form submission, we need to create a +page.server.js
file that exports an asynchronous function named actions
. This function will be responsible for processing the form data.
Create a +page.server.js
file in the same directory as your page.svelte
file. Inside the +page.server.js
file, add the following code:
export const actions = { default: async ({ request }) => { const formData = await request.formData(); const email = formData.get('email'); // Process the form data and perform actions return { success: true }; },};
We've added a default action that is triggered when the user clicks the submit button in the form. This action is an asynchronous function that accepts a parameter { request }
. We use the request.formData()
method to retrieve the form data. You can access specific form field values using the formData.get()
method, passing in the form element name as a parameter. Within the action, you can process the form data and perform any desired actions. Finally, you can return a value from the action, such as { success: true }
, to indicate a successful form submission.
We can access the returned value of our form action in our page by exporting the form
prop. In our +page.svelte
file, add the following code:
<script> export let form;</script>
Now, after submitting the form, our form action will run, and the value of form
will be updated accordingly. For example, if the form action returns { success: true }
, the value of form
will be { success: true }
. You can then use the form
prop to conditionally render UI components or perform other actions based on the form submission result.
In addition to the default action, you can define named actions to handle different form submissions on the same page. To implement named actions, follow these steps:
- Update the
+page.server.js
file to include named actions:
export const actions = { default: async ({ request }) => { // Default action implementation }, addUser: async ({ request }) => { // Add user action implementation }, getUser: async ({ request }) => { // Get user action implementation },};
- Modify the form element in the
page.svelte
file to include anaction
attribute with the name of the desired action as the value:
<form action="addUser" method="POST"> <!-- Form fields go here --> <input name="email" /> <button type="submit">Add User</button></form>
Note: The returned value of our form
prop will include the result of the form action. For example, if the addUser
action returns { success: true, user: user }
, the value of form
will be { success: true, user: user }
.
With named actions, you can define different actions for different form submissions on the same page, allowing you to handle each submission independently.
SvelteKit provides the use:enhance
action to enhance form interactions when JavaScript is available. The use:enhance
action emulates browser-native behavior without full-page reloads.
To enable progressive enhancement, add the use:enhance
action to your <form>
element, as shown in the following code:
<script> import { enhance } from '$app/forms'; // Import the enhance action
// Your script code goes here</script>
<form action="your-action-endpoint" method="POST" use:enhance> <!-- Form fields go here --> <button type="submit">Submit</button></form>
By adding the use:enhance
action, certain default behaviors are applied:
- The
page.form
andpage.status
properties are updated on successful or invalid responses, but only if the action is on the same page where the form is submitted from. - The
<form>
element is reset, and all data is invalidated on a successful response. - For a redirect response, the
goto
function is called to navigate to the specified location. - If an error occurs, the nearest
+error
boundary is rendered. - Focus is reset to the appropriate element after form submission.
You can also customize the behavior by providing a SubmitFunction
that runs just before the form submission. This function can handle tasks such as showing loading UI or handling specific response types.
Alternatively, you can implement progressive enhancement without using use:enhance
by adding a normal event listener on the <form>
element.
In this guide, we have learned how to use SvelteKit form actions to handle form submissions, process form data, and enhance form interactions. By following these steps, you can seamlessly integrate HTML forms into your SvelteKit application and provide a better user experience.
Happy coding with SvelteKit!