Gebna

Typesafe Links, Redirects, and Form Actions in SvelteKit

Written by Bahaa Zidan

One of the great features of SvelteKit is its phenomenal built-in routing and data loading capabilities. But as the number of pages and forms grows in your app, making refactors or changes to a page or even a layout might introduce some runtime bugs. That is because SvelteKit doesn’t provide any way to check if an href in an anchor tag or a url value in a redirect is valid. We need a way to guarantee that all our links, redirects, and even form actions are valid at compile time.

Introducing vite-plugin-kit-routes

A Vite plugin that generates a typesafe function for routes and form actions.

Installation

npm i -D vite-plugin-kit-routes

In your vite.config.ts:

import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";
import { kitRoutes } from "vite-plugin-kit-routes";
 
export default defineConfig({
  plugins: [
    sveltekit(),
    kitRoutes({ generated_file_path: "src/lib/__generated__/routes.ts" }),
  ],
});

Results

Now in all of your anchor tags, redirects, and even form actions, replace strings with invocations of the route function exported from $lib/__generated__/routes.ts: Screenshot