How to Navigate in SvelteKit with 'redirect' and 'goto'

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call

Navigating between routes programmatically is a common requirement in applications. SvelteKit provides two primary methods for this purpose: redirect and goto. In this guide, you'll learn how to use these methods effectively.

Using redirect

The redirect function is used for server-side navigation, such as during form submission or in endpoint handlers, and can be used within load functions, form actions, API routes, and the handle hook.

The redirect function must include a status code as a function argument. Common status codes include:

Code Example

This example is a SvelteKit server-side action that handles form data (email) and redirects the user to a different page (/auth/verify).

// +page.server.ts
import { redirect } from '@sveltejs/kit';

export const actions = {
	default: async ({ request }) => {
		// Form data
		const data = await request.formData();
		const email = data.get('email') as string;

		// Validate email & send One Time Passcode...

		// Redirect to verify page
		throw redirect(303, '/auth/verify');
	}
};

When to use redirect

Using goto

The goto function is used for client-side navigation. It is ideal for SPA (Single Page Application) behaviors where you want to navigate without reloading the page.

Code Examples

Call the goto function to navigate to a new route. This can be triggered by events such as button clicks:

<!-- +page.svelte -->
<script lang="ts">
  import { goto } from '$app/navigation';

  function handleNavigation() {
    goto('/new-route');
  }
</script>

<button on:click={handleNavigation}>Go to New Route</button>

The goto function can also accept additional options, such as parameters and replace state.

<!-- +page.svelte -->
<script lang="ts">
  import { goto } from '$app/navigation';

  function handleNavigation() {
    goto('/new-route', { replaceState: true, noScroll: true });
  }
</script>

<button on:click={handleNavigation}>Go to New Route</button>

When to use goto

Summary

Navigating programmatically in SvelteKit can be done using either redirect for server-side navigation or goto for client-side navigation.

That's it! Happy coding.

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call