Skip to content
cloudflare-zero-trust-access logo

Cloudflare Zero Trust Access Skill

cloudflare-zero-trust-access

Cloudflare Zero Trust Access authentication for Workers. Use for JWT validation, service tokens, CORS, or encountering preflight blocking, cache race conditions, missing JWT headers.

SKILL.md

Full skill instructions

Cloudflare Zero Trust Access Skill

Integrate Cloudflare Zero Trust Access authentication with Cloudflare Workers applications using proven patterns and templates.


Overview

This skill provides complete integration patterns for Cloudflare Access, enabling application-level authentication for Workers without managing your own auth infrastructure.

What is Cloudflare Access? Cloudflare Access is Zero Trust authentication that sits in front of your application, validating users before they reach your Worker. After authentication, Access issues JWT tokens that your Worker validates.

Key Benefits:

  • No auth infrastructure to maintain
  • Integrates with identity providers (Azure AD, Google, Okta, GitHub)
  • Service tokens for machine-to-machine auth
  • Built-in MFA and session management
  • Comprehensive audit logs

When to Use This Skill

Trigger this skill when tasks involve:

  • Authentication: Protecting Worker routes, securing admin dashboards, API authentication
  • Access Control: Role-based access (RBAC), group-based permissions, geographic restrictions
  • Service Auth: Backend services calling Worker APIs, CI/​CD pipelines, cron jobs
  • Multi-Tenant: SaaS apps with organization-level authentication
  • CORS + Auth: Single-page applications calling protected APIs

Keywords to Trigger: cloudflare access, zero trust, access authentication, JWT validation, service tokens, cloudflare auth, hono access, workers authentication, protect worker routes, admin authentication


Integration Patterns

📖 New to Cloudflare Access? Load references/​quick-start.md for step-by-step setup instructions (15-20 minutes).

Pattern 1: Hono Middleware (Recommended)

Use @hono/​cloudflare-access for one-line Access integration.

When to Use:

  • Building with Hono framework
  • Need quick, production-ready setup
  • Want automatic JWT validation and key caching

Template: templates/​hono-basic-setup.ts

Setup:

import { Hono } from 'hono'
import { cloudflareAccess } from '@hono/​cloudflare-access'

const app = new Hono<{ Bindings: Env }>()

// Public routes
app.get('/', (c) => c.text('Public page'))

// Protected routes
app.use(
  '/​admin/​*',
  cloudflareAccess({
    domain: (c) => c.env.ACCESS_TEAM_DOMAIN,
  })
)

app.get('/​admin/​dashboard', (c) => {
  const { email } = c.get('accessPayload')
  return c.text(`Welcome, ${email}!`)
})

Configuration (wrangler.jsonc):

{
  "vars": {
    "ACCESS_TEAM_DOMAIN": "your-team.cloudflareaccess.com",
    "ACCESS_AUD": "your-app-aud-tag"
  }
}

Benefits:

  • ✅ Automatic JWT validation
  • ✅ Public key caching (1-hour TTL)
  • ✅ Type-safe with TypeScript
  • ✅ Production-tested and maintained

Pattern 2: Manual JWT Validation

When to Use: Not using Hono, need custom validation logic

Template: templates/​jwt-validation-manual.ts (~100 lines, uses Web Crypto API)


Pattern 3: Service Token Authentication

When to Use: CI/​CD pipelines, backend services, cron jobs (no interactive login)

Client: Send CF-Access-Client-Id + CF-Access-Client-Secret headers

Server: Same middleware handles both - detect via !payload.email && payload.common_name

📄 Full guide: references/​service-tokens-guide.md


Pattern 4: CORS + Access

When to Use: SPA (React/​Vue/​Angular) calling protected API

⚠️ CRITICAL: CORS middleware MUST come BEFORE Access middleware!

// ✅ CORRECT ORDER
app.use('*', cors({ origin: 'https://app.example.com', credentials: true }))
app.use('/​api/​*', cloudflareAccess({ domain: (c) => c.env.ACCESS_TEAM_DOMAIN }))

Why: OPTIONS preflight has no auth headers → Access blocks with 401

📄 Full pattern: templates/​cors-access.ts


Pattern 5: Multi-Tenant

When to Use: SaaS with per-org authentication, white-label apps

Architecture: Tenant config in D1/​KV → Dynamic middleware per request

📄 Full pattern: templates/​multi-tenant.ts and references/​use-cases.md


Common Errors Prevented

This skill prevents 8 documented errors. Full details: references/​common-errors.md

Error #1: CORS Preflight Blocked (45 min saved)

Problem: OPTIONS requests return 401, breaking CORS

Solution: CORS middleware BEFORE Access middleware

// ✅ Correct
app.use('*', cors())
app.use('/​api/​*', cloudflareAccess({ domain: '...' }))

Error #2: Missing JWT Header (30 min saved)

Problem: Request not going through Access, no JWT header

Solution: Access Worker through Access URL, not direct *.workers.dev

✅ https://team.cloudflareaccess.com/​...
❌ https://worker.workers.dev

Error #3: Invalid Team Name (15 min saved)

Problem: Hardcoded or wrong team name causes "Invalid issuer"

Solution: Use environment variables

// ✅ Correct
cloudflareAccess({ domain: (c) => c.env.ACCESS_TEAM_DOMAIN })

// ❌ Wrong
cloudflareAccess({ domain: 'my-team.cloudflareaccess.com' })

Errors #4-8 (Quick Reference)

#ErrorSolution
4Key cache raceUse @hono/​cloudflare-access (auto-caches)
5Wrong service token headersUse CF-Access-Client-Id/​Secret (not Authorization)
6Token expiration (401 after 1 hr)Handle gracefully, redirect to login
7Overlapping policiesUse most specific paths
8Dev/​prod mismatchUse environment-specific configs

📄 Full error details: references/​common-errors.md (~2.5 hours saved per implementation)


Templates

TemplatePurpose
hono-basic-setup.tsStandard Hono + Access integration
jwt-validation-manual.tsManual JWT verification with Web Crypto
service-token-auth.tsService token patterns
cors-access.tsCORS + Access (correct ordering)
multi-tenant.tsMulti-tenant architecture
wrangler.jsoncComplete Wrangler configuration
.env.exampleEnvironment variable template
types.tsTypeScript definitions

Scripts

ScriptUsage
test-access-jwt.sh./​test-access-jwt.sh <jwt-token> - Decode and validate JWT
create-service-token.sh./​create-service-token.sh [name] - Service token setup guide

Use Cases

Use CaseTemplateKey Point
Admin Dashboardhono-basic-setup.tsEmail domain policy
API Authenticationhono-basic-setup.tsMixed user/​service policy
SPA + APIcors-access.tsCORS before Access!
CI/​CD Pipelineservice-token-auth.tsService token in secrets
Multi-Tenant SaaSmulti-tenant.tsD1 tenant config

📄 Detailed use cases: references/​use-cases.md


When to Load References

Reference FileLoad When...
references/​quick-start.mdStep-by-step setup for new users, first-time integration
references/​common-errors.mdDebugging auth issues, prevention patterns (includes all 8 errors)
references/​jwt-payload-structure.mdAccessing JWT claims, user vs service token
references/​service-tokens-guide.mdSetting up machine-to-machine auth
references/​access-policy-setup.mdDashboard configuration, policy creation
references/​use-cases.mdDetailed implementation for specific scenarios
references/​value-proposition.mdToken efficiency metrics, workflow guidance, production validation

Package Versions

PackageVersion
@hono/​cloudflare-access0.3.1
hono4.10.7
@cloudflare/​workers-types4.20251126.0

Verified: 2025-12-14 | Token Savings: ~58% | Production Tested: ✅


When NOT to Use

This skill is for Cloudflare Workers with Cloudflare Access. Do not use for:

  • ❌ Cloudflare Pages (use @cloudflare/​pages-plugin-cloudflare-access instead)
  • ❌ Non-Cloudflare platforms
  • ❌ Custom JWT auth (not Access)
  • ❌ Auth.js or other auth libraries
  • ❌ Self-hosted authentication

For those, use appropriate skills or libraries.


Additional Resources

Cloudflare Documentation:

Packages:

Dashboard:


Skill Version: 1.0.0 Last Updated: 2025-10-28 Errors Prevented: 8 Token Savings: 58% Time Savings: 2.5 hours Production Tested: ✅

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View