The `@authdog/nextjs-app` SDK integrates Authdog with the Next.js App Router: a client provider, `useAuth`/`useUser` hooks, and server helpers for callback exchange and logout.

## Install

```package-install
@authdog/nextjs-app
```

Supports Next.js 15/16 and React 18 or 19. Set `NEXT_PUBLIC_PK_AUTHDOG` for client calls and `PK_AUTHDOG` for server helpers. Both contain the same public key (`pk_...`).

## Wrap your app

Mount `AuthdogProvider` in the root layout. It stores a `?token=` value only when it has three JWT-shaped segments, then strips the URL. This regex is a shape check, not signature, issuer, audience, or expiry validation:

```tsx
// app/layout.tsx
import { AuthdogProvider } from "@authdog/nextjs-app/client"

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <AuthdogProvider>{children}</AuthdogProvider>
      </body>
    </html>
  )
}
```

## Read the user

`useUser` calls Authdog userinfo and returns the current profile. `useAuth` only reports whether a browser token exists; do not use it to authorize protected work:

```tsx
"use client"
import { useUser } from "@authdog/nextjs-app"

export default function Dashboard() {
  const { user, isLoading } = useUser()
  if (isLoading) return null
  if (!user) return <p>Not signed in</p>
  return <p>Signed in as {user.emails?.[0]?.value}</p>
}

// useAuth() -> { token, isAuthenticated, isLoading }
```

## Exchange the callback

`useAuthMiddleware(publicKey)` processes `?token=` on matching requests, validates it through Authdog userinfo, and writes HttpOnly cookies. It does **not** protect routes or validate cookies on later requests:

```ts
// middleware.ts
import { useAuthMiddleware } from "@authdog/nextjs-app/server"
export default useAuthMiddleware(process.env.PK_AUTHDOG!)

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
}
```

Return from hosted sign-in to a URL matched by this middleware. For protected Route Handlers or Server Actions, independently validate the credential on every request with a [backend SDK](/docs/backend), then apply [authorization](/docs/concepts/authorization). `logoutHandler` clears server cookies; `clearAuthdogSession()` clears only browser local storage, so complete logout should do both.

## Next steps

- [Component reference](/docs/components): the `@authdog/react-elements` UI used with the provider.
- [Backend requests](/docs/backend): validate the same session on your API routes.
- [Quickstarts](/docs/quickstarts): the five-minute path.
