How to set up redirects with Sveltekit Static Adapter

If you have a Sveltekit client-only application that uses the static adapter, there are few caveats when setting up redirects. The most problematic being the lack of a server to serve a Location header. Here’s a simple setup to handle this without having to move to a non-static adapter.

Redirects.js

First, create a redirects.js file in the src folder. This is the file where you will be declaring all your redirects.

1export const APP_REDIRECTS = {
2 '/from': '/to'
3}
  • .ts won’t work as we will need to import this in svelte.config.js

  • you can’t have this file in the project root. It must be located in the src folder or another folder inside src .

Layout.ts

Create a layout.ts file in src/routes folder to handle the redirects.

1import { redirect } from "@sveltejs/kit";
2import { APP_REDIRECTS } from "../redirects";
3
4
5export async function load({ url }) {
6 const pathname = url.pathname;
7
8 if (APP_REDIRECTS.hasOwnProperty(pathname)) {
9 return redirect(301, (APP_REDIRECTS as any)[pathname]);
10 }
11}

This file checks if the current path is in the APP_REDIRECTS object, and if yes, returns a redirect response.

That is all you need to make it work on the dev server. But, wait, there’s no dynamic server when you build the app using the static adapter. So, how do redirects work?

Svelte.config.js

By default, the static adapter crawls through the links in your app and finds pages to build. This even works for dynamic routes like /docs/{page} as long as they are linked to from within the app.

However, it is very likely that you won’t be linking to the redirected old pages. In that case, the easiest option is to set those pages in the prerender.entries option in svelte.config.js.

1import { APP_REDIRECTS } from './src/redirects.js';
2
3const config = {
4 // other options...
5
6 kit: {
7 // other options...
8 prerender: {
9 entries: [
10 '*',
11 ...Object.keys(APP_REDIRECTS)
12 ]
13 }
14 },
15};

We already have the paths in the APP_REDIRECTS object. We’ll simply get the keys and add it to entries. Sveltekit will then nicely generate static HTML files for the redirects.

To test, run npm run build and then npm run preview. Visit the old page to make sure the redirect is working.

If you look inside the build folder, you will see a code that looks like this. That’s how Sveltekit handles a redirect in the front-end without having to use the Location header.

1<script>location.href="/to";</script><meta http-equiv="refresh" content="0;url=/to">

I hope someday, there will be a much easier way to do this inside the configuration of the static adapter. But, this will work for now! :)

References

Newsletter

Comments

Published with Hyvor Blogs