> ## Documentation Index
> Fetch the complete documentation index at: https://vlyai-1c28d863.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Auth integration

> How Convex's auth context works inside queries, mutations, and actions.

Every Convex function has access to the calling user via `ctx.auth.getUserIdentity()`. Use it to scope reads and writes to the current user.

## In a query

```typescript theme={null}
export const myStuff = query({
  args: {},
  handler: async (ctx) => {
    const user = await ctx.auth.getUserIdentity();
    if (!user) throw new Error("Not signed in");

    return await ctx.db
      .query("things")
      .withIndex("by_owner", q => q.eq("ownerId", user.subject as Id<"users">))
      .collect();
  },
});
```

## In a mutation

Same shape — get the identity, throw on missing, write scoped to the user.

## In an action

Identical.

## What's in the identity

```typescript theme={null}
{
  subject:  string,           // user ID (matches ctx.db.get(Id<"users">))
  email:    string | undefined,
  name:     string | undefined,
  pictureUrl: string | undefined,
  // additional provider-specific fields
}
```

## Common patterns

<Tabs>
  <Tab title="Require sign-in">
    ```typescript theme={null}
    const user = await ctx.auth.getUserIdentity();
    if (!user) throw new Error("Not signed in");
    ```
  </Tab>

  <Tab title="Optional sign-in">
    ```typescript theme={null}
    const user = await ctx.auth.getUserIdentity();
    return await ctx.db
      .query("posts")
      .withIndex("by_visibility",
        q => q.eq("visibility", user ? "members" : "public"))
      .collect();
    ```
  </Tab>

  <Tab title="Role check">
    ```typescript theme={null}
    const user       = await ctx.auth.getUserIdentity();
    const membership = await ctx.db
      .query("memberships")
      .withIndex("by_user_and_workspace",
        q => q.eq("userId", user.subject).eq("workspaceId", workspaceId))
      .unique();
    if (membership?.role !== "admin") throw new Error("Permission denied");
    ```
  </Tab>
</Tabs>

## Related

<CardGroup cols={3}>
  <Card title="Built-in auth" icon="lock" href="/features/auth/built-in-auth">
    The auth system overview.
  </Card>

  <Card title="Roles & permissions" icon="shield-check" href="/features/auth/roles-and-permissions">
    Role-based access patterns.
  </Card>

  <Card title="Data access control" icon="users-round" href="/security/data-access-control">
    Security best practices.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.