Routing requests and serving content with sitelets
Sitelets are WebSharper's primary way to create server-side content. They provide a composable abstraction to route requests and generate responses like HTML pages or JSON.
The key concept is the endpoint: a value of a user-defined type that represents a specific request route. Sitelets parse incoming requests into these endpoint values, and then generate the appropriate content based on the endpoint. Link generation takes an endpoint value and produces a URL, which is the inverse of route parsing. By encapsulating these concepts, sitelets allow you to define a website's URL scheme, content, and linking in a type-safe manner.
In addition, if the router part is defined separately, it can be used on the client side too, for client-side routing and linking.
Below is a minimal example of a complete site, serving one HTML page:
First, a custom endpoint type is defined. It is used for linking requests to content within your sitelet. Here, you only need one endpoint, EndPoint.Index
, corresponding to your only page.
The content of the index page is defined as a Content.Page
, where the body consists of a server-side HTML element that computes and displays the current time within an <h1>
tag.
The MySampleWebsite
value has type Sitelet<EndPoint>
. It defines a complete website: the URL scheme, the EndPoint
value corresponding to each served URL (only one in this case), and the content to serve for each endpoint. It uses the Sitelet.Content
operator to construct a sitelet for the Index endpoint, associating it with the /index
URL and serving IndexContent
as a response.
Routing
WebSharper sitelets abstract away URLs and request parsing by using an endpoint type that represents the different HTTP endpoints available in a website. For example, a site's URL scheme can be represented by the following endpoint type:
Based on this, a sitelet is a value that represents the following mappings:
-
Mapping from requests to endpoints. A sitelet is able to parse a URL such as
/blog/1243/some-article-slug
into the endpoint valueBlogArticle (id = 1243, slug = "some-article-slug")
. More advanced definitions can even parse query parameters, JSON bodies or posted forms. -
Mapping from endpoints to URLs. This allows you to have internal links that are verified by the type system, instead of writing URLs by hand and being at the mercy of a typo or a change in the URL scheme. You can read more on this in the Content doc.
-
Mapping from endpoints to content. Once a request has been parsed, this determines what content (e.g., HTML, JSON, or other formats) must be returned to the client.
A number of primitives are available to create and compose sitelets.
Trivial sitelets
Two helpers exist for creating a sitelet with a trivial router that only handles requests on the root.
Application.Text
takes just aContext<_> -> string
function and creates a sitelet that serves the result string as a text response.Application.SinglePage
takes aContext<_> -> Async<Content<_>>
function and creates a sitelet that serves the returned content.
Sitelet.Infer
The easiest way to create a more complex sitelet is to automatically generate URLs from the shape of your endpoint type using Sitelet.Infer
, also aliased as Application.MultiPage
. This function parses slash-separated path segments into the corresponding EndPoint
value, and lets you match this endpoint and return the appropriate content. Here is an example sitelet using Infer
:
The above sitelet accepts URLs with the following shape:
The following types are accepted by Sitelet.Infer
:
-
Numbers and strings are encoded as a single path segment.
-
Tuples and records are encoded as consecutive path segments.
-
Union types are encoded as a path segment (or none or multiple) identifying the case, followed by segments for the arguments (see the example above).
-
Lists and arrays are encoded as a number representing the length, followed by each element. For example:
-
Enumerations are encoded as their underlying type.
-
System.DateTime
is serialized with the formatyyyy-MM-dd-HH.mm.ss
. See below to customize this format.
Customizing Sitelet.Infer
It is possible to annotate your endpoint type with attributes to customize Sitelet.Infer
's request inference. Here are the available attributes:
-
[<Method("GET", "POST", ...)>]
on a union case indicates which methods are parsed by this endpoint. Without this attribute, all methods are accepted. -
[<EndPoint "/string">]
on a union case indicates the identifying segment. -
[<Method>]
and[<EndPoint>]
can be combined in a single[<EndPoint>]
attribute: -
A common trick is to use
[<EndPoint "GET /">]
on an argument-less union case to indicate the home page. -
If several cases have the same
EndPoint
, then parsing tries them in the order in which they are declared until one of them matches: -
The method of an endpoint can be specified in a field's type, rather than the main endpoint type itself:
-
[<Query("arg1", "arg2", ...)>]
on a union case indicates that the fields with the given names must be parsed as GET query parameters instead of path segments. The value of this field must be either a base type (number, string) or an option of a base type (in which case the parameter is optional). -
You can of course mix Query and non-Query parameters.
-
Similarly,
[<Query>]
on a record field indicates that this field must be parsed as a GET query parameter.
-
[<Json "arg">]
on a union case indicates that the field with the given name must be parsed as JSON from the body of the request. If an endpoint type contains several[<Json>]
fields, a runtime error is thrown.Learn more about JSON parsing.
-
Similarly,
[<Json>]
on a record field indicates that this field must be parsed as JSON from the body of the request. -
[<FormData("arg1", "arg2", ...)>]
on a union case indicates that the fields with the given names must be parsed from the body as form data (application/x-www-form-urlencoded
ormultipart/form-data
) instead of path segments. The value of this field must be either a base type (number, string) or an option of a base type (in which case the parameter is optional). -
Similarly,
[<FormData>]
on a record field indicates that this field must be parsed from the body as form data. -
[<DateTimeFormat(string)>]
on a record field or named union case field of typeSystem.DateTime
indicates the date format to use. Be careful as some characters are not valid in URLs; in particular, the ISO 8601 round-trip format ("o"
format) cannot be used because it uses the character:
. -
[<Wildcard>]
on a union case indicates that the last argument represents the remainder of the url's path. That argument can be alist<'T>
, a'T[]
, or astring
.
Catching wrong requests with Sitelet.InferWithErrors
By default, Sitelet.Infer
ignores requests that it fails to parse, in order to give potential other middleware a chance to respond to the request. However, if you want to send a custom response for badly-formatted requests, you can use Sitelet.InferWithErrors
instead. This function wraps the parsed request in the ParseRequestResult<'EndPoint>
union. Here are the cases you can match against:
-
ParseRequestResult.Success of 'EndPoint
: The request was successfully parsed. -
ParseRequestResult.InvalidMethod of 'EndPoint * method: string
: An endpoint was successfully parsed but with the given wrong HTTP method. -
ParseRequestResult.MissingQueryParameter of 'EndPoint * name: string
: The URL path was successfully parsed but a mandatory query parameter with the given name was missing. The endpoint value contains a default value (Unchecked.defaultof<_>
) where the query parameter value should be. -
ParseRequestResult.InvalidJson of 'EndPoint
: The URL was successfully parsed but the JSON body wasn't. The endpoint value contains a default value (Unchecked.defaultof<_>
) where the JSON-decoded value should be. -
ParseRequestResult.MissingFormData of 'EndPoint * name: string
: The URL was successfully parsed but a form data parameter with the given name was missing or wrongly formatted. The endpoint value contains a default value (Unchecked.defaultof<_>
) where the form body-decoded value should be.
If multiple errors of these kinds occur, only the last one is reported.
If the URL path isn't matched, then the request falls through as with Sitelet.Infer
.
Other Constructors and Combinators
The following functions are available to build simple sitelets or compose more complex sitelets out of simple ones:
-
Sitelet.Empty
creates a sitelet which does not recognize any URLs. -
Sitelet.Content
, as shown in the first example, builds a sitelet that accepts a single URL and maps it to a given endpoint and content. -
Sitelet.Sum
takes a sequence of sitelets and tries them in order until one of them accepts the URL. It is generally used to combine a list ofSitelet.Content
s.The following sitelet accepts
/index
and/about
: -
+
takes two sitelets and tries them in order.s1 + s2
is equivalent toSitelet.Sum [s1; s2]
.
For the mathematically inclined, the functions Sitelet.Empty
and +
make sitelets a monoid. Note that it is non-commutative: if a URL is accepted by both sitelets, the left one will be chosen to handle the request.
-
Sitelet.Shift
takes a sitelet and shifts it by a path segment. -
Sitelet.Folder
takes a sequence of sitelets and shifts them by a path segment. It is effectively a combination ofSum
andShift
. -
Sitelet.Protect
creates protected content, i.e. content only available for authenticated users:Given a filter value and a sitelet,
Protect
returns a new sitelet that requires a logged in user that passes theVerifyUser
predicate, specified by the filter. If the user is not logged in, or the predicate returns false, the request is redirected to the endpoint specified by theLoginRedirect
function specified by the filter. See here how to log users in and out. -
Sitelet.Map
converts a sitelet to a different endpoint type using mapping functions in both directions. -
Sitelet.Embed
similarly converts a sitelet to a different endpoint type, but with a partial mapping function: the input endpoint type represents only a subset of the result endpoint type. -
Sitelet.EmbedInUnion
is a simpler version ofSitelet.Embed
when the mapping function is a union case constructor. -
Sitelet.InferPartial
is equivalent to combiningSitelet.Infer
andSitelet.Embed
, except the context passed to the infer function is of the outer endpoint type instead of the inner. For example, in the example forSitelet.Embed
above, the functionarticleContent
receives aContext<string>
and can therefore only create links to articles. Whereas withInferPartial
, it receives a fullContext<EndPoint>
and can create links toIndex
. -
Sitelet.InferPartialInUnion
is a simpler version ofSitelet.InferPartial
when the mapping function is a union case constructor. -
Sitelet.CorsContent
is a helper for creating a sitelet that serves content from a single endpoint with CORS (Cross-Origin Resource Sharing) checking enabled. It takes a URL, an endpoint, and content, and returns a sitelet that serves the content with the appropriate CORS headers.