In SvelteKit, programmatic routing refers to controlling page navigation and redirection through code rather than via click-based links. This approach is highly beneficial when dynamically navigating based on specific logical conditions is required, such as automatically redirecting to different pages after a user completes a form.
How to Implement Programmatic Routing
SvelteKit provides a module named $app/navigation that includes functionality for implementing programmatic routing. Specifically, you can use the goto function to implement page navigation.
Here are the basic steps to use this functionality:
-
Import the
gotofunction:
Within your Svelte component, you first need to import thegotofunction.javascriptimport { goto } from '$app/navigation'; -
Use the
gotofunction for navigation:
You can invoke thegotofunction within any event handler or lifecycle function to change the route.javascriptfunction handleSomeAction() { goto('/some-path'); } -
Pass parameters:
If needed, thegotofunction can accept a second parameter to specify navigation behavior. For instance, you can set{ replaceState: true }to replace the current entry in the history stack instead of adding a new one.javascriptfunction handleSubmit() { goto('/success-page', { replaceState: true }); }
Example: Page Navigation After User Login
Suppose you have a login page where, after the user fills out the form and clicks the login button, you want to redirect to different pages based on the user's role. Here's how to implement this logic using programmatic routing:
svelte<script> import { goto } from '$app/navigation'; let userInfo = { username: '', password: '' }; async function loginUser() { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userInfo) }); if (response.ok) { const userRole = await response.json(); if (userRole === 'admin') { goto('/admin-dashboard'); } else { goto('/user-dashboard'); } } else { console.error('Login failed'); } } </script> <form on:submit|preventDefault={loginUser}> <!-- Form Fields --> <button type="submit">Login</button> </form>
In this example, after the user fills out the form and submits it, the application invokes the loginUser function. This function first sends a login request to the server, then uses the goto function to navigate the user to the appropriate page based on the user's role as returned by the server. This approach efficiently handles dynamic navigation and is suitable for scenarios where routing decisions must be made based on logical conditions.