Authentication and Data Isolation
Authentication is delegated to Clerk: the frontend signs the user in and sends a Bearer token with every request, and the backend verifies it. That part is standard. What is specific to ClayDiary is how the verified identity reaches PostgreSQL, so that the database, not the application code, decides which rows a request can see.
From token to row visibility
Clerk JWT ──► verified `sub` (user id)
│
▼
look up role in `profiles`
│
▼
app.current_user_id + app.user_role (transaction-local)
│
▼
RLS policies filter every queryEvery request that touches user data goes through this chain, whether it is an ordinary API call or an LLM-generated SQL query.
How identity is bound
The role comes from the database, not the token. The backend reads only the
user id (sub) from the verified token. The role is looked up in profiles on
each request, so changing a user's role takes effect immediately and no client
token can claim one.
The identity is bound to the database transaction. The request session sets
app.current_user_id and app.user_role as transaction-local values. The order
matters: the user id is set first, so the user can read their own profiles row
under RLS, and only then is the role resolved and set. See
Row-level security for
the policies that consume these values.
The profiles row, which holds the user's role, is created when Clerk calls the
signup webhook.