The `@authdog/astro` SDK adds authentication to server-rendered Astro sites: middleware that resolves the session for every request, a server client for pages and endpoints, and a small client bootstrap. It reads the [session](/docs/concepts/sessions-tokens) Authdog issues.

## Install

```bash
npm install @authdog/astro
```

Requires Astro `^5` or `^6` with SSR enabled (`output: "server"` or `"hybrid"`). The package ships `@authdog/astro/server` and `@authdog/astro/client`.

## Add the middleware

`authdogMiddleware` populates `Astro.locals.authdog` (`{ session, isAuthenticated }`) on every request:

```ts
// src/middleware.ts
import { defineMiddleware } from "astro:middleware"
import { authdogMiddleware } from "@authdog/astro/server"

export const onRequest = defineMiddleware(
  authdogMiddleware({
    publicKey: import.meta.env.PUBLIC_AUTHDOG_PUBLIC_KEY ?? "",
  }),
)
```

Declare the locals type in `src/env.d.ts`:

```ts
interface Locals {
  authdog: import("@authdog/astro/server").AuthdogLocals
}
```

## Read the user in a page

`createAuthdogServer` verifies the session on the server — the enforcement point. Use it in a page's frontmatter:

```astro
---
import { createAuthdogServer } from "@authdog/astro/server"

const authdog = createAuthdogServer({
  publicKey: import.meta.env.PUBLIC_AUTHDOG_PUBLIC_KEY ?? "",
})

const profile = Astro.locals.authdog.isAuthenticated
  ? await authdog.getUser(Astro.request).catch(() => null)
  : null
---
```

## Sign out

Expose an endpoint that calls `authdog.logout`, which clears the cookie and redirects:

```ts
// src/pages/api/logout.ts
import type { APIRoute } from "astro"
export const GET: APIRoute = ({ request }) => authdog.logout(request)
```

## Client bootstrap

Run `initAuthdog()` once on the client to capture the `?token=` from the sign-in redirect and persist the session:

```astro
<script>
  import { initAuthdog } from "@authdog/astro/client"
  initAuthdog()
</script>
```

Pair the server session check with your [authorization](/docs/concepts/authorization) model to decide what an authenticated user may do.

## Next steps

- [Sign up & sign in](/docs/authentication) — the flows behind the redirect.
- [Backend requests](/docs/backend) — the verification model, in depth.
