In SvelteKit’s+page.tsfile, you can redirect by throwing aredirecterror from the@sveltejs/kitmodule within yourloadfunction.
Here’s how to do it:
// src/routes/+page.tsimport{redirect}from'@sveltejs/kit';importtype{PageLoad}from'./$types';// Optional, but good practice for type safetyexportconstload:PageLoad=async({url})=>{// --- Your logic here to decide if a redirect is needed ---// For demonstration, let's say we always want to redirect from this specific page.// In a real application, you'd have a condition, e.g.:// if (url.searchParams.has('old_param')) {// throw redirect(302, '/new-page');// }// if (!userIsLoggedIn) {// throw redirect(302, '/login');// }// To redirect to the root '/' page:throwredirect(302,'/');// If the redirect condition is not met, you would return data for the page:// return {// // someData: 'This page was not redirected.'// };};Explanation:
import { redirect } from '@sveltejs/kit';: You need to import theredirectutility from the SvelteKit library.export const load: PageLoad = async ({ url }) => { ... };: This is your standard SvelteKitloadfunction. It runs both on the server and in the browser.- The
urlparameter (fromLoadEvent) can be useful if your redirect logic depends on the current URL’s path, search parameters, etc.
- The
throw redirect(302, '/');:redirect(statusCode, location): This function creates a special SvelteKitRedirecterror. When SvelteKit catches this error, it performs the HTTP redirect.302(Found / Temporary Redirect): This is the most common status code for temporary redirects. It tells the browser (and search engines) that the resource has temporarily moved to a new URL. The browser will then issue a new request to the target URL./: This is the target URL. In this case, it’s the root of your application.
When to use different status codes:
302(Found / Temporary Redirect): Use this for most temporary redirects, e.g., redirecting users to a login page, after a form submission, or based on some temporary state.301(Moved Permanently): Use this if the resource has permanently moved to a new URL. Browsers will cache this aggressively, so use with caution. Only use if you are absolutely certain the redirect will be permanent.303(See Other): Often used after aPOSTrequest to redirect the user to aGETrequest, preventing accidental re-submission of form data if the user refreshes the page.
For a simple redirect to the root page,302is generally the safest and most appropriate choice.