WebSharper for C#

One language for the whole web app: C#

WebSharper compiles C# to modern JavaScript and writes the glue between the tiers for you: the endpoints, DTOs, fetch calls and serialization that a separate frontend needs. The server, the browser and the contract between them are written, typed and refactored in the same language, with async/await, LINQ and records on both sides.

$ dotnet new websharper-spa -lang C# -o MyApp
One C# project MyApp.csproj
Shared.cs Remoting.cs Client.cs Site.cs
dotnet build
Server

An ASP.NET Core app: sitelets, typed routes, RPC endpoints, auth and DI.

Browser

Readable ES2022 modules with native async, generators and classes, bundled for production.

Generated: RPC endpoints, client proxies, JSON 83 typed JS bindings

Debugging

Breakpoints in C#, all the way into the browser

Turn on source maps and the browser's developer tools show your C# files, not just the generated JavaScript. Pause on a line of Client.cs, step through it and inspect its variables, then step on into WebSharper's own libraries.

  • Browser: your .cs files in Chrome, Edge or Firefox DevTools, next to the sources of the libraries you use.
  • Server: the [Remote] method the client awaits stops in Visual Studio, Rider or VS Code, like any ASP.NET Core code.
  • One language in both debuggers: the same names, types and lines on each side of the call.
wsconfig.json "sourceMap": true
ElementsConsole Sources Network Paused on breakpoint

▾ localhost:5001

▾ Scripts/WebSharper

▾ Source

▾ Shop

Client.cs

Shared.cs

▸ WebSharper.UI

▸ WebSharper.StdLib

▸ Shop

Client.cs

15return new Template.Main.SearchForm()

16.OnSearch(async e =>

17{

18 // A remote call: arguments and results cross the wire typed.

19 results.Value = await Remoting.Search(e.Vars.Query.Value);

20})

21.Results(results.View.DocSeqCached(...))

Scope

Local e: {Vars: {…}, Target: …, Event: …}

Closure results: Var {…}

Your own files are copied next to the generated scripts, under Source/<Assembly>/, and the source map points there. Works for SPAs and for debug builds of client-server apps.

Why full-stack C#

Six reasons to write the frontend in C# too

If your backend is already in .NET, a separate TypeScript frontend means a second language, a second toolchain and a contract that can silently drift. Here's what you gain by writing both tiers in C#.

Built for AI-assisted development

Coding agents work best with a fast, strict feedback loop, and the C# compiler is one. Hallucinated members, wrong argument types and a client that's out of step with the server all fail dotnet build, so they never reach a browser.

  • Models have seen a huge amount of C#, and the code they write is checked by a compiler they can run.
  • A full feature fits in one context: the record, the endpoint and the UI that uses it, all in one language.
  • Typed bindings mean an agent can only call JavaScript APIs that actually exist, and our binding skill lets it generate new ones.
  • Every dotnet new template ships an AGENTS.md and agent skills, so your agent knows the project's conventions from the first prompt.

// agent: "add paging to product search"

agent › edit Client.cs

await Remoting.Search(query, page)

$ dotnet build

error CS1501: No overload for method

'Search' takes 2 arguments

Client.cs(14,25)

agent › edit Remoting.cs

[Remote] Search(string query, int page)

$ dotnet build

Build succeeded. Server and client agree.

Your agent can ask the compiler

dotnet ws mcp connects coding agents to the WebSharper Booster over MCP. Instead of guessing, the agent can look up what your last build reported, how a member translates to JavaScript and which RPC methods the server exposes.

WebSharper diagnostics C# → JS translation symbol search RPC methods

Booster Pro adds get_signature: exact C# signatures from your project and its references, with a warning when a .NET API has no JavaScript translation, so the agent doesn't write client code that can't compile.

// .mcp.json

{

"mcpServers": {

"websharper-csharp": {

"command": "dotnet",

"args": ["ws", "mcp",

"--lang", "csharp"]

}

}

}

Needs WebSharper 11 and the dotnet-ws tool. Build once to start the Booster and give it something to answer about.

Type safety from the database to the DOM

RPC calls, routes, HTML templates and JavaScript libraries are all typed. A misspelled template hole, a broken link or a renamed field is a compile error, not a support ticket. And Rename, Find All References and Go to Definition reach into the client code too, so long-lived apps stay easy to change.

One team, one skill set

Your .NET developers can ship whole features without handing off to a frontend team. Code review, hiring and onboarding all happen in one language, and there's no second package ecosystem to keep current.

What compiles behaves like .NET

Integer overflow wraps, exceptions keep their .NET types and decimal stays exact (through math.js). Where JavaScript can't follow .NET, such as reflection or culture-aware sorting, WebSharper leaves the API out instead of shipping a lookalike, and points you to the browser API to use.

322 of 339 conformance cases match

The .NET platform you already run

It's plain ASP.NET Core underneath, so your authentication, DI, EF Core, logging, NuGet feeds, CI and hosting all keep working. WebSharper is just another package in the project.

JavaScript you can read

No WebAssembly runtime to download and no opaque blob. You get ES modules whose classes and methods follow your C# closely, so you can read and step through them in the browser's developer tools. They come with TypeScript declarations too.

No glue code

Call the server like a local method

Mark a server method [Remote] and await it from the client. WebSharper generates the endpoint, the client proxy and the JSON, so you don't write routes, DTOs or fetch code.

1
Remoting.cs: an async server method that returns it.
2
Client.cs: a search box that awaits the call and renders a reactive list.
3
Shared.cs: a [JavaScript] record, used on both tiers.
4
Site.cs: a sitelet that renders the page on the server and hands the widget to the browser.
using WebSharper;

namespace Shop;

public static class Remoting
{
    static readonly Product[] Catalog = {
        new("Keyboard", 49.0),
        new("Monitor", 189.0),
        new("Mouse", 19.0)
    };

    // A typed server function; the client calls it like a local method.
    [Remote]
    public static Task<Product[]> Search(string query) =>
        Task.FromResult(Catalog
            .Where(p => p.Name.Contains(query, StringComparison.OrdinalIgnoreCase))
            .ToArray());
}

The compiler

C# in, idiomatic JavaScript out

WebSharper reads your code through Roslyn and translates C#'s semantics, not just its syntax. Pick a feature to see what WebSharper 11 emits for it. The output below is real compiler output, reformatted only.

C#
public async Task<int> CountDown()
{
    var i = 0;
    while (i < 10)
    {
        await Task.Delay(100);
        i++;
    }
    return i;
}
JavaScript (WebSharper 11)
CountDown() {
  return Task.FromAsync(async () => {
    let i = 0;
    while (i < 10) {
      await Task.Delay_1(100);
      i++;
    }
    return i;
  });
}

WebSharper 10 compiled a method like this to a hand-written state machine of about 50 lines. WebSharper 11 keeps your loop and your awaits, and wraps the async function in a .NET-compatible Task, so exceptions and continuations behave as in .NET.

Also translated

records & record structs pattern matching & switch expressions tuples & deconstruction local functions & lambdas interpolated strings with formats delegates & events generics & interfaces exceptions with try/catch/finally nullable value types System.Collections.Generic
322 / 339

Checked against .NET. A conformance suite runs the same C# on .NET and as JavaScript and compares the output on every build. The other 17 cases are known JavaScript differences, each with what to write instead.

See every case →

TypeScript interop

Typed for TypeScript, too

Next to every JavaScript module, WebSharper writes a .d.ts declaration file. It's on by default. Your C# types, default parameters and return types reach TypeScript intact, so a TypeScript codebase can call your C# with full type checking and editor completion.

  • 1 Adopt it one module at a time. You don't need to rewrite your React or Angular frontend. Compile a C# module and import it from the TypeScript you already have.
  • 2 Write the rules once. Pricing, validation and permission logic live in one C# source that runs on the server and ships, typed, to the browser. The two copies can't drift apart.
  • 3 Publish to npm. Set "javascriptExport": true in wsconfig.json and you get a dead-code-eliminated folder with an index.js and an index.d.ts, ready for npm pack.
  • 4 Keep the safety net. When the C# signature changes, tsc flags every TypeScript call site that no longer fits, and coding agents get the same errors on both sides of the boundary.
C# Pricing.cs
[JavaScript]
public record LineItem(string Sku, double UnitPrice, int Quantity = 1)
{
    public double Subtotal => UnitPrice * Quantity;
}

[JavaScript]
public static class Cart
{
    public static double Total(LineItem[] items,
        double taxRate = 0.2, string coupon = null) { ... }

    public static string[] Skus(LineItem[] items) => ...
}
d.ts Pricing.*.d.ts generated
// Pricing.LineItem.d.ts
export default class LineItem {
  Sku: string;
  UnitPrice: number;
  Quantity: number;
  get Subtotal(): number
  Equals(obj: any): boolean
  ...
}

// Pricing.Cart.d.ts
export function Total(
  items: LineItem[],
  taxRate?: number,
  coupon?: string
): number

export function Skus(
  items: LineItem[]
): string[]
TS checkout.ts
import { Total, LineItem } from "pricing";
declare const cart: LineItem[];

Total(cart, 0.2, "WELCOME10"); // ok
cart[0].Subtotal; // ok
Total(cart, "20%");
// TS2345: 'string' is not assignable
//   to parameter of type 'number'
cart[0].Prise;
// TS2339: Property 'Prise' does not
//   exist on type 'LineItem'

Real WebSharper 11 output and real tsc --strict errors, excerpted and reformatted. Records come through as classes with their properties, computed members and equality.

Reactive UI

HTML templates become typed C# classes

Designers keep plain HTML. At build time every ws-hole, ws-var and event in it becomes a C# member, and .Bind() wires it to reactive Vars. This is the real app; open the Preview tab.

using WebSharper;
using WebSharper.UI;
using WebSharper.UI.Client;

namespace CSharpTasks;

[JavaScript]
public static class App
{
    [SPAEntryPoint]
    public static void ClientMain()
    {
        // Reactive state: the page updates itself when these change.
        var tasks = ListModel.FromSeq(new[] {
            "Write the UI in C#",
            "Let WebSharper compile it to JavaScript"
        });
        var newTask = Var.Create("");

        new Template.Index()
            .Tasks(tasks.View.DocSeqCached((string task) =>
                new Template.Index.TaskItem()
                    .Title(task)
                    .Done(() => tasks.Remove(task))
                    .Doc()
            ))
            .NewTask(newTask)
            .Add(() =>
            {
                var title = newTask.Value.Trim();
                if (title != "") tasks.Add(title);
                newTask.Value = "";
            })
            .Remaining(tasks.View.Map(ts => $"{ts.Count()} to go"))
            .Bind();
    }
}
Terminal
> dotnet run
Building...
info: Now listening on: http://localhost:5100
info: Application started. Press Ctrl+C to shut down.
█

Ecosystem

The entire WebSharper ecosystem, from C#

Every WebSharper library and binding is a regular NuGet package with typed classes, IntelliSense and doc comments, and it works the same from C# as from F#. Charts, maps, editors, 3D and the newest browser APIs are a dotnet add package away.

42

JavaScript libraries

41

browser APIs

  • Mix C# and F# projects in one solution: WebSharper.UI and every binding are shared by both languages.
  • The modernized bindings pull their library from npm, so your bundler resolves and pins it like any other dependency.
  • Missing a library? Describe it with the Interface Generator, or let an agent write the binding.
Browse all bindings

Start in a minute

A new app

Install the templates and create a C# single-page app.

$ dotnet new install WebSharper.Templates

$ dotnet new websharper-spa -lang C# -o MyApp

An existing ASP.NET Core app

Add the compiler and the ASP.NET Core integration to the project.

$ dotnet add package WebSharper.CSharp

$ dotnet add package WebSharper.AspNetCore

C# for reach, F# for power: F# is WebSharper's original language and its most expressive one, with the same libraries and bindings. See WebSharper in F# →