0
0
Svelteframework~30 mins

Redirect from actions in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Redirect from actions in Svelte
📖 Scenario: You are building a simple Svelte app with a form where users can submit their email to subscribe to a newsletter. After submitting, you want to redirect them to a thank you page.
🎯 Goal: Create a Svelte form that uses an action to handle the submission and then redirects the user to a thank you page using a redirect from the action.
📋 What You'll Learn
Create a form with an action function in a +page.server.js file
The action should receive the form data and perform a redirect
Use SvelteKit's redirect helper to redirect to /thank-you
Create a simple thank you page at /thank-you/+page.svelte
💡 Why This Matters
🌍 Real World
Redirecting users after form submissions is common in web apps, such as signups, logins, or feedback forms.
💼 Career
Understanding how to handle form submissions and redirects on the server side is essential for building interactive and user-friendly web applications.
Progress0 / 4 steps
1
Set up the form in +page.svelte
Create a Svelte component in +page.svelte with a form that has an action attribute set to an empty string. The form should have an input field with name="email" and a submit button with the text Subscribe.
Svelte
Hint

Remember to set the action attribute on the form to an empty string to link it to the server action.

2
Create the action function in +page.server.js
Create a file +page.server.js and export an actions object with a default async function named default that accepts an { request } parameter. Inside the function, get the form data by calling await request.formData() and extract the email field from it.
Svelte
Hint

Use await request.formData() to get the form data, then use formData.get('email') to get the email value.

3
Add redirect to the action function
Import redirect from @sveltejs/kit at the top of +page.server.js. Then, inside the default action function, after getting the email, return redirect(303, '/thank-you') to redirect the user to the thank you page.
Svelte
Hint

Use throw redirect(303, '/thank-you') to perform the redirect from the action.

4
Create the thank you page
Create a new file +page.svelte inside a folder named thank-you. Inside it, write a simple message inside a <main> tag that says Thank you for subscribing!.
Svelte
Hint

Use a <main> tag with a heading inside it for the thank you message.