Sooner or later someone asks "what did this user actually do before it broke?" and the server logs only show half the story. The clicks, the failed payment form, the error that never reached the API: all of that happened in the browser.
The obvious fix is a fetch to /api/logs on every action. I started there too. It falls apart quickly:
- the user is on a train, the request fails, the entry is gone
- they close the tab right after clicking, the request is cancelled
- a retry after a timeout stores the same entry twice
- someone logs a whole form, and now there's a password in your audit table
This post shows how to do it properly with ASP.NET Core on the server. I'll use two packages I maintain, audit-log-lib (npm) and AuditLogLib.AspNetCore (NuGet), both Apache-2.0. If you'd rather build it yourself, the second half (what goes wrong and why) applies either way.
There's a live demo that runs entirely in your browser with a simulated backend. Tick "Backend unreachable" and watch entries queue up.
The server
Install the package (.NET 10, no other NuGet dependencies):
dotnet add package AuditLogLib.AspNetCore The package receives batches and hands them to one interface, IAuditLogSink. Storing them is your job, because only you know your database. Here's an EF Core version.
The table first. The unique index on EntryId matters, I'll explain why further down:
public class AuditLogRow { public long Id { get; set; } public string EntryId { get; set; } = string.Empty; public string? UserId { get; set; } public string? Action { get; set; } public string? Level { get; set; } public string? Payload { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset ReceivedAt { get; set; } } // in OnModelCreating modelBuilder.Entity<AuditLogRow>().HasIndex(r => r.EntryId).IsUnique(); Then the sink. It's registered as scoped, so you can inject your DbContext:
public sealed class EfAuditLogSink(AppDbContext db) : IAuditLogSink { public async Task WriteAsync(AuditLogBatch batch, CancellationToken cancelToken = default) { var ids = batch.Entries.Select(e => e.EntryId).ToList(); var existing = await db.AuditLogs .Where(r => ids.Contains(r.EntryId)) .Select(r => r.EntryId) .ToListAsync(cancelToken); foreach (var entry in batch.Entries) { if (entry.EntryId is null || existing.Contains(entry.EntryId)) { continue; // already stored, the browser is retrying } db.AuditLogs.Add(new AuditLogRow { EntryId = entry.EntryId, UserId = batch.UserId, // from the auth token, not from the browser Action = entry.Action, Level = entry.Level, Payload = entry.Payload?.GetRawText(), CreatedAt = entry.CreatedAt, // client clock ReceivedAt = batch.ReceivedAt, }); } await db.SaveChangesAsync(cancelToken); } } Notice UserId comes from batch, not from the entry. AuditLogBatch carries what the server knows for sure: the authenticated user, the connection, the IP, the time it arrived. Anything inside the entry was written by the browser, and the browser can say whatever it wants.
Wire it up in Program.cs:
builder.Services.AddAuditLog(); builder.Services.AddScoped<IAuditLogSink, EfAuditLogSink>(); // ... app.MapAuditLogHub("/hubs/audit").RequireAuthorization(); One thing that trips people up with SignalR and JWT: WebSockets can't send an Authorization header, so the token arrives in the query string. If you use JWT bearer auth, you need the usual SignalR hook:
options.Events = new JwtBearerEvents { OnMessageReceived = context => { var token = context.Request.Query["access_token"]; if (!string.IsNullOrEmpty(token) && context.HttpContext.Request.Path.StartsWithSegments("/hubs")) { context.Token = token; } return Task.CompletedTask; }, }; Without it the hub returns 401, and the network tab doesn't make it obvious why.
If you can't use SignalR (some proxies don't like WebSockets), there's also a plain HTTP endpoint: app.MapAuditLogEndpoint("/api/audit-logs"). You lose server-to-browser commands, everything else works the same.
The browser
npm install audit-log-lib @microsoft/signalr Create one instance in its own module and import it wherever you need it. Not inside a component, or you'll end up with five of them:
// src/audit.ts import { AuditLog, SignalRTransport, setupGlobalLogging } from 'audit-log-lib'; export const audit = new AuditLog({ transport: new SignalRTransport({ url: 'https://api.example.com/hubs/audit', accessTokenFactory: () => auth.getAccessToken(), }), redaction: {}, // defaults: passwords, tokens, emails, card numbers getContext: () => ({ route: location.pathname }), }); // also capture uncaught errors and console.error setupGlobalLogging(audit); accessTokenFactory is called on every connect, so a refreshed token is picked up without any extra code.
Then log the things you care about:
await audit.log('invoice.deleted', { invoiceId: 42 }); await audit.log('payment.failed', { orderId: 456, reason: err.message }, 'error'); I use area.action names in lowercase. It makes filtering in SQL a lot nicer later (WHERE Action LIKE 'payment.%'). Keep payloads small: ids, not whole objects.
On logout, send what's queued while the token is still valid:
await audit.flush(); clearToken(); That's the whole setup. The rest of this post is about what happens underneath, because that's where all the time went.
What goes wrong, and what the library does about it
The network is down
Every entry is written to IndexedDB first and marked as unsent. A background loop sends unsent entries in batches (50 entries or every 5 seconds by default) and marks them as sent only after the server confirms. If the server is down, the client reconnects with backoff, from 2 seconds up to a minute, and the queue just waits. Reload the page, close the browser, come back tomorrow: the entries are still there.
Old entries are cleaned up after 30 days, but only ones that were already sent. An early version deleted by age regardless, which meant a laptop that stayed offline for a month quietly lost its oldest entries. That one was caught in review, not in production, luckily.
The same entry arrives twice
This one is unavoidable. The server stores a batch, the response gets lost on the way back, the client never hears "ok", so it sends the batch again. Every entry gets a UUID (entryId) when it's created, and the server ignores ones it has already seen. That's what the unique index and the check in the sink are for. The check handles the normal case, the index catches the rare race where two requests with the same entry land at the same time.
Several tabs are open
Two tabs share one IndexedDB, so both see the same unsent entries. Without coordination, both send them. The library uses the Web Locks API so only one tab sends at a time. The other tabs keep logging into the same queue.
The batch is too big
SignalR's default limit for an incoming message is 32 KB. A batch of 50 entries with a stack trace or two goes over that easily, and the server just closes the connection. AddAuditLog() raises the limit to 1 MB for this hub only (your other hubs keep theirs). On top of that, when a batch fails, the next one is half the size, and it keeps halving until it goes through.
There's one case this doesn't solve: a single entry bigger than the server's limit. It will fail forever and block the queue behind it. If you log large payloads, keep an eye on that.
The tab is closed
When the page becomes hidden (switching tabs, closing, the phone locking), the client tries to send immediately. This is best effort. The browser may kill the page before the request finishes, and then the entries go out on the next visit instead.
Logging creates more logs
This was my favourite bug. In the demo app, a React list had a duplicate key. React printed a warning. setupGlobalLogging captured it and saved an entry. The new entry re-rendered the list. React printed the warning again. The entry count kept climbing as fast as React could render.
The fix: a captured console message that repeats within 10 seconds is logged once (dedupeMs). It compares only the message text, not the arguments, because React's warning includes a value that can change on every render. The downside is that console.error('Request failed', url) with different URLs also counts as a repeat. If every call matters, call audit.log() directly.
Personal data
Redaction runs before an entry is stored, so the sensitive part never touches IndexedDB, let alone the network:
await audit.log('user.signup', { email: 'ana@example.com', password: 'hunter2' }); // stored as { email: '[REDACTED]', password: '[REDACTED]' } The defaults cover keys like password, token, secret, apiKey, plus patterns for emails and card numbers. Card numbers are checked with Luhn, so a timestamp or a long order number is left alone (an earlier version masked those too, which made some logs useless).
Instead of masking you can use strategy: 'hash'. The same email always produces the same hash, so you can still see that two entries belong to the same person. It's a short non-cryptographic hash (djb2), meant for matching entries, not for anonymity: someone with a list of emails could hash them and compare.
To add your own keys, extend the defaults rather than replacing them:
import { DEFAULT_REDACT_KEYS } from 'audit-log-lib'; redaction: { keys: [...DEFAULT_REDACT_KEYS, 'iban', 'taxId'] } Talking back to the browser
With SignalR the connection works both ways, and that turned out to be the most useful part in practice. Support gets a ticket, the user's entries are still sitting in their browser because the app is set to send only warnings, and you can ask for more:
app.MapPost("/admin/users/{userId}/audit/debug", async (string userId, IAuditCommandSender commands) => { var commandId = await commands.SetLevelAsync(userId, "debug"); return Results.Ok(new { commandId }); }).RequireAuthorization("admin"); That user's browsers switch to debug level (it survives a reload) until you reset it. There are also PullAsync (send everything now), ClearAsync, PauseAsync and ResumeAsync. Each browser tab acknowledges a command after running it, and you can listen for those acks with IAuditCommandAckHandler.
You can send your own command types too, and handle them in the app:
audit.on('command', (cmd) => { if (cmd.type === 'toast') showToast(String(cmd.payload)); }); Things to keep in mind
-
CreatedAtis the client's clock. UseReceivedAtwhen order matters across users. - Don't put a user id in
getContextand trust it. The server knows who the user is from the token. - It's a browser library. With SSR, create the instance only on the client (
typeof window !== 'undefined'). - Not on ASP.NET Core? The server side is one hub method or one POST endpoint, described in the contract. It's short.
Links
- Demo: audit-log-lib-demo.pages.dev
- Code, both packages and a sample API: github.com/Darex97/audit-log-library
I'm curious how others handle this. Do you log user actions from the frontend at all, or do you rely on server logs and session replay tools? And if you've solved the "one huge entry blocks the queue" problem in a way you like, I'd love to hear it.
