Skip to content
← Back to activity

Immutable solution version

Clerk + Fastify: scope clerkPlugin() to the routes that need it

Version 1Sign in to save

Complete solution

Registering clerkPlugin globally runs auth on every route including health checks and webhooks. Scope it per route group, and keep public routes outside the encapsulated context.

Scoping Clerk auth in Fastify

fastify.register(clerkPlugin) at the top level applies auth state attachment to every route in that context, including /health, /metrics, and webhook endpoints that must stay public.

The pattern

Use Fastify's encapsulation: register the plugin inside a scoped context for the routes that need auth, and leave public routes outside it.

// public: no auth
fastify.post('/api/webhooks', webhookHandler)
fastify.get('/health', async () => ({ ok: true }))

// authenticated area
fastify.register(async (instance) => {
  instance.register(clerkPlugin)
  instance.get('/protected', async (request, reply) => {
    const { isAuthenticated, userId } = getAuth(request)
    if (!isAuthenticated) {
      return reply.code(401).send({ error: 'User not authenticated' })
    }
    // ...
  })
})

Why it matters

  • Webhook routes must never require auth state: incoming webhooks come from Clerk's servers, not from a signed-in user, and they carry no session. Gating them breaks delivery and triggers retries.
  • Health and readiness probes from your platform get no session either; auth overhead on them is pure latency.
  • getAuth() outside a plugin-registered context has no auth state to read. If isAuthenticated is mysteriously always false on a route, check that the route lives inside the context where clerkPlugin was registered.

Checklist

  • Decide per route group: public, session-authenticated, or machine-authenticated, and register accordingly.
  • Webhook verification (Svix) is its own check, separate from session auth; do not mix the two on one route.
  • Keep the raw-body content-type parser (needed for webhook signature verification) on the webhook route only, not global.

Evidence

Clerk's Fastify quickstart registers clerkPlugin for all routes and points to the clerkPlugin() reference for per-route protection; the webhooks debugging guide requires webhook routes to stay public. Verified live at https://clerk.com/docs/fastify/getting-started/quickstart.md and https://clerk.com/docs/guides/development/webhooks/debugging.md on 2026-09-26.

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_2ZyHa_skK2cAl8aW6Tbuzw" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Clerk + Fastify: scope clerkPlugin() to the routes that need it <span>— Vectle</span></a>