SvelteKit separates server and client code clearly: +page.server.ts runs only on the server, +page.ts runs on both. UUID generation should live in the server-only file to avoid hydration mismatches and to keep ID generation close to the database write. The uuid npm package works in Node.js and the browser without any bundler configuration. See UUID in JavaScript for the broader runtime context.
Server load function
// src/routes/orders/+page.server.ts
import type { PageServerLoad } from './$types';
import { v7 as uuidv7 } from 'uuid';
import { db } from '$lib/server/db';
export const load: PageServerLoad = async () => {
const orders = await db.query('SELECT * FROM orders ORDER BY id');
return { orders };
};
export const actions = {
create: async ({ request }) => {
const data = await request.formData();
const id = uuidv7(); // server-side — never sent to client until after INSERT
await db.query(
'INSERT INTO orders (id, status) VALUES ($1, $2)',
[id, data.get('status')]
);
return { id };
},
};
UUID v7 is generated server-side in the form action — after the INSERT succeeds, the ID is returned to the client as part of the action result. This avoids the race condition where a client-generated ID might differ between SSR and hydration. See UUID v7 for Audit Logging for the append-only table pattern.
Svelte store with optimistic UUID
For optimistic UI — adding a row locally before the server confirms — generate a UUID v7 client-side as a temporary key:
// src/lib/stores/orders.ts
import { writable } from 'svelte/store';
import { v7 as uuidv7 } from 'uuid';
interface Order { id: string; status: string; pending?: boolean; }
export const orders = writable<Order[]>([]);
export function addOptimistic(status: string): string {
const tempId = uuidv7(); // client-generated — replace with server ID on confirm
orders.update(list => [...list, { id: tempId, status, pending: true }]);
return tempId;
}
export function confirmOrder(tempId: string, serverId: string) {
orders.update(list =>
list.map(o => o.id === tempId ? { ...o, id: serverId, pending: false } : o)
);
}
The tempId is only used as a client-side stable key for the Svelte {#each} block. The server-assigned serverId replaces it on confirmation. See UUID v4 vs v7 — UUID v7’s timestamp prefix means tempId and serverId both sort correctly relative to other orders without any extra logic.
SvelteKit API route
// src/routes/api/orders/+server.ts
import { json } from '@sveltejs/kit';
import { v7 as uuidv7 } from 'uuid';
import type { RequestHandler } from './$types';
export const POST: RequestHandler = async ({ request }) => {
const body = await request.json();
const id = uuidv7();
// persist to database...
await db.query('INSERT INTO orders (id, status) VALUES ($1, $2)', [id, body.status]);
return json({ id }, { status: 201 });
};
Typed ID pattern
// src/lib/types.ts
export type OrderId = string & { readonly _brand: 'OrderId' };
export const toOrderId = (s: string): OrderId => s as OrderId;
Branded types prevent accidental ID mix-ups at compile time with zero runtime overhead. The full TypeScript pattern is covered in TypeScript UUID Types.
Further reading
- UUID in JavaScript — full guide
- UUID in React and Next.js — hydration patterns
- TypeScript UUID Types — branded types
- crypto.randomUUID() runtime support
- UUID v4 vs v7 — which to use
- UUID v7 for Audit Logging
External references
Frequently asked questions
Where should I generate UUIDs in a SvelteKit app?
Generate UUIDs server-side in +page.server.ts load functions or form actions — not in +page.ts or Svelte component scripts that run on both server and client. Client-side UUID generation is safe for ephemeral IDs (optimistic UI, local state) but runs the risk of hydration mismatch if the server and client generate different values for the same rendered element. See UUID in React and Next.js for the same hydration concern in Next.js.
Does crypto.randomUUID() work in SvelteKit?
Yes — in Node.js (server) and in modern browsers (client). SvelteKit's server runtime is Node.js, where crypto.randomUUID() has been available since Node 19. In the browser, it requires a secure context (HTTPS or localhost). For UUID v7, install the uuid npm package — it works in both environments. See crypto.randomUUID() runtime support.