The `@authdog/fastify` SDK validates Authdog sessions on Fastify 4 and 5. It registers as a plugin, decorates every request with the resolved session, and gives you a `requireAuth` guard for protected routes. For the model behind it, see [Backend requests](/docs/backend).

## Install

```bash
npm install @authdog/fastify fastify
```

`fastify` is a peer dependency (`^4` or `^5`). The plugin is built on `@authdog/node-commons`.

## Register the plugin

Register `authdogPlugin` with your environment's **public key** (`pk_...`). It decorates each request with `request.authdog` and exposes the guard and logout handler on `app.authdog`:

```ts
import Fastify from "fastify"
import { authdogPlugin } from "@authdog/fastify"

const app = Fastify()
await app.register(authdogPlugin, { publicKey: process.env.PK_AUTHDOG! })
```

The key is validated when the plugin registers. Pass `fetchUserInfo: false` to skip the per-request `userinfo` verification when you only need to detect a token.

`request.authdog` has the shape `{ token, user, isAuthenticated }` and the token is resolved from the `authdog-session` cookie first, then an `Authorization: Bearer <token>` header.

## Protect a route

Use `app.authdog.requireAuth` as a `preHandler`. It rejects unauthenticated requests with `401 { "error": "Unauthorized" }`:

```ts
app.get(
  "/me",
  { preHandler: app.authdog.requireAuth },
  async (req) => req.authdog!.user,
)
```

Resolving a session tells you *who* the caller is — pair it with your environment's [authorization](/docs/concepts/authorization) model to decide *what* they can do.

## Sign out

`app.authdog.logout` clears the `authdog-session` cookie and redirects to a sanitized `?redirect_uri`:

```ts
app.get("/logout", (req, reply) => app.authdog.logout(req, reply))
```

## Service-to-service

Machine-to-machine callers send their token as `Authorization: Bearer <token>`; it resolves on the same path as a browser session and `requireAuth` gates it identically. See [Backend requests](/docs/backend#service-to-service-m2m).

## Next steps

- [Backend requests](/docs/backend) — the verification model across every backend SDK.
- [Express](/docs/backend/express) — the same primitives for Express.
- [Calling the REST API](/docs/api) — read users and organizations once a request is authenticated.
