WebSharper Core

Your first full-stack app

Build a small expense tracker with a server API, a reactive UI and a Chart.js chart from NuGet.

This guide builds Spend Tracker, a small full-stack app where you log expenses and see where your money goes. You will use the main pieces of WebSharper along the way:

  • a sitelet that serves the page,
  • remote procedure calls ([<Rpc>]) that let the browser call server code as if it were local,
  • reactive UI with Var, View and ListModel, bound to an HTML template,
  • a JavaScript library binding from NuGet (WebSharper.ChartJs) to draw a chart.

The finished Spend Tracker app

Want to see it first? Try the finished app right here on this page.

WebSharper 11 preview

This guide targets the WebSharper 11 preview, which needs the .NET 11 SDK. You also need Node.js: WebSharper uses npm packages for JavaScript libraries, Vite to serve them while you develop, and esbuild to bundle them for release.

Create the app

Install the WebSharper 11 templates (see Getting started for what each template does), then create a client-server application:

dotnet new install WebSharper.Templates::11.0.0.781-preview.2
dotnet new websharper-web -lang F# -n SpendTracker
cd SpendTracker
dotnet run

Open the URL printed in the terminal. You get a page with a text box that sends your input to the server and shows the reversed text. That round trip is already a working full-stack app. Here is where its pieces live:

FileWhat it holds
Site.fsThe endpoints (EndPoint) and the server-side page for each one.
Remoting.fsServer functions marked [<Rpc>], callable from the browser.
Client.fsCode marked [<JavaScript>], compiled to JavaScript and run in the browser.
Main.htmlThe HTML template. ws-hole, ws-var, ws-onclick and ${...} mark the places your code fills in.
wsconfig.jsonWebSharper compiler settings (see wsconfig.json).

Stop the app with Ctrl+C before you continue.

Define the data and the server API

Replace the contents of Remoting.fs with an Expense record and three server functions. The store is in memory, which keeps the guide short; swap it for a database later.

Remoting.fs
namespace SpendTracker
 
open System.Collections.Concurrent
open System.Threading
open WebSharper
 
[<JavaScript>]
type Expense =
    {
        Id: int
        Description: string
        Category: string
        Amount: float
    }
 
module Server =
 
    // An in-memory store: fine for a tutorial, swap in a database later.
    let private store = ConcurrentDictionary<int, Expense>()
    let mutable private lastId = 0
 
    let private add description category amount =
        let id = Interlocked.Increment &lastId
        let expense = { Id = id; Description = description; Category = category; Amount = amount }
        store[id] <- expense
        expense
 
    do
        add "Groceries" "Food" 54.20 |> ignore
        add "Train pass" "Transport" 32.00 |> ignore
        add "Cinema" "Fun" 18.50 |> ignore
        add "Electricity" "Housing" 64.90 |> ignore
        add "Lunch with Sam" "Food" 12.80 |> ignore
 
    [<Rpc>]
    let GetExpenses () : Async<Expense[]> =
        async {
            return store.Values |> Seq.sortBy (fun e -> e.Id) |> Array.ofSeq
        }
 
    [<Rpc>]
    let AddExpense (description: string) (category: string) (amount: float) : Async<Expense> =
        async {
            return add description category amount
        }
 
    [<Rpc>]
    let DeleteExpense (id: int) : Async<unit> =
        async {
            store.TryRemove id |> ignore
        }

Expense is marked [<JavaScript>] so the browser can use the same type. The [<Rpc>] functions run on the server; WebSharper generates the client-side stubs and the JSON serialization for their arguments and results.

Lay out the page

Replace the contents of Main.html with the page below, and add a stylesheet for it as wwwroot/site.css (files in wwwroot are served as they are):

Main.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${Title} · Spend Tracker</title>
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link href="/site.css" rel="stylesheet" />
  </head>
  <body>
    <nav class="st-nav navbar navbar-expand py-3">
      <div class="container">
        <a class="st-brand" href="/"><span class="st-logo">$</span> Spend Tracker</a>
        <ul class="navbar-nav ms-4 me-auto" ws-hole="MenuBar"></ul>
        <a class="nav-link" href="https://websharper.com">Built with WebSharper</a>
      </div>
    </nav>
    <main class="container py-4">
      <div ws-replace="Body">
        <div ws-template="ExpenseForm">
          <header class="st-header mb-4">
            <h1>Where did my money go?</h1>
            <p>Log your expenses and see your spending by category.</p>
          </header>
          <div class="row g-3 mb-3">
            <div class="col-4">
              <div class="st-card">
                <div class="st-stat-label">Total spent</div>
                <div class="st-stat-value">${Total}</div>
              </div>
            </div>
            <div class="col-4">
              <div class="st-card">
                <div class="st-stat-label">Expenses</div>
                <div class="st-stat-value">${Count}</div>
              </div>
            </div>
            <div class="col-4">
              <div class="st-card">
                <div class="st-stat-label">Top category</div>
                <div class="st-stat-value">${TopCategory}</div>
              </div>
            </div>
          </div>
          <div class="row g-3">
            <div class="col-lg-7">
              <div class="st-card">
                <h2>Add an expense</h2>
                <div class="st-form row g-2 mb-4">
                  <div class="col-sm-5">
                    <input class="form-control" placeholder="Description" ws-var="Description" />
                  </div>
                  <div class="col-sm-3">
                    <select class="form-select" ws-var="Category">
                      <option>Food</option>
                      <option>Transport</option>
                      <option>Housing</option>
                      <option>Fun</option>
                    </select>
                  </div>
                  <div class="col-sm-2">
                    <input class="form-control" placeholder="0.00" inputmode="decimal" ws-var="Amount" />
                  </div>
                  <div class="col-sm-2 d-grid">
                    <button class="btn btn-primary" ws-attr="AddAttr" ws-onclick="OnAdd">Add</button>
                  </div>
                </div>
                <table class="table st-table">
                  <thead>
                    <tr><th>Description</th><th>Category</th><th class="text-end">Amount</th><th></th></tr>
                  </thead>
                  <tbody ws-hole="Rows">
                    <tr ws-template="Row">
                      <td>${Description}</td>
                      <td><span class="st-pill" data-category="${Category}">${Category}</span></td>
                      <td class="st-amount">${Amount}</td>
                      <td class="text-end">
                        <button class="st-delete" title="Delete" ws-onclick="OnDelete">&times;</button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="col-lg-5">
              <div class="st-card">
                <h2>Spending by category</h2>
                <div ws-hole="Chart"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="st-footer container pb-4">
      Made with <a href="https://websharper.com">WebSharper</a> and <a href="https://www.chartjs.org">Chart.js</a>.
    </footer>
    <script ws-replace="scripts"></script>
  </body>
</html>

The page keeps the holes the template's Site.fs fills (${Title}, MenuBar, Body and scripts), and adds an ExpenseForm template for the home page. Each ws-* attribute and ${...} placeholder in it becomes a typed method on the generated template class: ws-var="Description" becomes .Description(var), ws-onclick="OnAdd" becomes .OnAdd(handler), and the nested ws-template="Row" becomes its own MainTemplate.Row() class.

Make the list reactive

Replace Client.Main in Client.fs with the code below. Keep the Templates module at the top of the file as it is.

Client.fs
[<JavaScript>]
module Client =
 
    let Main () =
        // The expenses shown on the page, keyed by Id.
        let expenses = ListModel.Create (fun (e: Expense) -> e.Id) []
        async {
            let! xs = Server.GetExpenses()
            expenses.Set xs
        }
        |> Async.StartImmediate
 
        // Recomputed every time the list changes.
        let total =
            expenses.View
            |> View.Map (fun xs -> xs |> Seq.sumBy (fun e -> e.Amount) |> sprintf "%.2f")
        let count =
            expenses.View |> View.Map (Seq.length >> string)
        let topCategory =
            expenses.View
            |> View.Map (fun xs ->
                if Seq.isEmpty xs then "–"
                else
                    xs
                    |> Seq.groupBy (fun e -> e.Category)
                    |> Seq.maxBy (fun (_, es) -> Seq.sumBy (fun e -> e.Amount) es)
                    |> fst)
 
        // The form fields.
        let description = Var.Create ""
        let category = Var.Create "Food"
        let amount = Var.Create ""
        let canAdd =
            View.Map2 (fun (d: string) (a: string) ->
                d.Trim() <> "" && (match System.Double.TryParse a with | true, v -> v > 0.0 | _ -> false))
                description.View amount.View
 
        Templates.MainTemplate.ExpenseForm()
            .Description(description)
            .Category(category)
            .Amount(amount)
            .AddAttr(Attr.DynamicPred "disabled" (View.Map not canAdd) (View.Const "disabled"))
            .OnAdd(fun _ ->
                async {
                    let! expense =
                        Server.AddExpense description.Value category.Value (float amount.Value)
                    expenses.Add expense
                    description.Value <- ""
                    amount.Value <- ""
                }
                |> Async.StartImmediate)
            .Rows(
                expenses.View
                |> Doc.BindSeqCached (fun expense ->
                    Templates.MainTemplate.Row()
                        .Description(expense.Description)
                        .Category(expense.Category)
                        .Amount(sprintf "%.2f" expense.Amount)
                        .OnDelete(fun _ ->
                            async {
                                do! Server.DeleteExpense expense.Id
                                expenses.RemoveByKey expense.Id
                            }
                            |> Async.StartImmediate)
                        .Doc()))
            .Total(total)
            .Count(count)
            .TopCategory(topCategory)
            .Doc()

There is no code that updates the table or the total by hand:

  • a Var holds a value and a View observes it. The form fields are Vars bound with ws-var, so typing updates them and setting them (description.Value <- "") clears the input.
  • a ListModel is a reactive collection. Doc.BindSeqCached renders a Row per item and re-renders only the rows that change.
  • total, count, topCategory and canAdd are derived views. The Add button is disabled until there is a description and a positive amount.

Finally, in Site.fs, the heading now lives in the template, so make the home page body just the client-side part:

Site.fs
    let HomePage ctx =
        Content.Page(
            Templating.Main ctx EndPoint.Home "Home" [
                client (Client.Main())
            ],
            Bundle = "home"
        )

Run the app with dotnet run: you can now add and delete expenses, and the summary cards keep up.

Add a chart binding from NuGet

WebSharper talks to JavaScript libraries through bindings: NuGet packages that describe a library's API in .NET types. Add the Chart.js binding, and Chart.js itself from npm:

dotnet add package WebSharper.ChartJs --prerelease
npm install chart.js

The binding imports Chart.js as an ES module (chart.js/auto). In development, Vite serves it from node_modules; in a Release build, esbuild bundles it into your page's script. Browse the other bindings in the WebSharper bindings catalog.

Draw spending by category

Add a Charts module to Client.fs, between Templates and Client, and open the namespaces it needs at the top of the file:

Client.fs
open WebSharper.JavaScript
open WebSharper.UI.Html
open WebSharper.UI.Client
open WebSharper.ChartJs
 
// ...
 
[<JavaScript>]
module Charts =
 
    /// The colour of each category, matching the pills in Main.html.
    let ColorOf category =
        match category with
        | "Food" -> "#36b9ff"
        | "Transport" -> "#ff7a59"
        | "Housing" -> "#8b5cf6"
        | "Fun" -> "#ffb020"
        | _ -> "#6b7385"
 
    /// A doughnut chart of the total spend per category, kept in sync with `expenses`.
    let ByCategory (expenses: View<seq<Expense>>) =
        let dataSet = DoughnutChartDataSet(Label = "Spend", BorderWidth = 2, HoverOffset = 6)
        let data = ChartData(Datasets = [| dataSet |])
        let options =
            PieDoughnutChartOptions(
                MaintainAspectRatio = false,
                Cutout = "68%",
                Plugins = Plugin(
                    Legend = LegendConfig(
                        Position = PositionString.Bottom,
                        Labels = LabelConfig(UsePointStyle = true, Padding = 16)
                    )
                )
            )
        div [attr.style "height: 300px"] [
            canvas [
                on.afterRender (fun el ->
                    let chart = Chart(el, ChartCreate(data, options, Type = ChartType.Doughnut))
                    expenses
                    |> View.Sink (fun xs ->
                        let totals =
                            xs
                            |> Seq.groupBy (fun e -> e.Category)
                            |> Seq.map (fun (category, es) -> category, Seq.sumBy (fun e -> e.Amount) es)
                            |> Array.ofSeq
                        data.Labels <- Array.map fst totals
                        dataSet.Data <- Array.map snd totals
                        dataSet.BackgroundColor <- Union2Of2 (Array.map (fst >> ColorOf) totals)
                        chart.Update()))
            ] []
        ]

Then fill the template's Chart hole, just before .Doc() in Client.Main:

Client.fs
            .TopCategory(topCategory)
            .Chart(Charts.ByCategory expenses.View)
            .Doc()

This is the general recipe for driving any JavaScript widget from WebSharper's reactive model:

  • on.afterRender creates the widget once its element is in the page. Chart.js needs a mounted <canvas>.
  • View.Sink runs a callback with the current value and again on every change. Here it regroups the expenses, writes the new labels, values and colours into the chart's data, and calls chart.Update().

Type = ChartType.Doughnut tells Chart.js which chart type's defaults to use, so the legend lists the categories. PieDoughnutChartOptions adds the doughnut-specific options, such as the size of the hole (Cutout), and ColorOf gives each category the same colour as its pill in the table.

Run dotnet run again. Adding or deleting an expense now updates the table, the total and the chart together.

Build for release

dotnet publish -c Release -o out

A Release build runs npm install and the esbuild step from esbuild.config.mjs, which bundles your client code, WebSharper's runtime and Chart.js into one script per page under out/wwwroot/Scripts/WebSharper/. Run the published app with:

dotnet out/SpendTracker.dll

Try it live

Here is the finished app. This page has no server behind it, so the live version swaps the [<Rpc>] functions of Remoting.fs for a Server module with the same signatures that keeps the expenses in the browser. The Charts and Client code is the same as above.

Where to go next

On this page