Authdog

Next.js

View as Markdown

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

npm 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 publishable pk_... key.

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:

// 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:

"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:

// 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, then apply authorization. logoutHandler clears server cookies; clearAuthdogSession() clears only browser local storage, so complete logout should do both.

Next steps

Learn more