Skip to content

About

Opinionated open-source dashboard starter: React + TypeScript, ASP.NET Core (C#), and SQL Server. Built in public.

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

dashboard-starter

An opinionated, open-source dashboard starter for building real business apps with React, C# / ASP.NET Core, and SQL Server.

Clone it, rename it, and start on your actual product instead of rebuilding auth, layout, and plumbing for the tenth time.

Live demo: dashboard.mvmorten.com. It's deployed from main on every merge, so it always shows the latest step. Click Try the demo on the sign-in page and you get your own private sandbox: an account and two tenants with sample members and customers, which nobody else can see. You're an Admin in "Demo", so everything there works for real, and Read-only in "Other Demo": switch between them at the top to see the same person with different permissions. A sandbox is deleted after 2 hours without use, 24 hours at most, or when you sign out.

Status: Just getting started. This project is being built in public, and every step is documented in a blog series. Expect the code to change quickly while the foundation takes shape.


Why this exists

Most starter templates fall into one of two camps: a pretty UI with no real backend, or a backend sample with no usable front end. Very few show how a full production app fits together end to end, and fewer still explain why each decision was made.

This project is for developers who want to understand the whole stack. You should be able to follow any feature from a React component, through the API, to the exact SQL it runs, without digging through framework internals. Most of the choices below follow from that: when a tool does a lot of work you can't see, we usually pick the plainer option you can read.

This repo aims to be:

  • Usable. A working dashboard you can fork and ship on.
  • Opinionated. One clear way to do things, not a menu of every option.
  • Explained. Every major decision is written up in the accompanying blog posts, so you can disagree with it knowingly.

The stack

Layer Choice
Front end React + TypeScript, built with Vite. Plain CSS (no UI kit), React Router for pages, TanStack Query for server data
API ASP.NET Core Web API with controllers (C#, current .NET LTS)
Database SQL Server, one shared database for all tenants
Data access Dapper, with hand-written SQL inline in C#
Schema changes Idempotent SQL scripts in /sql, applied by an explicit command
Multi-tenancy TenantId on every tenant-owned table, backed by SQL Server Row-Level Security
Auth Our own user tables, Argon2id password hashing, ASP.NET Core cookie authentication
Email Resend's REST API through a plain HttpClient, behind an IEmailSender interface; locally, emails are text files in .dev-mail/
Local dev Docker Compose runs SQL Server only; the API and front end run natively
CI and deploy GitHub Actions: build, lint, and schema checks on every pull request; deploy on every merge to main
Hosting Azure App Service (Linux) serving the API and the React build, Azure SQL Database, both created from Bicep in /infra

Multi-tenancy

  • One shared database, many tenants. One schema, one migration run, one backup, one connection string. That's the economy of scale that makes SaaS work. See the FAQ for why not one database per tenant.
  • One account, many tenants. A person signs in once and can belong to several tenants. Nobody wants a separate account for every organization they work with.
  • Global tables have no TenantId: Users, Tenants, TenantUsers, and the role definitions (Roles, RolePermissions). Your account, email (unique across the system), password hash, and lockout state belong to you, not to any one tenant.
  • Everything else is tenant-owned: it carries a TenantId, the TenantId leads its indexes, and every query filters by the current tenant.
  • Row-Level Security is the safety net. The API puts the current tenant in SESSION_CONTEXT on each connection, and a security policy filters every tenant-owned table. A query that forgets its WHERE TenantId = @TenantId still can't see another tenant's rows, or write to them. See "Row-Level Security" below.
  • Roles are per tenant. You can be an admin in one tenant and read-only in another: each membership in TenantUsers has exactly one RoleId. See "Roles and permissions" below.
  • Switching tenants. With one tenant you go straight in. With several, you land in the one you used last and can switch from the top bar. The auth cookie holds your user and current tenant; switching checks your membership and issues a new cookie.
  • Removing access works right away. Memberships can be disabled per tenant, and the API rechecks membership on each request, cached for at most a minute (Auth:SessionCheckSeconds). The same check ends every session of a user whose password changed or who is locked out.
  • The development seed creates two sample tenants, Acme Corporation and Globex Industries, and a local account in both (admin@example.com). A real deployment starts empty: create your first tenant, and if your app only ever needs one, you can ignore the rest.

Roles and permissions

  • Code checks permissions, never role names. A permission is an area and an action: members.view, members.manage. They're all listed in one file, src/Db/Authorization/Permissions.cs, each with a line saying what it allows.

  • A role is a named set of permissions, defined in the database by a migration (sql/migrations/0009_roles.sql) and the same in every tenant. There's no screen for editing roles: they're part of the app's design, like its tables.

    Role Permissions
    Admin members.view, members.manage, customers.view, customers.edit
    Member members.view, customers.view, customers.edit
    Read-only members.view, customers.view

    The CRUD module (Customers) is where Member and Read-only differ: both can look, only Member and Admin can change. customers.edit covers delete too; a fork that wants delete separate adds customers.delete with one migration (sql/migrations/0014_customer_permissions.sql shows how).

  • One role per membership. It's a RoleId column on TenantUsers rather than a separate table, so "exactly one role in each tenant" is kept by the schema itself. New memberships get Member unless you say otherwise.

  • The API checks every request. Controllers say [Authorize(Policy = Permissions.MembersManage)], and one small handler we own (src/Api/Auth/PermissionHandler.cs) answers it. The permissions come from the database with the per-request session check (cached for at most Auth:SessionCheckSeconds), never from the cookie, so a changed role or a disabled membership takes effect within a minute, and usually on the very next request when it's changed on the Members page. Not signed in is a 401; signed in without the permission is a 403.

  • The UI only hides things. /api/auth/me returns your permissions in the current tenant, and one helper, can(permission) (src/Web/src/auth/permissions.ts), hides menu items and buttons you can't use. That's a convenience; the API is the check.

  • Every tenant keeps an admin. You can't change your own role or disable yourself, and no change may leave a tenant without an active member who can manage members. The rule is in one place (src/Db/Users/Memberships.cs), used by the API and the Db runner, and runs in one transaction with the change, under a lock on the tenant, so two admins demoting each other at once can't both succeed.

  • Adding a permission in a fork: add a constant to Permissions.cs (and to the front end's copy in permissions.ts if the UI needs it), write a migration that grants it to the roles that should have it, and put [Authorize(Policy = ...)] on the endpoints. CI fails if the code and the database don't list the same permissions.

Demo sandboxes

A public demo needs a way in without an account. Step 7 used one shared account with a published password, which meant switching off anything a visitor could change, and every visitor saw what the last one typed. Now each visitor gets their own sandbox (src/Api/Demo).

  • "Try the demo" posts to an anonymous endpoint (POST /api/demo/sandbox) that creates, in one transaction, a user and two tenants ("Demo", where they're Admin, and "Other Demo", where they're Read-only), plus four sample members who are rows of this sandbox only, and sample customers in each tenant (30 businesses in "Demo", 27 people in "Other Demo": more than a page each, and different, so switching tenants shows they're separate). Then it signs them in with the normal cookie. What a sandbox contains is defined in one file, SandboxDefinition.cs.
  • Demo rows are marked. Users.IsDemo and Tenants.IsDemo, and an ExpiresAt on both. A check constraint allows ExpiresAt on demo rows only, so a real tenant or user can never expire. Sandbox addresses are on demo.invalid, a domain reserved so it can't belong to anyone.
  • A sandbox can't become a real account. It has no password and can't get one: change password, password reset, and the Db runner's set-password all refuse demo users, and there's no way to change an email. Inside its own tenants, though, it's a normal account: the visitor can change members' roles and disable them.
  • Expiry. A sandbox lasts 2 hours without use and 24 hours at most (Demo:SandboxIdleMinutes, Demo:SandboxHours). Each session check, at most once a minute, moves the expiry forward; signing out ends it at once, since there's no password to come back with. An expired sandbox's session ends on its next request.
  • Limits on the anonymous endpoint. The usual antiforgery token, 10 new sandboxes per client address per hour (ASP.NET Core's built-in rate limiter, per IPv4 address or IPv6 /64, behind App Service's forwarded headers), and at most 500 active at once, after which the button says "The demo is busy, try again later." The idle expiry is what keeps the cap honest: filling it takes steady work rather than one burst, because a sandbox nobody uses is gone in two hours.
  • A row cap. A demo tenant holds at most 200 customers (Demo:MaxCustomersPerTenant), and deleted ones count, so adding and deleting in a loop can't grow the table. It's checked in the same transaction as the insert, under a lock on the tenant row, and past it the API answers 422 with a plain message. Real tenants have no cap.
  • Cleanup is background work. A BackgroundService in the API (SandboxCleanupService) runs every hour, and once at startup, on a built-in PeriodicTimer. It deletes expired demo tenants and users and every row they own, logging each run. With several App Service instances, sp_getapplock lets one clean at a time. It works on each tenant's rows with that tenant set in SESSION_CONTEXT, as a request does, so Row-Level Security applies to it too: no login is exempt.
  • Adding a table? If it has a TenantId column, or a foreign key to Users or Tenants, add it to SandboxCleanup.TenantRows or SandboxCleanup.UserRows. With sandboxes on, the API refuses to start until you do, naming the column, and CI proves that check works.
  • Off by default. A fork doesn't get an anonymous button that creates accounts unless it asks: with Demo:SandboxesEnabled false, the button is hidden, the endpoint is a 404, and the cleanup service doesn't run. Development turns it on; the deploy turns it on when the repo variable DEMO_ENABLED is true.

Database conventions

  • Dapper, not an ORM. Queries are plain SQL you can read, tune, and run in SSMS.

  • Inline SQL, parameters only. Queries live in the C# that uses them, written as raw string literals ("""). Values always go in as parameters, never with $ string interpolation. Dynamic pieces, like a sortable column, come only from a fixed list in code, never straight from user input.

  • Stored procedures only where they help, such as set-based batch work or heavy reporting. See the FAQ.

  • Keys: int identity on every table, bigint on tables that grow without limit (audit log, events). Links that must be unguessable, like password resets and invites, use random tokens, not IDs.

  • Standard columns on every tenant-owned table. Customers (sql/migrations/0013_customers.sql) is the one to copy:

    Column
    TenantId Whose row it is. Leads every index except the primary key, and Row-Level Security filters on it.
    CreatedAt, CreatedBy When and by whom it was made (datetime2, UTC; a user id).
    UpdatedAt, UpdatedBy The last change.
    DeletedAt, DeletedBy Soft delete: NULL until the row is deleted.
    RowVersion rowversion, for optimistic concurrency.

    The *By columns are NULL when no person did it (a data migration, an import). They're always set from the signed-in user, never from the request.

  • Soft delete. Deleting sets DeletedAt and DeletedBy; the row stays, for the audit log step. Every app query says AND DeletedAt IS NULL explicitly, updates included, rather than reading through a view that hides deleted rows: you can see it's there in every query, and CI proves it by calling every endpoint on a deleted row. A deleted row is a 404 everywhere. Filtered indexes (WHERE DeletedAt IS NULL) keep deleted rows out of the indexes the list reads. (Deleting a demo sandbox removes its rows for real; that's cleanup, not the app.)

  • Optimistic concurrency with rowversion. Every read returns the row's version, base64 in JSON. Every change and delete sends it back in the request body, and the UPDATE includes it: WHERE Id = @Id AND TenantId = @TenantId AND RowVersion = @RowVersion AND DeletedAt IS NULL, with OUTPUT inserted.RowVersion. Zero rows changed means one of two things, and the API tells them apart: the row is gone or deleted (404), or someone else saved first (409 Conflict). A 409 is ProblemDetails with the current rowVersion and the current record as extensions, so the client can show what changed and merge without asking again. 409 means only "someone else changed this"; other refusals use other codes. Always write rowversion, never timestamp: same type, but timestamp is the old name and looks like a date.

  • History: system-versioned temporal tables keep every past version of a row, so the audit log doesn't depend on triggers.

Row-Level Security

  • One script holds the policy and its predicate, sql/programmable/Security.fn_TenantAccessPredicate.sql. It drops the policy, alters the function, and creates the policy again, listing every tenant-owned table with a filter predicate (reads, and which rows an UPDATE or DELETE can find) and two block predicates (no inserting into, or moving a row to, another tenant). The runner runs it in one transaction, so no table is ever unprotected.

  • It fails closed. No tenant in SESSION_CONTEXT, no rows: a query sees nothing, an INSERT is refused, an UPDATE changes nothing.

  • Nobody is exempt, not the API's login, not the admin login the Db runner uses. Work that isn't a request sets the tenant itself: the demo sandbox cleanup works on each tenant's rows in that tenant's context, and so does the Db runner (below).

  • It's the safety net, not the filter. Queries still say WHERE TenantId = @TenantId, and the policy doesn't hide soft-deleted rows (AND DeletedAt IS NULL does).

  • Adding a tenant-owned table? Add its three lines to the policy, and add it to SandboxCleanup.TenantRows (src/Api/Demo/SandboxCleanup.cs). CI fails if a table with a TenantId column is missing from the policy. TenantUsers is the one exception: a global table that happens to have a TenantId.

  • Data migrations on a tenant-owned table start with -- for-each-tenant. Written the obvious way, UPDATE dbo.Customers SET ... runs with no tenant set, so Row-Level Security shows it no rows, and it "succeeds" having changed nothing. Nothing fails, so nothing tells you. With -- for-each-tenant as its first line, the runner runs the migration once per tenant, with that tenant in SESSION_CONTEXT, all in one transaction (TenantSession.ForEachTenantAsync in src/Db/Tenants): if it fails in any tenant, it's rolled back in all of them, and the error names the tenant. Keep schema changes in their own migration before it, and filter by the tenant you're in:

    -- for-each-tenant
    UPDATE dbo.Customers
    SET Status = 'Inactive'
    WHERE TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS int)
      AND Status = 'Dormant';

Schema scripts

/sql
  /migrations     run once, in order: tables, columns, indexes, data fixes
  /programmable   rerun every time: views, functions, procs, RLS predicates
  /seed           development only: sample data (the local account is made in C#, see below)
  • Migrations are numbered (0001_tenants.sql, 0002_users.sql, ...) and idempotent: each checks before it changes (IF NOT EXISTS, IF COL_LENGTH(...) IS NULL), so running one twice is safe. Once a migration has run, it's never edited. A change is a new script.

  • Programmable objects use CREATE OR ALTER and are edited in place. The file is the definition.

  • Applying them is a command you run on purpose:

    dotnet run --project src/Db -- migrate    # migrations + programmable objects
    dotnet run --project src/Db -- seed       # development only
    

    The runner records each migration in a SchemaVersions table with a hash of its contents, skips ones already applied, and fails loudly if an applied script was edited. The same command runs on your laptop, in CI, and in deployment.

  • The API never changes the database. On startup it only checks that the schema is current. If it isn't, it refuses to start and tells you which command to run.

  • Running a copied query in SSMS? Set the tenant first, or Row-Level Security will return no rows (even as sa):

    EXEC sp_set_session_context @key = N'TenantId', @value = 1;

The CRUD example: Customers

Customers is the sample module: the pattern to copy for your own tenant-owned records, from the table to the screen. Each layer is one place: the table in sql/migrations/0013_customers.sql, the SQL in src/Api/Customers/CustomerStore.cs, the endpoints in CustomersController.cs, the field rules in CustomerValidation.cs, the form's copy of those rules in src/Web/src/customers/rules.ts, the calls in customers.ts, and the pages in src/Web/src/pages/Customers.tsx (the list) and Customer.tsx (the form, with its parts in pages/customer/).

Endpoint Needs
GET /api/customers?search=&status=&sort=&dir=&page= customers.view 25 a page, with the total. search matches the start of a name or email; %, _ and [ match only themselves. status: Active or Inactive (none for both). sort: name (the default), email, status, updated or created; dir: asc (the default) or desc. Ties go by id, in the same direction. Any other value is a 400 that names it.
GET /api/customers/{id} customers.view One customer, with its rowVersion.
POST /api/customers customers.edit 201 with the new customer.
PUT /api/customers/{id} customers.edit The fields and the rowVersion you loaded. 200, 404, or 409 with the current record.
DELETE /api/customers/{id} customers.edit Soft delete; the rowVersion goes in the body. 204, 404, or 409.
  • Validation is on the server: 400 with ProblemDetails errors keyed by field (name, email, ...). Text is trimmed, an empty optional field is stored as NULL, and the lengths are the column lengths. The form checks the same rules first, so mistakes show without a round trip (see "Forms" below), but the server has the final word.
  • Email isn't unique. Two customers can share an address (a family, a shared inbox). User accounts are different: Users.Email is unique, because it's how you sign in.
  • The list (/customers) is the data grid (below): a table on a wide screen and cards on a phone, with a search box, a status filter, sorting, and 25 a page. All of it is in the URL, so Back, a reload and a shared link show the same page.
  • The form (/customers/new, /customers/{id}) is built from the shared field components (see "Forms" below) and checks the rules before it saves. Without customers.edit the same page shows the fields to read, and there's no "New customer" button. Delete asks once, on the page. Leaving with unsaved changes asks first: closing the tab, or following a link. React Router's useBlocker only works in its data mode, so useUnsavedChangesWarning listens for link clicks itself. It doesn't catch the browser's Back button.
  • Not yet: restoring deleted customers and history (the audit log step).

The data grid

Customers and Members share one grid, in src/Web/src/grid/. It's built by hand, without a grid library: what it needs is a list of columns, header buttons, a sort select for phones and a column picker, about the size of the code a library would need to set it up. TanStack Table would start to earn its place with column resizing or reordering, multi-column sort, or very long lists in the browser; none of those are here yet.

  • The view is in the URL. ?search=&status=&sort=&dir=&page=, with the API's own names and values, so the address bar shows the request the list makes. Defaults are left out: the plain list's URL is just /customers. A new search, filter or sort goes back to page 1. Clear appears when anything differs from the default. The rules are in listState.ts, a pure module with tests.
  • Follow a sort from click to SQL: the header button calls sortBy() (listState.ts), the URL becomes ?sort=updated&dir=desc, useCustomers sends the same to GET /api/customers, the controller checks updated against CustomerStore.SortColumns, and the query ends ORDER BY c.UpdatedAt DESC, c.Id DESC. The request's text only ever picks a key in that list; it never reaches the SQL.
  • Headers are buttons with aria-sort on the sorted column. The first click sorts text A to Z and dates newest first; a second click reverses it. On a phone there are no headers to tap, so a select picks the column and the direction together.
  • Column choices (wide screens only; the name column can't be hidden) are saved in localStorage, per user and grid. It's a display preference and losing it costs a click, so it doesn't earn a table. They stay out of the URL on purpose: a shared link shows the same rows, not your columns.
  • Long emails wrap cleanly: only before a dot or after the @ (emailParts.ts), never mid-word. Cutting them short with an ellipsis would hide the address behind a hover tooltip, and nothing here may need hover. A column too narrow for an address's longest part makes the table scroll in its own box.
  • Members sorts in the browser. GET /api/members sends the whole tenant at once, so another order would fetch the same rows again. sortRows.ts uses the API's rules: one column, then the id, empty values first when ascending. When invites make member lists long, Members can move to server paging without changing the grid.
  • Indexes: the Name and Email sorts use 0013's indexes; Updated and Created have their own (0015), led by TenantId and filtered to live rows. Status has two values and sorts the tenant's rows each time, which is cheap at the sizes this starter is for. With 50,000 customers in one tenant, the Updated sort reads 25 rows from its index backwards, with no sort.

Edit conflicts: the three-way merge

Two people open the same customer. One saves. When the other saves, the API answers 409 with the record as it is now. Instead of "someone else changed this, start over", the form merges, field by field, using three versions: what the form loaded (the original), what's in the form (mine), and what the other person saved (theirs).

The field Result
Changed only by me Keep mine
Changed only by them Take theirs, and list it, so nothing changes without being seen
Changed by both, to the same value Fine
Changed by both, to different values A conflict: yours and theirs side by side (stacked on a phone), and you pick one

Then you save again. That save sends their rowVersion, so if a third person saved in between, it's another 409 and another merge, starting from their version. If the other person deleted the customer, the form says so and offers to save your version as a new customer.

The merge is a pure function with no imports, src/Web/src/customers/merge.ts, tested with Node's own test runner (npm test, which runs merge.test.ts): no test library, and no browser.

Forms

Every form is built from a few field components in src/Web/src/forms/: TextField (text, email, phone), SelectField, TextAreaField and PasswordField. Each is a Field with its own input inside, and Field owns the label, the "(optional)" marker, the hint, the error, and the ids and aria-describedby that tie them together. They're built by hand, without a form library. These forms have five fields at most, none of them repeat or depend on each other, and the merge screen fills in values from outside the form. React Hook Form would earn its place with repeating groups (order lines, contacts), a long form whose fields depend on each other, or a multi-step wizard. A schema library like Zod would earn its place with a Node back end that could share the schema.

  • The rules are plain code, written twice. The server's rules are in CustomerValidation.cs and PasswordRules.cs. The form has a copy of each, with the same messages word for word: customers/rules.ts and auth/passwordRules.ts, pure modules with no imports. The client copy is there so people find out sooner. It's never a security boundary: the server checks everything again.
  • CI proves the two copies agree. The test cases are shared JSON files, customers/rule-cases.json and auth/password-cases.json (input, then the exact errors or what gets stored). npm test runs them against the TypeScript copy, and .github/scripts/rule-cases.mjs runs the same cases against the API. If a rule or a message changes on one side only, one of the two fails. To change a rule, change both copies and add a case.
  • Trimming like .NET. .NET's Trim() and JavaScript's trim() don't remove the same characters (U+0085 and U+FEFF differ), so the rules modules trim exactly what .NET does.
  • Follow one field from the screen to the server: the Notes field is a TextAreaField in pages/customer/CustomerEditor.tsx. On submit, useForm runs validateCustomer (customers/rules.ts), whose notes check is the same if as the one in CustomerValidation.Validate, with the same 2000 limit (the column length in 0013_customers.sql) and the same message. The case "notes one over the limit" in rule-cases.json proves both say it.
  • When errors show: nothing while you type the first time. On submit, every problem at once, with focus on the first field that has one. After that, a field showing an error is checked again on every change, so the error goes as soon as it's fixed. Errors are linked to their fields with aria-describedby and read when the field gets focus, never on every key. No error summary at the top: with five fields, focus on the first problem is enough.
  • Character count on a field with a long limit (Notes, 2000): it appears at 80% of the limit ("400 characters left") and turns red past it. It counts the trimmed length, as the rule does. A screen reader hears it once typing pauses for a second, not on every key.
  • Sign-in has no client checks, so nothing there can hint at whether an account exists. The new-password forms check the length (and, when changing your password, that it isn't your email), and that the two copies match. That last one is a form check, not a password rule: the server never sees the second copy.
  • No maxLength on inputs: it would cut pasted text short without a word. The rules say how long is too long instead.

Code conventions

Mostly style, written down so contributors know what to expect. Enforced by .editorconfig, ESLint, and Prettier rather than code review.

  • 2-space indentation everywhere, spaces not tabs: C#, TypeScript, SQL, JSON, YAML. Yes, the .NET default is 4. Two is on purpose.
  • Braces always. No single-line if statements, in C# or TypeScript.
  • Prefer early returns over nesting. Guard clauses at the top of a method instead of wrapping the body in an if. If you're indented 14 levels deep, the indent width isn't the problem.
  • Brace placement follows each language's default: own line in C#, same line in TypeScript.
  • C#: a classic Program class with Main (no top-level statements), implicit usings off so every file lists its own using lines, file-scoped namespaces, and nullable reference types on.
  • Front end: standard Prettier formatting, with ESLint enforcing braces.
  • Mobile first. The base CSS targets a phone, and min-width media queries add the larger layouts. Every screen has to work at 390 px wide without the page scrolling sideways; wide content like data grids scrolls inside its own container. Touch targets are at least 44 px, and nothing is reachable only by hover.
  • Logging: the built-in Microsoft.Extensions.Logging with the console provider. Always inject ILogger<T>, so every message is tagged with the class that wrote it. Write message templates with named placeholders, _logger.LogInformation("Applied {Migration}", name), never string interpolation: interpolation loses the named values and builds the string even when that log level is off. The build enforces this (rule CA2254). Never log secrets: passwords, connection strings, tokens, cookies. Per-request scopes, JSON output, and a global exception handler come in later steps. The Db runner is a command-line tool, so it prints its results with Console directly; that's output, not logging.

Dependencies

Every package is code someone else wrote that we have to keep up to date and trust, so the default is what's already there: .NET and ASP.NET Core, the browser's own APIs, and React. A library has to earn its place through necessity (there's no built-in way to do it), safety (it closes a security hole), or a real gain in correctness (Dapper: hand-written row mapping is repetitive, error-prone code). Saving a few lines isn't enough on its own.

It's a principle, loosely held: it guides the decision, it doesn't rule out good libraries. Each new dependency is justified in the pull request that adds it and listed here.

Package Where Why it's here
Dapper API, Db runner Maps query results to C# objects. Hand-written row mapping (column names as strings, casts, null checks) is repetitive code that breaks quietly. Dapper does only that; the SQL stays ours.
Microsoft.Data.SqlClient API, Db runner The SQL Server driver. .NET doesn't ship one; this is Microsoft's.
Konscious.Security.Cryptography.Argon2 API, Db runner Argon2id password hashing. .NET has no built-in Argon2, and the built-in alternative (PBKDF2) isn't memory-hard, so a GPU can try passwords far faster. Earns its place on safety. It does the algorithm only; the salt, the PHC format, constant-time comparison, and rehashing are our code (src/Db/Passwords). Checked against the reference implementation (argon2-cffi) in both directions.
Azure.Extensions.AspNetCore.DataProtection.Blobs API Keeps the Data Protection keys (which encrypt the sign-in cookie) in Azure Blob Storage, so a deploy or restart doesn't sign everyone out. Only used when DataProtection__BlobUri is set.
Azure.Extensions.AspNetCore.DataProtection.Keys API Encrypts those keys with a Key Vault key that never leaves the vault, so a copy of the blob alone is useless. Safety.
Azure.Identity API Lets the app sign in to Storage and Key Vault with its managed identity, so no storage key or secret sits in its settings.
System.Security.Cryptography.Pkcs Security pin Not used directly. SqlClient 7.1.1 pulls in 9.0.18, which has two denial-of-service advisories, so Directory.Packages.props pins it to the patched 10.0.13. Remove the pin once SqlClient depends on a patched version itself.
react, react-dom Front end The UI library the front end is built on.
react-router Front end Client-side routing: the URL changes and the right page renders without a reload, and back, forward, and deep links work. The browser has no built-in way to do that for a single-page app. We use only the declarative parts (BrowserRouter, Routes, Route, NavLink), not its data loaders or framework mode, so data fetching stays in our own code.
@tanstack/react-query Front end Server data: caching, sharing one request between components, and re-checking when the tab regains focus. Doing that by hand with useEffect is where stale data, double requests, and missed cancellations come from, so this is a gain in correctness. It sits on a plain fetch client (src/Web/src/api.ts), with one hook per resource.
@tanstack/react-query-devtools Front end, dev A panel that shows what is cached and why. Loaded in development only; a production build leaves it out.
vite Front end, dev Dev server (including the /api proxy) and production bundler.
@vitejs/plugin-react Front end, dev Lets Vite compile JSX and reload components in place while you edit.
typescript Front end, dev Type checking; npm run build fails on type errors. Pinned to 6.0.x until typescript-eslint supports TypeScript 7.
@types/react, @types/react-dom Front end, dev Type definitions for React.
@types/node Front end, dev Types for vite.config.ts, which runs in Node, not the browser. Kept on the same major as the Node version CI uses (24), so the types only describe APIs that version has.
eslint, @eslint/js Front end, dev Linting, with ESLint's recommended JavaScript rules.
typescript-eslint Front end, dev Lets ESLint read TypeScript and adds TypeScript-aware rules.
eslint-plugin-react-hooks Front end, dev Catches broken hook usage and missing effect dependencies, which are real bugs, not style.
eslint-plugin-react-refresh Front end, dev Warns when a file's exports would stop Vite's in-place reload from working.
globals Front end, dev Tells ESLint which browser globals exist (window, document), so they aren't flagged as undefined.
prettier Front end, dev Formatting, so style never comes up in review. Pinned to an exact version, because formatting can change between releases.
eslint-config-prettier Front end, dev Turns off ESLint rules that would fight Prettier's formatting.

"Dev" packages are build and editor tooling; they aren't shipped to the browser.

Services, not packages. Password reset emails go through Resend. It's a service the API calls over HTTP, not a package: one POST with a plain HttpClient (src/Api/Email/ResendEmailSender.cs), so there's no SDK to keep up to date. It only runs when its settings are present, and swapping it for another service means writing one class that implements IEmailSender.

src/Web/package.json also has one overrides entry: it forces minimatch (the glob matcher inside ESLint and typescript-eslint) up to 11.0.4, because 10.x has a denial-of-service bug (GHSA-g3hv-75wg-m249) and those packages still ask for 10.x. It's dev tooling only, and lint was checked against it. Remove the override once ESLint and typescript-eslint depend on minimatch 11 themselves.

What it will include

The goal is the 80% every dashboard app needs on day one:

  • Solution layout: front end, API, and database projects in one repo
  • Local dev environment with Docker Compose and seeded data
  • App shell: sidebar navigation, top bar with tenant switcher, responsive layout, light and dark themes
  • Authentication: sign in and sign out, lockout, and a private demo sandbox for every visitor
  • Password reset and change password
  • Tenants: one account across tenants, tenant-scoped data, Row-Level Security
  • Users, roles, and permissions, enforced on both API and UI
  • A reusable data grid with server-side paging, sorting, and filtering
  • CRUD example module showing the end-to-end pattern, including edit conflicts
  • Forms with shared validation rules
  • Settings and user profile pages
  • Audit log of who changed what
  • Dashboard home with sample KPI cards and charts
  • Error handling, logging, and health checks
  • Automated tests for API and UI
  • CI pipeline and a documented deployment path, with a live demo deployed on every merge

How we work

This repo uses GitHub flow:

  1. Branch off main for every change, including docs. Name branches by area or step, such as step-2/solution-layout or docs/readme-fix.
  2. Open a pull request. The description explains what changed and why, since PRs double as the record behind each blog post.
  3. Once CI exists, its checks must pass before merging.
  4. Squash merge, so main gets one clean commit per PR, then delete the branch.

main is protected: no direct pushes, no force pushes.

Why the change? The first few commits went straight to main. With one person on the project, branches and PRs aren't strictly necessary. They're still a good habit: a protected main keeps you from pushing a half-finished change or a broken build where everything else depends on it, and a PR gives you one last look at the diff before it lands. And if you work on a team, which most of us will, you won't be committing straight to main, or at least you shouldn't be. This is also a starter other people will fork, so it should show the workflow worth copying. We noticed early and switched before any real code landed. PR #1 was the first one under the new rules.

Building in public

Each milestone above gets its own post covering what was built, the tradeoffs, and what I'd do differently.

Every post gets a release. When a post's pull requests are merged, main is tagged v0.N to match the post number, with a GitHub Release that links to the post and lists its PRs. Check out the tag to see exactly the code the post describes.

# Post Release Status
1 Why build another dashboard starter? v0.1 Published
2 No magic: repo structure and local dev setup v0.2 Published
3 Ship Early, Ship Often: Deploying to Azure Before the First Feature v0.3 Published
4 The App Shell: A Sidebar, a Top Bar, and Three Dependencies v0.4 Published
5 Signing In: Our Own Auth, and the Deploy It Broke v0.5 Published
6 Password Reset: Tokens, Timing, and an Email Service on Its Way Out v0.6 Published
7 Roles and Permissions: Check What, Not Who v0.7 Published
8 Demo Sandboxes: A Private Copy for Every Visitor v0.8 Published
9 The CRUD Module: Customers, Row-Level Security, and a Three-Way Merge v0.9 Published
10 The Data Grid: Sorting, Filters, and Columns, Built by Hand v0.10 Published
11 Forms Without a Form Library v0.11 Published
12 Audit log v0.12 Planned
... More to come

Getting started

You need the .NET 10 SDK (current LTS), Node.js (current LTS; at least 22.22, because React Router 8 requires it), and Docker Desktop.

From the repo root:

cp .env.example .env                       # local dev settings (gitignored)
docker compose up -d --wait                # start SQL Server and wait until it's ready
dotnet run --project src/Db -- migrate     # create the database and schema
dotnet run --project src/Db -- seed        # add sample tenants and a local account (Development only)
dotnet run --project src/Api               # API on http://localhost:5080

Then, in a second terminal:

cd src/Web
npm install
npm run dev                                # front end on http://localhost:5173

Open http://localhost:5173 and either click Try the demo, which makes you a private sandbox just like the live demo, or sign in with the local account: admin@example.com, password LocalDevOnly!Admin1. Like the SQL Server password in .env.example, that password is for your laptop only; seed refuses to run anywhere but Development. The local account is a Member in Acme Corporation and an Admin in Globex Industries; switch between them from the top bar. The Health page shows three green checks: the front end, the API, and the database, with the schema version the database is on.

The health check page: front end, API, and database all ok, with the SQL Server version and schema version 0004_security_schema.sql

What just happened:

  • Docker runs SQL Server 2025 only, on port 1433, with its data in a named volume (sqlserver-data) so it survives restarts.
  • migrate creates the DashboardStarter database if it's missing, runs any new scripts in sql/migrations, then reruns everything in sql/programmable. It prints applied, skipped, or failed for each file. Run it as often as you like; the second run skips everything.
  • seed runs the scripts in sql/seed (two sample tenants, Acme Corporation and Globex Industries), then creates the local account, admin@example.com, with the password above (src/Db/Users/LocalAccount.cs). Running it again changes nothing. It refuses to run outside Development. (Seeded in step 7? migrate retires the old shared demo account, guest@example.com, and the API's cleanup removes it at startup. Seeded before step 7? The old demo@example.com is still there. It's harmless; docker compose down -v starts over without it.)
  • The API checks at startup that no migrations are pending. If one is, it refuses to start and tells you to run migrate. It never changes the schema itself.
  • The front end runs on the Vite dev server, which forwards /api to the API, so the browser only ever talks to one origin.

More users. There's no sign-up page yet; accounts are made with the Db runner, which prompts for the password without showing it:

dotnet run --project src/Db -- create-user --email ann@example.com --name "Ann Example" --tenant "Acme Corporation"
dotnet run --project src/Db -- set-password --email ann@example.com     # also signs out her other sessions
dotnet run --project src/Db -- set-role --email ann@example.com --tenant "Acme Corporation" --role Admin

create-user makes the membership a Member unless you add --role Admin or --role Read-only. set-role changes it later; it's also how a fresh deployment gets its first admin, since nobody can use the Members page to promote themselves. Like the Members page, it refuses to leave a tenant with nobody who can manage members.

A password is 12 to 128 characters and can't be the account's own email; there are no rules about digits or symbols, following current NIST guidance. The API and the Db runner check the same rules (src/Db/Passwords/PasswordRules.cs).

Password reset emails, locally. In Development nothing is sent: each email is written as a text file to .dev-mail/ at the repo root (gitignored). Click "Forgot password?" on the sign-in page, enter admin@example.com or an account you made with create-user (demo sandboxes never get one), then open the newest file in .dev-mail/ and follow its link. Links work once, for 30 minutes. Signed in, you can change your password from the account menu in the top bar.

Email on a deployed copy is off until you set it up: the sign-in page hides "Forgot password?" and nothing is sent. Turning it on takes a Resend account, a sending subdomain with a few DNS records, and two settings (Email__From, Email__ResendApiKey); the walkthrough is step 7 of docs/deploy-azure.md. Reset links are built from the CanonicalHost setting, never from the request, so a forged Host header can't point a link at someone else's site.

--tenant takes a tenant's id or name; run create-user again with another tenant to add a second membership. Passwords are never accepted as arguments, which would end up in your shell history. For scripts, pipe the password in and add --password-stdin.

Testing as Production? Use dotnet run --no-launch-profile for both the API and the Db runner. Without it, dotnet run applies the project's launch profile, which sets the environment to Development whatever you set yourself.

Using VS Code? The repo includes launch configurations (Run and Debug, or F5): API, Db: migrate, Db: seed, Web (Chrome), and API + Web for the whole app. They do the same as the commands above, with the debugger attached. You still start SQL Server with docker compose up -d --wait and run npm install in src/Web once. The .NET configurations need the C# extension (ms-dotnettools.csharp); VS Code offers to install it.

Changed the password in .env? The API and the Db runner use the password from .env.example by default. If you change it, set your connection string as an environment variable in the terminal you run them from.

Bash or zsh (macOS, Linux, Git Bash):

export ConnectionStrings__Default='Server=127.0.0.1,1433;Database=DashboardStarter;User Id=sa;Password=<your password>;Encrypt=True;TrustServerCertificate=True'

PowerShell (Windows):

$env:ConnectionStrings__Default = 'Server=127.0.0.1,1433;Database=DashboardStarter;User Id=sa;Password=<your password>;Encrypt=True;TrustServerCertificate=True'

Use single quotes, as shown, so characters like ! and $ in the password are taken literally. Either way, the variable lasts until you close that terminal.

For the API you can use a user secret instead: dotnet user-secrets set "ConnectionStrings:Default" "<connection string>" --project src/Api.

Already have a SQL Server? Set ConnectionStrings__Default to point at it and skip Docker. That works, but Docker is the supported path. If something else already uses port 1433, change the port on the left of "1433:1433" in docker-compose.yml and in your connection string.

On an Apple Silicon Mac? SQL Server's container image is built for Intel, so turn on "Use Rosetta for x86_64/amd64 emulation" in Docker Desktop's settings before starting it. It runs a little slower than native, which doesn't matter for development.

Docker Desktop licensing: free for personal use, education, and small businesses. Larger companies need a paid subscription, so check before installing it on a work machine.

Start over with an empty database: docker compose down -v deletes the container and its volume. Then run the steps again from docker compose up.

Repo layout

/sql                 schema scripts (see "Schema scripts" above)
/src/Db              the Db runner: `migrate`, `seed`, `app-user`, and the account commands (`create-user`, `set-password`, `set-role`)
/src/Api             ASP.NET Core Web API (controllers)
/src/Web             React + TypeScript front end (Vite)
/infra              Bicep for the Azure resources (see docs/deploy-azure.md)
/docs                deployment guide, and screenshots used in this README
/.vscode             launch configurations for VS Code (optional)
docker-compose.yml   SQL Server for local development

Checks

The same checks run in CI on every pull request:

dotnet build                 # warnings are errors, including code style from .editorconfig
cd src/Web
npm run lint                 # ESLint
npm run format:check         # Prettier (npm run format to fix)
npm test                     # unit tests, with Node's test runner
npm run build                # type-check and build

CI also runs the API against a real SQL Server and checks sign-in end to end with curl: wrong passwords, lockout, antiforgery, switching tenants, and sessions ending after a password change. The script is .github/scripts/auth-checks.sh. A second script, .github/scripts/password-checks.sh, does the same for password reset and change password: one answer for every address, emails only to real accounts (read from .dev-mail/), links that work once and expire, sessions that end, the hourly email cap, and the password rules. A third, .github/scripts/sandbox-checks.sh, covers demo sandboxes: what one contains, that two can't see each other, expiry, cleanup removing exactly a sandbox's rows, and the cleanup lock. .github/scripts/customer-checks.sh covers the Customers API: each role's permissions, validation, paging and search escaping, 409 with the current record, soft delete on every endpoint, tenant isolation, and the demo row cap. .github/scripts/rule-cases.mjs runs the forms' shared rule cases against the API (see "Forms"). .github/scripts/rls-checks.sh checks Row-Level Security straight in SQL Server: the policy covers every table with a TenantId, no tenant means no rows, and one tenant can't read or write another's, as the API's login and as the admin. CI also checks the sandbox limits, that cleanup knows every table, the upgrade from step 7's shared demo account and from step 8, and that -- for-each-tenant data migrations reach every tenant. They all run locally too (see the comments at their tops).

Security checks

Free GitHub features, so none of them add a dependency to the project:

  • CodeQL (.github/workflows/codeql.yml) reads the C#, TypeScript, and workflow files on every pull request and once a week, looking for security bugs like SQL injection and XSS. Findings show up on the PR and in the Security tab.
  • Dependabot (.github/dependabot.yml) opens a weekly PR per ecosystem (NuGet, npm, GitHub Actions) with minor and patch updates grouped, plus immediate PRs for known advisories. Every update goes through CI like any other change. Major versions of typescript, @types/node, and react-router are ignored and bumped by hand after reading their upgrade notes, because a major can pass CI and still be wrong for this project (the reasons are in dependabot.yml).
  • Secret scanning with push protection blocks a push that contains something that looks like a key or password.
  • Private vulnerability reporting: how to report a problem is in SECURITY.md.

Changes that touch auth, tenant filtering, SQL, or the workflows also get a /security-review pass with Claude Code before the PR opens (see CLAUDE.md).

Forked the starter? The workflow files come with you, but the GitHub settings don't. In your fork, go to Settings > Advanced Security and turn on Dependabot alerts, Dependabot security updates, secret scanning, push protection, and private vulnerability reporting, then update the contact details in SECURITY.md. Leave CodeQL's "default setup" off: the workflow file already runs CodeQL, and GitHub rejects its results while default setup is on.

Deploying

Every merge to main deploys to Azure once CI passes: the React build is served by the API from one App Service, the database is Azure SQL, and the pipeline runs migrate before the new code goes out. The one-time setup (Azure resources from Bicep, passwordless sign-in for GitHub, secrets, and an optional custom domain) is in docs/deploy-azure.md. Forks skip the deploy until they set it up.

FAQ

Why not Entity Framework Core? We want every query to be SQL you can read, tune, and run yourself. Dapper maps results to objects and otherwise stays out of the way: no generated SQL, no change tracking to reason about. Schema changes are plain SQL scripts instead of migrations generated from C# models.

Why not stored procedures? This project is for developers who want to understand the whole stack, not a data layer owned by a DBA. Procedures have their place, but putting every query in one splits each feature across two places and two deployments, which is a maintenance headache in a codebase meant to be easy to follow. Two common objections: parameterized queries get their execution plans cached and reused just like procedures do, and it's parameters, not procedures, that prevent SQL injection. If your team has a DBA who owns the database and reviews every query, procedures can be the right call there.

Why one shared database instead of one per tenant? A database per tenant sounds safer, but it multiplies the work: every migration runs N times, schemas drift, a deploy can half-succeed, and reporting across tenants means querying every database. Before accepting that requirement, ask what it's really protecting against. Data leaking between tenants is handled by Row-Level Security. The honest weak spot of a shared database is restoring a single tenant from backup, which takes work. Legal data-residency rules are a real reason to split, but by region, not by tenant.

Why int keys instead of GUIDs? They're 4 bytes instead of 16 in every index and foreign key, don't fragment the clustered index, and are easy to read when debugging. "Guessable IDs" are only a problem without authorization: every request here is permission-checked and tenant-scoped, so guessing the next ID gets you a not-found. Gaps in the numbers after a restart are normal; IDs aren't row counts.

Why controllers instead of minimal APIs? Controllers are time-tested and come with a structure everyone recognizes: one class per resource, with routes and authorization visible on the class and its methods. Minimal APIs are leaner, but in a large app every team ends up inventing its own way to organize them. Minimal APIs do support native AOT, which controllers don't, but that matters for serverless and tiny containers, not a dashboard app.

Why not ASP.NET Core Identity? It does a lot you can't easily see, which makes it hard to trace why it behaves the way it does, and its built-in UI is Razor Pages, which a React app doesn't use. We use ASP.NET Core's cookie authentication and authorization directly, with our own user tables. Lockout, password reset tokens, and signing out other sessions after a password change are each a small amount of code you can read.

Why not JWT? Cookies, because the only client is a browser on the same site. An HttpOnly cookie can't be read by JavaScript, so a script injection bug can't steal the session, and a session can be revoked immediately. CSRF is handled with SameSite cookies and antiforgery tokens. If you add a mobile app or a public API, add token auth for those clients alongside the cookies.

Why are the cookie names different locally? Deployed, the sign-in and antiforgery cookies are named __Host-ds-auth, __Host-ds-af, and __Host-ds-xsrf, and always Secure. The __Host- prefix makes the browser reject the cookie unless it's Secure, set for the whole site, and tied to this one host name, so no subdomain can plant or overwrite it. Locally the front end runs on plain http://localhost through the Vite proxy: ASP.NET Core's antiforgery refuses a non-HTTPS request when its cookie must be Secure, and Safari won't keep Secure cookies on http://localhost at all. So in Development only, the names lose the prefix (ds-auth, ds-af, ds-xsrf) and Secure follows the request. It's one place in the code, src/Api/Auth/AuthCookies.cs, and CI checks the deployed names and flags.

Why is there Azure code in the app? Only for one thing: the keys that encrypt the sign-in cookie. They have to outlive a deploy, or every deploy signs everyone out, and they're worth protecting, because whoever has them can forge a session for any user. On Azure they live in Blob Storage, encrypted by Key Vault, reached with the app's managed identity (src/Api/Hosting/DataProtectionSetup.cs). Without its two settings the app uses ASP.NET Core's local default, so it still runs anywhere; a fork hosted elsewhere swaps in that platform's equivalent.

Why Resend for email, and not Azure's own email service? The plan was Azure Communication Services Email, reached with the app's managed identity, so there'd be no key to keep. It wasn't available to us, so step 6 uses Resend: one HTTP call, a sending-only API key restricted to one domain, and nothing tied to Azure, so the "one Azure-specific piece" above stays one. The key lives where the other secrets do (the GitHub demo environment and App Service settings) and never in a log. Any other service fits behind IEmailSender.

Why do reset links put the token after a #? The part of an address after # (the fragment) never leaves the browser, so the token can't end up in a server's access log or a proxy along the way. The reset page reads it, then removes it from the address bar. Only a SHA-256 hash of the token is stored, so someone who can read the database still can't use it. Links work once, for 30 minutes, and asking for a new one cancels the old one.

Why Argon2id for passwords? It's OWASP's first recommendation. It's memory-hard, so each guess costs memory as well as CPU, which takes away most of an attacker's GPU advantage. Hashes are stored with their settings, so the settings can be raised later and users are rehashed automatically when they sign in.

Why doesn't the API run migrations on startup? A database that changes because you started the app is hidden behavior. You run the migrate command on purpose, and you see exactly which scripts it applied.

Why a sandbox per visitor instead of a shared demo account? A shared account with a published password can't be allowed to change anything that matters: anyone could lock out the next visitor, demote the only admin, or leave something offensive for everyone after them. So step 7's demo showed an admin's controls switched off, which demonstrates very little. A sandbox per visitor costs a few rows and a cleanup job, and every visitor gets the real app. The cleanup also earned its place as the starter's example of background work.

Why does the demo cleanup run in the API, not in a scheduled GitHub Action? It's data work, not schema work, so it fits the API's own database login, and it needs no extra secret, firewall rule, or schedule outside the app. Running in the app also shows forks how background work is done in ASP.NET Core: a BackgroundService with a PeriodicTimer, and a database app lock so several instances don't do the same work at once.

Why does the API have its own database login? So "the API never changes the schema" is enforced by SQL Server, not just promised by our code. The deploy pipeline runs migrate with an admin login. The API connects as a separate login in the app_runtime role, which can read and write data but can't create, alter, or drop anything. If the API is ever compromised, the attacker gets the same limits. dotnet run --project src/Db -- app-user creates or updates that login.

Why Azure? It's the natural home for a .NET and SQL Server app, and App Service plus Azure SQL means no servers or containers to manage. Settings come from environment variables, and the app runs anywhere .NET and SQL Server do. The one Azure-specific piece is where the cookie encryption keys are kept (see above), and it switches off without its settings. Email goes through Resend over plain HTTP, so it works the same from any host. Azure is the one deployment path we document and test, the same way Docker is the one local setup.

Why Docker for the database? It's the one setup that works the same on Windows, Mac, and Linux, with the same SQL Server version as CI. Docker only runs the database, so you debug the API and front end normally.

Contributing

Issues and suggestions are welcome. Since the project is opinionated, pull requests that change core stack choices may not be merged, but the discussion is always useful.

License

MIT. Use it for anything, including commercial projects.

About

Opinionated open-source dashboard starter: React + TypeScript, ASP.NET Core (C#), and SQL Server. Built in public.

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages