Authdog

Fastify

Last updated Jul 11, 2026
View as Markdown

The @authdog/fastify SDK validates Authdog sessions on Fastify 4 and 5. It registers as a plugin, decorates every request with the resolved session, and gives you a requireAuth guard for protected routes. For the model behind it, see Backend requests.

Install

Bash
npm install @authdog/fastify fastify

fastify is a peer dependency (^4 or ^5). The plugin is built on @authdog/node-commons.

Register the plugin

Register authdogPlugin with your environment's public key (pk_...). It decorates each request with request.authdog and exposes the guard and logout handler on app.authdog:

TypeScript
import Fastify from "fastify"
import { authdogPlugin } from "@authdog/fastify"

const app = Fastify()
await app.register(authdogPlugin, { publicKey: process.env.PK_AUTHDOG! })

The key is validated when the plugin registers. Pass fetchUserInfo: false to skip the per-request userinfo verification when you only need to detect a token.

request.authdog has the shape { token, user, isAuthenticated } and the token is resolved from the authdog-session cookie first, then an Authorization: Bearer <token> header.

Protect a route

Use app.authdog.requireAuth as a preHandler. It rejects unauthenticated requests with 401 { "error": "Unauthorized" }:

TypeScript
app.get(
  "/me",
  { preHandler: app.authdog.requireAuth },
  async (req) => req.authdog!.user,
)

Resolving a session tells you who the caller is — pair it with your environment's authorization model to decide what they can do.

Sign out

app.authdog.logout clears the authdog-session cookie and redirects to a sanitized ?redirect_uri:

TypeScript
app.get("/logout", (req, reply) => app.authdog.logout(req, reply))

Service-to-service

Machine-to-machine callers send their token as Authorization: Bearer <token>; it resolves on the same path as a browser session and requireAuth gates it identically. See Backend requests.

Next steps