The `@authdog/gatsby` SDK provides browser callback utilities and a `requireAuth` gate for Gatsby Functions.

## Install

```package-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.

## Handle the browser callback

`AuthdogProvider` only strips `?token=` and reloads. It does not validate, persist, or exchange the token, so it does not make a session available. To retain the callback token for API calls, run `initAuthdog()` instead:

```tsx
// gatsby-browser.js
import React, { useEffect } from "react"
import { initAuthdog } from "@authdog/gatsby/client"

function AuthdogBootstrap({ children }) {
  useEffect(() => {
    initAuthdog()
  }, [])
  return children
}

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

`initAuthdog()` stores tokens that match JWT structure in `localStorage`; this is not cryptographic validation. Set `GATSBY_AUTHDOG_PUBLIC_KEY` for browser configuration. Do not mount `AuthdogProvider` around this bootstrap because it can remove the token first.

## Protect a Function

`createAuthdog` runs on the server with your environment's **public key** (`pk_...`, server-only via `PK_AUTHDOG`). `requireAuth` accepts either `Authorization: Bearer <token>` or an `authdog-session` cookie, validates it through userinfo, returns `401` on failure, and attaches `req.authdog` on success:

```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 })
})
```

Send the browser token explicitly when calling a Function:

```ts
import { initAuthdog } from "@authdog/gatsby/client"

const token = initAuthdog()
const response = await fetch("/api/me", {
  headers: token ? { Authorization: `Bearer ${token}` } : {},
})
```

The SDK does not create `authdog-session`; if you prefer an HttpOnly cookie, implement a server callback that validates the token before setting it.

Re-export the logout handler to clear `authdog-session`:

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

When using the bearer/local-storage flow, also call `clearAuthdogToken()` in the browser. Treat `requireAuth` in 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.
