Course lesson 52 · Better Auth

Protecting our API Routes

One study unit · Read, recall, then practice · Original video 00:08:42

The server now protects both tRPC calls and WebSocket connections with Hono authentication middleware. Better Auth validates the session from request headers, and the middleware stores the authenticated user ID in typed request context. That identity replaces hardcoded account values in the socket proxy and tRPC context, so each user sees their own data.

Primary source: course video 52 · Supplied English subtitles · 00:08:42.

Understand the idea

What the course does

  1. Attach a custom middleware to tRPC and socket routes, initially logging to verify that it runs.
  2. Extract a helper that initializes the server-side Better Auth instance from environment configuration.
  3. Read the session using request headers and return an unauthorized response if no authenticated user exists.
  4. Place the user ID in Hono context and retrieve it in both protected route handlers.
  5. Set the socket’s forwarded account header from that identity and pass it into tRPC context creation.
  6. Deploy and verify that records associated with the old hardcoded identity are no longer listed for the signed-in user.

Watch for

Recall before revealing

Why should the socket’s account header come from middleware rather than browser input?

Reveal the explanation

Middleware derives it from a validated session, preventing the browser from simply selecting another account’s tracker.

Try it

Explain the expected result for a signed-out API request and a signed-in request from a different user than the demo account.

Check your result

The first is rejected; the second proceeds with its own identity and does not inherit the hardcoded demo account’s data.

Practice prompts and answer checks are added teaching material. Answer from memory first, then compare and explain any difference.

Rewatch only what you need

Open this lesson in your original course library and seek to the times below. Videos are not hosted on this site.

Companion primary documentation: Better Auth basic usage. For recorded API names, commands, limits, and prices, check the version you use.

← Previous   Next →