The `@authdog/gatsby` SDK adds authentication to Gatsby sites: a React provider for the browser and a server client for Gatsby Functions that gives you a real `requireAuth` gate. It reads the [session](/docs/concepts/sessions-tokens) Authdog issues.

## Install

```bash
npm install @authdog/gatsby @authdog/react-elements
```

Requires Gatsby `^5` and React 18 or 19. The `@authdog/react-elements` package supplies the drop-in UI and its stylesheet.

## Wrap the app

Mount `AuthdogProvider` from both browser and SSR runtimes so the session is available everywhere:

```tsx
// gatsby-browser.js and gatsby-ssr.js
import "@authdog/react-elements/styles.css"
import { AuthdogProvider } from "@authdog/gatsby/client"

export const wrapRootElement = ({ element }) => (
  <AuthdogProvider>{element}</AuthdogProvider>
)
```

The provider captures the `?token=` from the sign-in redirect, validates it, and persists the session. Set `GATSBY_AUTHDOG_PUBLIC_KEY` for the browser build.

## Protect a Function

`createAuthdog` runs on the server with your environment's **public key** (`pk_...`, server-only via `PK_AUTHDOG`). Its `requireAuth` wrapper is the enforcement point — it returns `401` for unauthenticated requests and attaches `req.authdog`:

```ts
// src/api/me.ts
import { createAuthdog } from "@authdog/gatsby/server"

const authdog = createAuthdog({ publicKey: process.env.PK_AUTHDOG! })

export default authdog.requireAuth(async (req, res) => {
  res.status(200).json({ user: req.authdog?.user ?? null })
})
```

Re-export the ready-made logout handler for sign-out:

```ts
// src/api/logout.ts
export { logoutHandler as default } from "@authdog/gatsby/server"
```

The client provider is UX only — treat `requireAuth` in your Functions as the security boundary and pair it with your [authorization](/docs/concepts/authorization) model.

## Next steps

- [Component reference](/docs/components) — the `@authdog/react-elements` UI.
- [Backend requests](/docs/backend) — the verification model, in depth.
