SvelteKit UUID Slugs in a Derived Store
By Justin Poehnelt Published 1 min read
Last verified in 2024. APIs or CLI flags may have changed; browse recent posts in the archive.
UUIDs work well as unique identifiers in URLs, but they are long and awkward to read. Encoding a UUID as a shorter string fixes that. This post shows how to handle that conversion in a SvelteKit store.
URL safe base 64 encoding uses the following characters: A-Z, a-z, 0-9, -, and _. The padding character = is not used and the characters + and / are replaced with - and _ respectively. See RFC 4648, sec. 5.
UUID to slug and slug to UUID
Here are the conversion functions. The uuid package parses and stringifies UUIDs, and Buffer converts between byte arrays and base64 strings. When Buffer is unavailable, the code falls back to btoa and atob.
const toBase64: (bytes: Uint8Array) => string = (() => {
if (typeof Buffer !== "undefined") {
return (bytes: Uint8Array) => Buffer.from(bytes).toString("base64");
}
return (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes));
})();
const fromBase64: (base64: string) => Uint8Array | Buffer = (() => {
if (typeof Buffer !== "undefined") {
return (base64: string) => Buffer.from(base64, "base64");
}
return (base64: string) =>
Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
})();
/**
* Returns the given uuid as a 22 character slug. This can be a regular v4
* slug or a "nice" slug.
*/
export function uuidToSlug(id: string) {
const bytes = uuid.parse(id);
const base64 = toBase64(bytes);
const slug = base64
.replace(/\+/g, "-") // Replace + with - (see RFC 4648, sec. 5)
.replace(/\//g, "_") // Replace / with _ (see RFC 4648, sec. 5)
.substring(0, 22); // Drop '==' padding
return slug;
}
/**
* Returns the uuid represented by the given slug
*/
export function slugToUUID(slug: string) {
const base64 = `${slug.replace(/-/g, "+").replace(/_/g, "/")}==`;
return uuid.stringify(fromBase64(base64));
}
A parameters store
In my SvelteKit application I am using the following folder structure for parameters:
src
└── routes
└── [fooId]
└── +page.svelte The +page.svelte component renders the page. The fooId path parameter carries a UUID encoded as a slug in the URL, and the params store converts that slug back to a UUID.
This example only converts parameters whose values are 22 characters long and whose names end with Id or id. Adjust that check to match your own parameter names.
// src/lib/stores.ts
import { page } from "$app/stores";
import { derived } from "svelte/store";
import { slugToUUID } from "$lib/utils/uuid";
export const params = derived(page, ($page) => {
return Object.fromEntries(
Object.entries($page.params).map(([key, value]) => {
// Convert slugs to UUIDs if ending in 'Id' or 'id' and 22 characters long
if (/^(id|[a-zA-Z]+Id)$/.test(key) && value && value.length === 22) {
value = slugToUUID(value);
}
return [key, value];
}),
);
});
The Regex match above matches these examples:
id: matchesfooId: matchesfoo: does not matchfooid: does not match
Using the parameters store
Import the params store in +page.svelte to read the decoded UUIDs.
// src/routes/[fooId]/+page.svelte
<script>
import { params } from "$lib/stores";
import { page } from "$app/stores";
</script>
<p>uuid: {$params.fooId}, slug: {$page.params.fooId}</p>
The above code will show the following output:
uuid: 376a4cca-9431-44f0-bc04-054faffba9b1, slug: N2pMypQxRPC8BAVPr_upsQ Conclusion
While I plan to use this technique, I may also consider storing a short slug as a unique key in the database. That lets me use the slug directly in URLs without conversion, at the cost of an extra database lookup.