In SvelteKit, page redirection can be implemented in multiple ways, depending on the timing of the redirection. Below are common scenarios and their implementation methods:
1. Using the goto Function
In SvelteKit, you can use the navigation helper function goto to perform client-side redirection. This is a common approach for redirecting after user interaction or when specific conditions are met.
Example:
Suppose you are on a login page; after a user successfully logs in, redirect them to the homepage:
javascriptimport { goto } from '$app/navigation'; async function login(username, password) { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); if (response.ok) { // Login successful, redirect to homepage goto('/'); } else { console.error('Login failed'); } }
2. Redirecting in the load Hook
If you need to determine redirection during page loading (e.g., based on user authentication status), implement it within the page's load function.
Example:
Suppose you want to restrict access to a protected page; if the user is not logged in, redirect them to the login page:
javascriptexport async function load({ session, fetch }) { if (!session.user) { return { status: 302, redirect: '/login' }; } // User is authenticated, continue loading the page // Additional page logic... }
In this example, we check for user information in the session object. If none is found, we return an object with status code 302 and the redirect path.
3. Redirecting in the endpoint
When handling logic in an API endpoint (e.g., processing form submissions), you can directly return a redirect response.
Example:
javascriptexport async function post(request) { const result = await someDatabaseOperation(request.body); if (result.success) { return { status: 303, // See Other headers: { location: '/success' } }; } else { return { status: 303, headers: { location: '/error' } }; } }
In this example, we return different redirect paths based on the operation result. Status code 303 indicates a See Other response, typically used for redirection after POST requests.
By using these methods, you can implement redirection in your SvelteKit application based on various scenarios and requirements.