Sveltekit - Advanced Routing



Advanced routing in SvelteKit offers several powerful features that enhance how developers can manage and structure their routes. This includes optional parameters, rest parameters, parameter matchers, route groups, and breaking out of layouts.

Optional Parameters

Optional parameters allow developers to create routes that can work with or without specific parameters. This is especially helpful in situations like localization, where a language code might not always be needed.

Basic Syntax

To make a parameter optional, you wrap it in double brackets. For example:

  • Required parameter: [lang]/home mentioning language to be required parameter.
  • Optional parameter: [[lang]]/home mentioning language to be optional parameter.

Rest Parameters

Rest parameters enable routes to match an unknown number of path segments. This is particularly useful for creating catch-all routes.

Basic Syntax

The rest parameter is defined by wrapping the parameter name in square brackets with three dots. For example:

src/routes/[...path]/+page.svelte

Parameter Matchers

Parameter matchers provide a way to validate route parameters against specific patterns. This prevents the router from matching invalid input.

Syntax Example

To create the parameter matcher you need to use the export function match() in the src/params directory as shown in the below example syntax:

// src/params/hex.js
export function match(value) {
    return /^[0-9a-f]{6}$/.test(value);
}

Route Groups

Route groups help developers organize routes without changing their URLs. By using parentheses in folder names, you can keep related routes together while keeping the paths neat.

Example Structure

src/routes/
 (admin)/
    dashboard/
    settings/

Breaking Out of Layouts

SvelteKit allows specific pages to break out of shared layouts when needed. This is useful when certain pages should not inherit layout styles or components.

Example

The following example demonstrates using param matchers correctly in a SvelteKit application to validate route parameters to ensure they meet specific criteria.

 <!--src/params/id.js-->
export function match(value) {
    return /^[0-9]+$/.test(value); // Only allow numeric IDs
}

<!--src/routes/user/[id=id]/+page.svelte-->
<script context="module">
    export async function load({ params }) {
    const { id } = params;
    return { props: { id } };
    }
</script>

<script>
    export let id;
</script>

<h1>User ID: {id}</h1>

<!--src/routes/+layout.svelte-->
<nav>
    <a href="/">Home</a>
    <a href="/user/1">User 1</a>
    <a href="/user/abc">Invalid User</a> <!-- This will trigger a 404 -->
</nav>

<slot />

Output

sveltekit-params
Advertisements