September 16, 2022
A Simple Guide to Redirects in Svelte Kit
Justin Golden
The Problem
You want to handle redirects without creating a new page or a lot of code for each new redirect. You want something that works and that scales.
The Solution
Create a hooks.js
file in your routes
directory:
import redirects from './data/redirects';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
const redirect = redirects.find((item) => event.url.pathname === item.source);
if (redirect) {
return new Response('', { status: 301, headers: { Location: redirect.destination } });
}
const response = await resolve(event);
return response;
}
(optional) Create redirects.js
(in my example in my data
directory):
(alternatively, you could just store this object inside of hooks.js
, but I like to keep them separate)
const redirects = [
{
source: '/test1',
destination: '/test2'
}
];
export default redirects;

The Details
For starters, I think the redirects
file is fairly self-explanatory, but I’ll give it a go anyways. We export a list of redirect objects, which contain sources
and destinations
. We redirect from the source to the destination. Each source
should be unique.
- The
hooks
file first imports ourredirects
:
import redirects from './data/redirects';
- Then sets the typing for typescript / syntax highlighting (you can remove this but it’s nice to have):
/** @type {import('@sveltejs/kit').Handle} */
- We export a the
handle
function, which takes in theevent
which represents the request and aresolve
function which generates a response (in our case, rendering a page, see the docs):
export async function handle({ event, resolve }) {
- We then check to see if any
redirects
contains the current page (event.url.pathname
) as asource
:
const redirect = redirects.find((item) => event.url.pathname === item.source);
- If the redirect exists, then we return a response with status 301 (permanent redirect, 302 is temporary, Status code 301) to the new location,
redirect.destination
return new Response('', { status: 301, headers: { Location: redirect.destination } });
- If there is no redirect, then we simply resolve the event and return that response, not changing anything form default behavior.
const response = await resolve(event); return response;
More Blog Articles