Sveltekit - Redirects



The Redirect chapter in SvelteKit explains how to use redirects to help users easily move from one page to another on your website.

What are Redirects?

Redirects are used to send users from one URL to another. This can be helpful for different reasons, like when a page moves to a new location or when you want to direct users after they submit a form.

Using the redirect Function

In SvelteKit, you can use the redirect function to set up redirects in your application. You need to import this function from @sveltejs/kit.

Implementing Redirects

To Implement redirects in SvelteKit, you can follow the steps mentioned below:

  • Import the Redirect Function: Firstly, you need to import the redirect function from @sveltejs/kit.
import { redirect } from '@sveltejs/kit';
  • Create a Load Function: Then you can create a load function in your route file (e.g., src/routes/a/+page.server.js) to handle the redirect.
  • export function load() {
        throw redirect(307, '/b'); // Redirects to '/b'
    }

    Status Codes

    SvelteKit contains the following status codes that indicate the different types of redirects.

    • 303: This status code is used for form actions after successful submissions.
    • 307: This status code indicates a temporary redirect.
    • 308: This status code indicates a permanent redirect.

    Example

    The following is a simple example that demonstrates how to use redirects in SvelteKit.

     <!--src/routes/a/+page.server.js-->
    import { redirect } from '@sveltejs/kit';
    
    export function load() {
        throw redirect(307, '/b'); // Redirects to '/b'
    }
    
    <!-- src/routes/b/+page.svelte -->
    <script>
        // Any necessary script for your page can go here
    </script>
    
    <h1>Welcome to Page B!</h1>

    Output

    sveltekit-redirects
    Advertisements