Shared Utilities
The @kit/shared registry, safe redirects, slugs and currency formatting, with the edge cases each one handles.
@kit/shared holds the small, framework-free helpers every package uses. Each one has its own entry point, and all of them run the same on Cloudflare Workers and in the browser:
| Import | Exports |
|---|---|
@kit/shared/registry | createRegistry |
@kit/shared/safe-redirect | getSafeRedirectPath |
@kit/shared/utils | generateSlug, formatCurrency, emailDomain (the domain of an address, for logs) |
@kit/shared/logger | logger, withoutQueryDetails (see Logging) |
@kit/shared/flash | parseFlash (see Flash notices) |
@kit/shared/env-validators | The validators kit-env.ts uses: siteUrl, authSecret, absolutePath, wholeNumber |
Registry
createRegistry maps names to lazy factories. Use it when one interface has several implementations (a mailer, a storage driver, a billing provider) and the app picks one by name.
import { createRegistry } from '@kit/shared/registry';interface Greeter { greet(name: string): string;}const greeters = createRegistry<Greeter, 'formal' | 'casual'>() .register('formal', () => ({ greet: (name) => `Good morning, ${name}.` })) .register('casual', async () => { // heavy implementations can be imported here, so they load on first use return { greet: (name) => `Hey ${name}!` }; });const greeter = await greeters.get('casual');greeter.greet('Ada'); // 'Hey Ada!'How it behaves:
- Lazy. A factory runs on the first
get, so unused implementations (and their imports) are never loaded. - Built once per isolate. The instance is cached for the life of the Worker isolate, across requests. Concurrent
getcalls share one in-flight build. - Retried on failure. A factory that throws, rejects or returns a falsy value isn't cached; the next
gettries again. - No fallback. An unknown name rejects with
Implementation "<name>" not found. Pick the name explicitly; the registry never guesses. get('a', 'b')resolves several at once.addSetup(group, callback)registers one-time setup steps, and everygetfirst runs any that haven't succeeded yet, in all groups. A failing step makes everygetreject until it succeeds; steps that succeeded don't rerun.
Because the instance outlives the request, a factory must not return or capture anything tied to one request: a Request, a Response, a stream, a socket or a per-request client. On Workers, the second request that touches it fails with "Cannot perform I/O on behalf of a different request". Return configuration and stateless clients that open their I/O inside each call (a Postgres client holding a connection counts as request-bound), and pass request data as method arguments.
Safe Redirects
getSafeRedirectPath(path, fallbackPath = '/') returns path only if it is a same-origin relative path, and fallbackPath otherwise. Every redirect target that comes from a user (a next query parameter, a form field, a cookie) must go through it, including every post-sign-in redirect.
import { getSafeRedirectPath } from '@kit/shared/safe-redirect';const next = getSafeRedirectPath(c.req.query('next'), '/dashboard');return c.redirect(next);It rejects absolute and protocol-relative URLs (https://evil.com, //evil.com), backslash and encoded tricks (/\evil.com, /%2F%2Fevil.com), control and non-ASCII characters, and paths over 2,048 characters. Paths with a query string or hash are kept as they are.
Raw Unicode paths such as /café fall back too. Links must percent-encode them (/caf%C3%A9), which browsers and encodeURI already do.
Slugs
generateSlug(name) returns a lowercase, transliterated, hyphenated slug:
import { generateSlug } from '@kit/shared/utils';generateSlug('Acme Inc.'); // 'acme-inc'generateSlug('Café Münster'); // 'cafe-muenster'generateSlug('株式会社'); // ''It returns "" when nothing transliterates: emoji and names in Chinese, Japanese, Korean, Hebrew, Hindi or Thai. Always handle the empty case, for example by falling back to a random suffix. Length isn't capped, so trim it if your column has a limit.
Currency
formatCurrency({ value, currencyCode, locale }) formats money with Intl.NumberFormat:
import { formatCurrency } from '@kit/shared/utils';formatCurrency({ value: 1999.5, currencyCode: 'USD', locale: 'en-US' }); // '$1,999.50'formatCurrency({ value: '0.10', currencyCode: 'EUR', locale: 'de-DE' }); // '0,10 €'- Decimal strings, such as Postgres
numericcolumns, are passed toIntlas strings, so large values don't lose precision throughNumber. They're still rounded to the currency's decimals ('10.125'in USD shows$10.13). Strings must look like-?123or-?123.45:'1,000','.5'and'+1'throw. - An invalid amount (
NaN,'','abc') throws aRangeErrorinstead of showing$0.00, and so do an invalid currency code or locale. Pass0explicitly when zero is what you mean.
Flash notices
A flash is a one-shot notice for the page a redirect leads to, such as "You joined Acme" after accepting an invitation. Set it in the action, then redirect:
import { setFlash } from '#/lib/flash.server.ts';const t = getServerTranslator({ c, namespace: 'invitations' });setFlash({ c, message: t('link.joined', { organization: name }) });return localizedRedirect({ c, href: '/dashboard' });setFlash stores the message in a short-lived, HttpOnly flash cookie (60 seconds). On the next request, middleware/09.flash.ts moves it into shared.flash and clears the cookie. FlashToast (@kit/ui/flash-toast) in the root layout then shows it once as a toast. kind is success (the default) or info.
- Pass translated plain text. It's rendered as text, never as HTML, and capped at 300 characters.
- Never put a notice in the URL. A query parameter shows again on reload and in shared links, and stripping it costs a second page fetch.
- A cookie the kit didn't write, or one that is malformed, is cleared and ignored (
parseFlashin@kit/shared/flash).
Related
- Logging: the structured logger in
@kit/shared/logger. - Authorization Policies: business rules built on
@kit/policies.
Table filters
@kit/ui/table-filters provides a Supamode-style toolbar built with shadcn Button, Command, Popover, Input and Calendar. Put it above your own @kit/ui/table or other table. It owns the editors; your app owns the filtered rows and selected values.
import { useState } from 'react';import { TableFilters, type FilterOption, type TableFiltersLabels } from '@kit/ui/table-filters';import { Table, TableBody, TableCell, TableRow } from '@kit/ui/table';type OrdersTableProps = { orders: { id: string; name: string; status: string }[]; labels: TableFiltersLabels; statusLabel: string; isLabel: string; options: FilterOption[];};function OrdersTable({ orders, labels, statusLabel, isLabel, options }: OrdersTableProps) { const [status, setStatus] = useState<FilterOption | null>(null); const rows = orders.filter((order) => !status || order.status === status.value); return ( <div className="space-y-4"> <TableFilters labels={labels} fields={[ { type: 'choice', key: 'status', label: statusLabel, operator: isLabel, value: status, options, onChange: setStatus, }, ]} canClear={Boolean(status)} onClear={() => setStatus(null)} /> <Table> <TableBody> {rows.map((order) => ( <TableRow key={order.id}> <TableCell>{order.name}</TableCell> </TableRow> ))} </TableBody> </Table> </div> );}Pass translated copy through TableFiltersLabels: title, addFilter, clearFilters, searchFields, searchOptions, empty, loading, failed, retry, back, apply, remove. Each field supplies its translated label and operator.
- Choices: pass
optionsorloadOptions({ query, signal }). Options containvalue,label, optionaldescription. Async searches debounce 250 ms, abort replaced requests, ignore stale completions, and expose loading/empty/retry states. The app's endpoint must authorize access; the toolbar grants no permissions. - Dates: use
type: 'date-range', controlled{ from, to }ISO days,days: { first?, last }, optional locale and translatedpresets. The calendar fills the popover width. Calendar selections apply together; presets apply immediately. Days use UTC. - Search: optional
search: { value, placeholder, onChange, maxLength? }adds a search strip. Changes call your callback immediately; debounce server navigation in the app, cancelling pending search when other filters change. - Chips:
pinnedkeeps a default filter editable without a remove button.disabledprevents editing; an existing selection can still be removed. - State: bind callbacks to React state, your router, or a server query. No routing, transport, database or admin dependency is built in. Reset pagination when a filter changes. Keep stable field keys; remount the toolbar with a query key when navigating between independent filter states.