Middleware: using auth.id - suggestion welcome.

Hey all ๐Ÿ‘‹

I'm building an audit log using a PRE-middleware that I want to slap onto every endpoint โ€” authenticated or not. The function stack is dead simple: Add Record into log_audit with auth_id, uri, method, etc.

Works beautifully... right up until a public endpoint shows up without an auth object. No auth.id, middleware throws a tantrum, request dies. ๐Ÿ’ฅ

What I'm after: a clean, fast way to log the record and just leave auth_id empty when the endpoint is unauthenticated โ€” instead of crashing.

A few things I'm wondering:

  • What's the most reliable way to detect "no auth present" inside middleware without a try/catch wrestling match?

  • Is there a tidy pattern to make auth_id optional/nullable in the Add Record step?

  • Anyone running a global audit middleware across mixed public/private endpoints โ€” how did you handle the auth gap?

Short version: I want one middleware to rule them all, and I'd rather it logged a quiet null than fell over. Curious how others solved this.

Thanks! ๐Ÿ™

Security
4 replies