Hamadaska
N°02Case study

A full-stack app for recording expenses, built with ASP.NET Core, React, TypeScript and PostgreSQL.

A full-stack app for recording expenses, built with ASP.NET Core, React, TypeScript and PostgreSQL.

z z Tuna Purr Click On/Off Click Click On/Off
Back to home page
N°02Case studyPersonal Expense Tracker

How I built the Expense Tracker

Backend
C#, ASP.NET Core, EF Core, PostgreSQL
Frontend
React, TypeScript, TanStack Query
Source
GitHub
E Expense Tracker Dashboard Expenses Log out Dashboard From To Total spending Expenses Average expense Largest expense Housing Travel Shopping Bills Food Apply Spending over time Spending by category Top categories Top expenses /summary /by-day /by-category /top-expenses EExpense TrackerLog outDashboardExpensesDashboardFromToApplyTotal spendingExpensesAverage expenseLargest expense/summarySpending over time/by-daySpending by category/by-categoryTop categories/by-categoryTop expenses/top-expensesHousingTravelShoppingBillsFood
Each panel and its API call

01

The idea

The Expense Tracker started as a way to put ASP.NET Core knowledge into practice and gain experience building a full-stack application with React.

The app lets users manage expenses, filter transactions, and view spending summaries. I kept the functionality straightforward to leave room for the engineering behind it: authentication, database design, API development, and automated testing.

02

Planning the application

Before writing any code, I decided what I wanted the project to achieve. The goal was to build a portfolio project focused on backend development, so I kept the application simple: users log expenses and view their spending on a dashboard.

The priority was getting the core functionality working properly before adding anything else. Features like recurring transactions and budgets could come later, once the basics were finished, tested, and stable.

For authentication, I chose Keycloak instead of building my own login system. It handles user authentication and issues tokens that the API validates. It also runs locally through Docker Compose, so the project can be run without relying on an external identity provider.

I divided development into phases, starting with the backend and its testing and infrastructure, then moving on to the frontend. Below is how I approached the initial build.

Sep Oct Nov backend first then the frontend API Tests Frontend Sign-in Docker + CI Final fixes CRUD, dashboard Testcontainers React, TanStack Query, charts Keycloak, JWT Compose, GitHub Actions logic moved into services backend first then the frontend SepOctNov APICRUD, dashboardSign-inKeycloak, JWTTestsTestcontainersDocker + CICompose, GitHub ActionsFrontendReact, TanStack Query, chartsFinal fixeslogic moved into services
Two months of commits

03

Architecture

The backend follows a Clean Architecture style: four projects in the ASP.NET Core solution, with clear responsibilities and dependencies that point inward.

API Infrastructure Application Domain endpoints, auth, configuration EF Core, PostgreSQL, migrations services, DTOs, validation rules, IFinanceDbContext User, Expense, Category implements the interface no package references at all APIInfrastructureApplicationDomain endpoints, auth,configurationEF Core,PostgreSQL,migrationsservices, DTOs,validation rules,IFinanceDbContextUser, Expense, Category implementsthe interface no package references at all
Dependencies point inward

For an application this small, this approach is more than necessary. A simpler layered setup would have worked just as well with less boilerplate. I chose it to get hands-on experience separating responsibilities, managing dependencies, and working with interfaces and dependency injection. It added a layer of complexity, but for a learning project, it was worth it.

04

Database design

The app uses PostgreSQL with Entity Framework Core as its ORM. Each expense belongs to one user and one category.

Amounts use decimal because floats can't store values like 0.1 exactly, and those small errors would add up in totals. Expense dates are stored as DateOnly, since only the day the user selected matters, not the exact time. A timestamp could change the date when converted between time zones. CreatedAt and UpdatedAt stay as DateTime because they record the exact moment an expense was created or updated. Their displayed date and time can change with the user's time zone, which is expected.

User Category Expense Id Guid, PK ExternalIdentityId string, unique Email string, unique CreatedAt DateTime Expenses many Id int, PK Name string, unique CreatedAt DateTime Id Guid, PK UserId Guid, FK CategoryId int, FK Amount decimal(18,2) Description string ExpenseDate DateOnly CreatedAt DateTime UpdatedAt DateTime index (UserId, ExpenseDate) one user's expenses, by date 9 seeded rows: Food, Bills, Travel, Transport, Housing, Shopping, Entertainment, Healthcare, Other no rounding errors only the day audit times, in UTC UserIdGuid, PKExternalIdentityIdstring, uniqueEmailstring, uniqueCreatedAtDateTimeExpensesmanyUserIdExpenseIdGuid, PKUserIdGuid, FKCategoryIdint, FKAmountdecimal(18,2)no rounding errorsDescriptionstringExpenseDateDateOnlyonly the dayCreatedAtDateTimeUpdatedAtDateTimeaudit times, in UTCindex (UserId, ExpenseDate)one user's expenses, by dateCategoryIdCategoryIdint, PKNamestring, uniqueCreatedAtDateTime9 seeded rows:Food, Bills, Travel, Transport,Housing, Shopping, Entertainment,Healthcare, Other
One expense and its choices

05

Authentication and security

Authentication was one of the more involved parts of the application. Keycloak is the identity provider, using OpenID Connect and the Authorization Code Flow with PKCE for the React frontend. After sign-in, the frontend sends an access token with its API requests, and the ASP.NET Core backend validates the JWT before allowing access to protected endpoints. The first time a Keycloak user calls the API, the backend creates a matching local user.

Step 1 of 7
React app Keycloak ASP.NET Core PostgreSQL 1 redirect to sign in 2 user signs in here the password never reaches the app 3 back with a token 4 GET /api/expenses + token 5 validate the JWT 6 WHERE UserId = you 7 only your expenses
1234567redirect to sign inReact app → Keycloakuser signs in hereon Keycloak's pagethe password never reaches the appback with a tokenKeycloak → React appGET /api/expenses + tokenReact app → ASP.NET Corevalidate the JWTin ASP.NET CoreWHERE UserId = youASP.NET Core → PostgreSQLonly your expensesASP.NET Core → React app
Sign in, then call the API

I made the API return 404 instead of 403 when a user requests another user's expense. A 403 would confirm the expense exists, while a 404 looks the same as an ID that was never there.

06

The REST API

The API has endpoints for managing expenses, retrieving categories, and generating dashboard reports.

Expense retrieval uses LINQ to apply filtering, sorting, and pagination before the database query runs, because loading a user's expenses into memory first would get slower as their data grows. It also lets the database use the index on UserId and ExpenseDate.

Queries project data into DTOs, so the API's shape isn't tied to the database. An entity can change without changing what the frontend receives, and responses return only the fields it needs, including things like the category name. Request DTOs also leave out fields like UserId, so a client can't set them.

The dashboard has four endpoints that share one query, filtered by the signed-in user and an optional date range. Like the filtering, the totals are calculated in PostgreSQL through EF Core, not in memory.

Pick an endpoint
every expense Where(e => e.UserId == userId) date range PostgreSQL runs it category, amount, search OrderBy(…) Skip + Take Select(DTO) ToListAsync() GroupBy(e => 1) Sum, Count, Max FirstOrDefaultAsync() GroupBy(category) Sum(amount) ToListAsync() GroupBy(ExpenseDate) Sum(amount) ToListAsync() OrderByDescending(amount) Take(10) Select(DTO) ToListAsync()
every expenseWhere(e => e.UserId == userId)date rangethen, by endpoint:GET /api/expensescategory, amount, search↓OrderBy(…)↓Skip + Take↓Select(DTO)↓ToListAsync()↓items, page, pageSize, totalGET /api/dashboard/summaryGroupBy(e => 1)↓Sum, Count, Max↓FirstOrDefaultAsync()↓Total, Count, Average, LargestGET /api/dashboard/by-categoryGroupBy(category)↓Sum(amount)↓ToListAsync()↓each category, with its totalGET /api/dashboard/by-dayGroupBy(ExpenseDate)↓Sum(amount)↓ToListAsync()↓up to 31 days: by dayup to 120 days: by weeklonger: by monthGET /api/dashboard/top-expensesOrderByDescending(amount)↓Take(10)↓Select(DTO)↓ToListAsync()↓up to 10PostgreSQL runs it at the last step
What each endpoint runs

07

Building the frontend

The frontend uses React, TypeScript, and Vite, with React Router handling navigation and TanStack Query managing API data.

Filters are stored in URL search parameters rather than only in component state. This allows users to refresh the page or share a filtered view without losing their selections.

/expenses?pageSize=5
  1. useExpenseQueryParams
  2. TanStack Query
  3. GET /api/expenses

Pick some filters, then press Send.

Your filtersSearchcoffeeCategoryFoodFrom1 Oct 2026Sort byAmount: high/expenses?search=coffee&categoryId=1&fromDate=2026-10-01&sortBy=amount&sortDirection=desc&pageSize=5useExpenseQueryParamsTanStack QueryGET /api/expenses
Sample data, not the real APIA filtered search's URL

TanStack Query handles fetching, caching, loading states, and request errors, keeping server data separate from local UI state.

On the dashboard, Recharts displays spending trends and category breakdowns.

08

Testing and development infrastructure

Automated tests check behavior beyond successful requests. The backend uses xUnit, with integration tests that run the actual API against PostgreSQL through Testcontainers. These cover CRUD operations, validation, filtering, pagination, dashboard calculations and access restrictions between users.

The frontend is tested with Vitest and React Testing Library, covering components, forms, API behavior and routing-related functionality.

Docker Compose can run the full app locally.

Browser web api keycloak db Nginx, :5173 ASP.NET Core, :5048 sign-in, :8080 PostgreSQL, :5433 docker compose up integration tests: real API, real Postgres Vitest + React Testing Library components, forms, routing swapped for a test handler, so real sign-in isn't tested yet BrowserwebNginx, :5173Vitest + React Testing Librarycomponents, forms, routingintegration tests: real API,real PostgresapiASP.NET Core, :5048dbPostgreSQL, :5433keycloaksign-in, :8080swapped for a test handler,so real sign-in isn't tested yetdocker compose up
What runs and what's tested

GitHub Actions automates builds, tests and container image publishing:

  1. push
  2. build
  3. unit tests
  4. integration tests
  5. Docker image
  6. container registry

09

Problems along the way

Docker + Keycloak

Every request returned 401

What happened Once everything ran in Docker Compose, every signed-in request failed with 401, even with a token that looked valid.

Why Keycloak had two addresses. From my Mac it was at localhost:8080, but the API, inside Docker's network, reached it at keycloak:8080. A token records where it came from in its iss (issuer) claim, and the API checks that claim. The tokens said localhost, the API expected keycloak, and nothing matched.

Browser Keycloak API localhost:8080 keycloak:8080 inside Docker JWT iss localhost:8080 expected keycloak:8080 401 Browserlocalhost:8080inside DockerKeycloakJWTisslocalhost:8080APIkeycloak:8080expected keycloak:8080401
One Keycloak, two names

The fix Two Keycloak settings:

compose.yaml# Every token names the same issuer…
KC_HOSTNAME: http://localhost:8080
# …while the API still reaches Keycloak by its Docker name
KC_HOSTNAME_BACKCHANNEL_DYNAMIC: "true"

ASP.NET Core + JWT

The sub claim that wasn't there

What happened A smaller token problem. Looking up "sub" on a valid token found nothing and threw an error.

Why ASP.NET Core renames some inbound claims by default, so sub had become a long URL-style name.

The fix Setting MapInboundClaims = false, so "sub" stays "sub".

10

Future work

A few areas still need work:

  • Production deployment: The application currently runs locally. Deployment is planned for later.
  • End-to-end testing: The existing tests cover individual components and API behavior, but not complete user flows, including authentication.
  • Monitoring: Adding structured logging and monitoring would make diagnosing problems easier in a deployed environment.
  • UI polish: I'm especially fond of user interfaces and user experience, and I have some whimsical design ideas I plan to add.