Route unstable
Route definitions: a flat union of routes, each a path template with
params and search Schemas, plus a parser and a printer that agree.
A route union is a Schema.TaggedUnion, so a route value such as
{ _tag: "Person", params: { id: 1 }, search: {} } can be a root's props and
a page's props. Parsing decodes path and search strings through each route's
Schemas with Schema.toCodecStringTree, so params: { id: Schema.Number }
works directly, and printing encodes through the same Schemas.
Matching
- A template has literal segments,
:nameparams and an optional trailing*, which captures the rest of the path as the"*"param. - A literal segment beats a param and a param beats a rest, whatever the declaration order. Between equal templates, the first declared wins.
- If a path param fails to decode, matching falls through to the next
route, so
/people/:idwith a Number and/people/:slugwith a String can coexist. If a required search field fails to decode, the URL is a 404: the result is the catch-all"/*"route, with no fall-through. - A trailing slash is stripped, a printed path never has one, and matching is case-sensitive.
- Redirects take part in the ranking like routes, and
parseresolves them, so the server and the client agree.
Search
- A search field that decodes when its key is absent, such as
Schema.optional(Schema.String)or a field withSchema.withDecodingDefaultKey, is treated as absent when its value fails to decode or its key is repeated.resolvenames such keys ininvalid, and the Router replaces the URL with one without them. - A lone value decodes into an array field, so
?tag=xis["x"]. - A field with a decoding default holds it when its key is absent,
makefills it in, andprintleaves out a param equal to it. printencodes search likeURLSearchParamsand GET forms: a space is+, a literal plus is%2B. Parsing accepts both+and%20as spaces.
Base path
Templates are relative to the union's base path, which a Router Layer sets
at startup. parse only accepts URLs under the base and print adds it
back, so printed links are always absolute. A trailing slash on the base is
kept for Home only: under "/docs/" Home prints as "/docs/", and under
"/en" as "/en". A relative or full-URL base, such as Vite's "./",
keeps the routes at the root. The base "#" puts the URL in the fragment,
as "#/people/1", for static hosting.
Example A route table
import { Option, Schema } from "effect"import { Route } from "effect/ui"
const AppRoute = Route.union( { Home: Route.make("/"), Person: Route.make("/people/:id", { params: { id: Schema.Number }, search: { tab: Schema.optional(Schema.String) } }), NotFound: Route.make("/*") }, Route.redirect("/old/:id", (params) => ({ _tag: "Person", params: { id: Number(params.id) }, search: {} })))
Option.getOrThrow(AppRoute.parse("/people/1?tab=posts")).search // => { tab: "posts" }AppRoute.Person.href({ params: { id: 2 } }) // => "/people/2"Option.getOrThrow(AppRoute.parse("/old/3")).params // => { id: 3 }Option.getOrThrow(AppRoute.parse("/nope"))._tag // => "NotFound"Constructors
Defines a route from a path template and the Schemas of its params and search.
Details
Every :name in the template must have a Schema in params, which is a
compile error otherwise. A trailing * captures the rest of the path, as
the "*" param. Params and search decode from URL strings through
Schema.toCodecStringTree, so a Schema.Number param parses "42". A
search field that is neither optional nor defaulted makes the route a 404
when it's missing or fails to decode.
Give a search field a default with the Schema API, as
Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(1))):
its type is then number, an absent or invalid param decodes to the
default, print leaves the param out while it holds the default, and the
union's make fills it in.
Signature
declare function make<Path extends string, Params extends Fields = {}, Search extends Fields = {}>(path: Path, ...__namedParameters: [PathParams<Path>] extends [never] ? [options?: { readonly params?: Params; readonly search?: Search;}] : [options: { readonly params: Params & { [K in string]: Constraint }; readonly search?: Search;}]): Route<Path, Declared<Params>, Declared<Search>>A redirect for a route union: a template whose raw string params and search map to a route value.
Details
A redirect is ranked with the routes, and parse returns the route it
maps to. resolve reports it as redirected, which the server answers
with a 301.
Signature
declare function redirect<Path extends string>(path: Path, to: (params: { [K in string]: string }, search: Readonly<Record<string, string | ReadonlyArray<string>>>) => { readonly _tag: string;}): RedirectBuilds a route union from routes by tag, and redirects.
Details
The result is a Schema.TaggedUnion whose values are
{ _tag, params, search }, with make, match, guards and isAnyOf,
plus parse, resolve, print, printPath, subset and catchAll,
and one constructor per route: AppRoute.Home(),
AppRoute.Person({ params: { id: 1 } }). A constructor is make with the
tag filled in, and make stays for a tag held in a variable. Both fill in
params and search when no field needs a value, and a field's decoding
default when it's left out. Each constructor also has href, which takes the
same argument and prints a link: AppRoute.Person.href({ params: { id: 1 } }). Router.navigable wraps the union to add push and replace.
A catch-all "/*" route, conventionally NotFound, ranks last; its tag is
exposed as catchAll. Under the route base, it handles unmatched URLs,
required search fields that fail to decode and malformed percent-escapes.
Malformed path segments stay as written in params["*"]. Without a catch-all,
parse returns Option.none() for these URLs and catchAll is undefined.
Gotchas
- A tag in Union.ReservedTag (
parse,print,make,match,name,Type, ...) is a type error, and throws when the union is built if it names a member the union has at runtime.
Signature
declare function union<Routes extends Record<string, Any>>(routes: Routes & { [K in string | number | symbol]: K extends ReservedTag ? never : Any }, ...redirects: readonly Array<Redirect>): Union<Routes>Models
Any route definition.
Signature
type Any = Route<string, Schema.Struct.Fields, Schema.Struct.Fields>Any route union.
Signature
interface AnyUnion { readonly base: () => string; readonly catchAll: string | undefined; readonly parse: (url: string) => Option<{ readonly _tag: string; }>; readonly print: (route: any) => string; readonly printPath: (route: any) => string; readonly resolve: (url: string) => Option<Resolved<{ readonly _tag: string; }>>; readonly setBase: (base: string) => void;}A redirect: a template whose raw params and search map to a route value.
Signature
interface Redirect { readonly _tag: "Redirect"; readonly path: string; readonly to: (params: Readonly<Record<string, string>>, search: Readonly<Record<string, string | ReadonlyArray<string>>>) => { readonly _tag: string; };}What resolve returns: the route a URL resolves to, whether a redirect or
a normalisation (such as a trailing slash) changed the URL, whether the
route is the union's catch-all "/*" route, and the search keys that were
dropped because their values failed to decode.
Details
The server answers a changed URL with a permanent redirect to
print(route), a non-empty invalid with a temporary one, since the same
URL may be valid later, and a notFound route with a 404. notFound is
true whether the catch-all matched the path or a required search field that
failed to decode fell back to it. A union without a catch-all never sets
it, because such URLs don't resolve.
Signature
interface Resolved<A> { readonly invalid: readonly Array<string>; readonly notFound: boolean; readonly redirected: boolean; readonly route: A;}A route definition: a path template and the Schemas of its params and search.
Signature
interface Route<out Path extends string, out Params extends Schema.Struct.Fields, out Search extends Schema.Struct.Fields> { readonly "~effect/ui/Route": "~effect/ui/Route"; readonly params: Params; readonly path: Path; readonly search: Search;}A route union: a Schema.TaggedUnion of route values, with a parser, a
printer and one constructor per route.
Details
The schema members come from Union.Base and the constructors from Union.Constructors.
Signature
type Union<Routes extends Record<string, Any>> = Union.Base<Routes> & Union.Constructors<Routes>Other
Type IDs
Utility Types
A params or search Struct, each field as MakeField gives it, which make
fills in, defaults included, when no field needs a value.
Signature
type FieldsSchema<Fields extends Schema.Struct.Fields> = {} extends Schema.Struct<{ [K in keyof Fields]: MakeField<Fields[K]> }>["~type.make.in"] ? Schema.withConstructorDefault<Schema.Struct<{ [K in keyof Fields]: MakeField<Fields[K]> }>> : Schema.Struct<{ [K in keyof Fields]: MakeField<Fields[K]> }>A field as a route value holds it: a field with a decoding default, such
as Schema.withDecodingDefaultKey, also gets that default in make.
Signature
type MakeField<S extends Schema.Constraint> = S extends { readonly "~encoded.optionality": "optional"; readonly "~type.constructor.default": "no-default"; readonly "~type.optionality": "required";} ? Schema.withConstructorDefault<S & Schema.WithoutConstructorDefault> : SThe params fields of a route value: the declared ones, plus "*" for a
template ending in *.
Signature
type ParamFields<R> = R extends Route<infer Path, infer Params, infer _Search> ? Path extends `${string}*` ? Params & { readonly "*": Schema.String;} : Params : neverThe names of a template's :name params.
Signature
type PathParams<Path extends string> = Path extends `${string}:${infer Rest}` ? Rest extends `${infer Name}/${infer Tail}` ? Name | PathParams<`/${Tail}`> : Rest : neverThe search fields of a route value.
Signature
type SearchFields<R> = R extends Route<infer _Path, infer _Params, infer Search> ? Search : never