Redirecting from actions helps you send users to a new page after they submit a form or perform an action. It makes the app feel smooth and guides users where they need to go next.
0
0
Redirect from actions in Svelte
Introduction
After a user submits a login form, redirect them to their dashboard.
When a user creates a new post, send them to the post's page.
If a user deletes an item, redirect them back to the list view.
After a user updates their profile, redirect to the profile page.
Syntax
Svelte
import { redirect } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { // handle form data here throw redirect(303, '/new-url'); } };
Use throw redirect(statusCode, url) inside an action to redirect.
Status code 303 means 'See Other' and is commonly used after form submissions.
Examples
Redirects the user to '/home' after the action runs.
Svelte
import { redirect } from '@sveltejs/kit'; export const actions = { default: async () => { throw redirect(303, '/home'); } };
Redirects to a thank-you page after saving form data.
Svelte
import { redirect } from '@sveltejs/kit'; export const actions = { save: async ({ request }) => { const formData = await request.formData(); // save data logic throw redirect(303, '/thank-you'); } };
Sample Program
This form asks for a name. When submitted, the action checks if the name is given. If yes, it redirects the user to '/welcome'. If not, it returns an error (not shown here for simplicity).
Svelte
<script lang="ts" context="module"> import { redirect } from '@sveltejs/kit'; export const actions = { default: async ({ request }) => { const formData = await request.formData(); const name = formData.get('name'); // pretend to save the name if (!name) { return { error: 'Name is required' }; } throw redirect(303, '/welcome'); } }; </script> <form method="post"> <label for="name">Name:</label> <input id="name" name="name" required /> <button type="submit">Submit</button> </form>
OutputSuccess
Important Notes
Always use throw redirect() inside actions to perform redirects.
Use status code 303 to tell the browser to use GET for the redirected page.
Redirects help avoid resubmitting forms if the user refreshes the page.
Summary
Redirects from actions guide users after form submissions or events.
Use throw redirect(status, url) inside the action function.
Status code 303 is standard for redirecting after POST requests.