@appwarden/middleware

中文文档
3.17.14发布于 2026/10/30MITTypeScriptES Module构建来源已验证近 30 天下载 2060

Instantly disable all user interaction with your app deployed on Cloudflare or Vercel

原始使用文档
文档目录22 节
  1. Core Features
  2. Feature Compatibility
  3. Configuration
  4. appwardenApiToken (required)
  5. debug (optional)
  6. appwardenApiHostname (optional)
  7. bypassPaths (optional)
  8. website (optional)
  9. api (optional)
  10. multidomainConfig (Cloudflare universal only, optional)
  11. cacheUrl (Vercel only)
  12. vercelApiToken (Vercel only)
  13. Installation
  14. 1. Cloudflare
  15. 2. Vercel
  16. Supported platforms
  17. Agent skills
  18. Contributing
  19. Development
  20. Security
  21. Versioning & dependencies
  22. License

@appwarden/middleware

Docs GitHub npm version npm provenance Test Coverage License: MIT

Core Features

  • Discord Integration: Quarantine your website via Discord commands (/quarantine [un]lock)
  • Instant Quarantine: Immediately redirects all visitors to a lock page when activated to stop in progress attacks.
  • Nonce-based Content Security Policy (See Feature Compatibility): Deploy a nonce-based Content Security Policy (CSP) using HTML rewriting on Cloudflare where supported.
  • Minimal Runtime Overhead: Negligible performance impact by using event.waitUntil for status checks

Feature Compatibility

The table below summarizes which Appwarden features are available on each platform, including quarantine enforcement and Content Security Policy (CSP) support (with or without nonces).

Platform / AdapterPackage / entrypointQuarantineCSPCSP Nonce
Cloudflare – Universal middleware@appwarden/middleware/cloudflare✅✅✅
Cloudflare – Astro@appwarden/middleware/cloudflare/astro✅✅✅
Cloudflare – React Router@appwarden/middleware/cloudflare/react-router✅✅✅
Cloudflare – TanStack Start@appwarden/middleware/cloudflare/tanstack-start✅✅✅
Cloudflare – Next.js (OpenNext adapter)@appwarden/middleware/cloudflare/nextjs✅✅❌
Vercel - Universal middleware@appwarden/middleware/vercel✅✅❌

Nonce-based CSP requires HTML rewriting and is only available on Cloudflare. Next.js on Cloudflare (OpenNext) and Vercel Edge Middleware apply CSP headers only and do not support nonces. If you are using Next.js on Cloudflare, please use the Cloudflare Universal middleware for CSP nonce support.

Configuration

The following options are shared across the Cloudflare and Vercel middleware bundles. You must provide at least one of website, api, or multidomainConfig (Cloudflare universal only) so Appwarden knows which requests to protect.

appwardenApiToken (required)

The Appwarden API token used to authenticate requests to the Appwarden API. See the API token management guide for details on creating and managing your token.

Treat this token as a secret (similar to a password): do not commit it to source control and store it in environment variables or secret management where possible. Appwarden stores API tokens using AES-GCM encryption and does not display them after creation.

debug (optional)

Defaults to false. Set to true (or the string "true") during initial setup to log lock checks and configuration issues. Disable in production once the integration is stable.

appwardenApiHostname (optional)

Reserved for internal testing. Leave unset to use the production Appwarden API.

bypassPaths (optional)

An array of path patterns that should always pass through without a lock check. Patterns match exact paths and subpaths at segment boundaries. A trailing /* is optional.

bypassPaths: ["/health", "/api/health"]

website (optional)

Configure website quarantine and CSP.

  • lockPageSlug – relative path to redirect to when the site is locked. Defaults to /maintenance.

  • cspMode – optional CSP mode: "disabled", "report-only", or "enforced". When omitted, no CSP header is applied.

  • cspDirectives – optional CSP directives object, or a JSON string. For example:

    website: {
      lockPageSlug: "/maintenance",
      cspMode: "enforced",
      cspDirectives: {
        "script-src": ["'self'", "{{nonce}}"],
        "style-src": ["'self'", "{{nonce}}"],
      },
    }
    

To add a nonce to a directive (see Feature Compatibility), include the "{{nonce}}" placeholder in the list of sources.

api (optional)

Configure API quarantine.

  • basePaths – array of path patterns to treat as API routes. Defaults to ["/"].
  • response – optional response to return when an API route is locked:
    • status – defaults to 503
    • body – defaults to {"error":"Service unavailable"}
    • headers – optional array of { name, value }
api: {
  basePaths: ["/api"],
  response: {
    status: 503,
    body: '{"error":"Service unavailable"}',
    headers: [{ name: "Content-Type", value: "application/json" }],
  },
}

multidomainConfig (Cloudflare universal only, optional)

Per-hostname overrides. Each key is a hostname and each value can override website, api, bypassPaths, and debug. Domain-specific values take precedence over top-level values.

multidomainConfig: {
  "app.example.com": {
    website: { lockPageSlug: "/maintenance-app" },
  },
  "api.example.com": {
    api: { basePaths: ["/api"] },
  },
}

cacheUrl (Vercel only)

The URL or connection string of the cache provider (for example, Upstash or Vercel Edge Config) that stores the quarantine status for your domain. See the Vercel integration guide for cache provider configuration details.

vercelApiToken (Vercel only)

A Vercel API token that Appwarden uses to manage the Vercel Edge Config cache provider that synchronizes the quarantine status of your domain. See the Vercel integration guide for cache provider configuration details.

Appwarden never stores or logs your Vercel API token; it is used only to manage the quarantine status cache for your domain.

Installation

Compatible with websites powered by Cloudflare or Vercel.

For more background and advanced configuration, see the Appwarden documentation.

1. Cloudflare

1.1 Universal Middleware (direct Cloudflare Worker usage)

The Universal Middleware (@appwarden/middleware/cloudflare) supports any website deployed on Cloudflare. It deploys as a standalone Cloudflare Worker and incurs additional usage-based charges. The easiest way to deploy this universal middleware is via our build-cloudflare-action; see the Cloudflare integration guide for workflow details. If you prefer to manage your own Cloudflare Worker instead of using the GitHub Action, you can mount the universal Cloudflare middleware directly using the @appwarden/middleware/cloudflare bundle:

// src/worker.ts
import { createAppwardenMiddleware } from "@appwarden/middleware/cloudflare"

const appwardenHandler = createAppwardenMiddleware((cloudflare) => ({
  debug: cloudflare.env.DEBUG,
  appwardenApiToken: cloudflare.env.APPWARDEN_API_TOKEN,
  website: {
    lockPageSlug: cloudflare.env.APPWARDEN_LOCK_PAGE_SLUG,
    cspMode: cloudflare.env.CSP_MODE,
    cspDirectives: cloudflare.env.CSP_DIRECTIVES,
  },
  api: {
    basePaths: ["/api"],
  },
  bypassPaths: ["/health"],
}))

export default {
  fetch(request: Request, env: CloudflareEnv, ctx: ExecutionContext) {
    return appwardenHandler(request, env, ctx)
  },
}

See the Cloudflare integration docs on appwarden.io for environment variable setup and deployment details.

1.2 Cloudflare framework adapters

If you are using a supported framework, you can mount Appwarden inside your application using framework-specific adapters. This approach incurs no additional cost.

Framework adapters can also sync Appwarden-managed lock page and CSP settings into your build:

  1. Add a build hook such as "prebuild": "appwarden-link --fqdn=your.app"
  2. Import .appwarden/linked/middleware.json
  3. Merge that generated config with code-level overrides by calling getAppwardenConfiguration(generatedConfig, overrides)

Values passed in overrides take precedence over the generated config.

Astro on Cloudflare
// src/middleware.ts
import {
  createAppwardenMiddleware,
  getAppwardenConfiguration,
} from "@appwarden/middleware/cloudflare/astro"
import { sequence } from "astro:middleware"
import { env } from "cloudflare:workers"
import appwardenConfig from "../.appwarden/linked/middleware.json"

const appwarden = createAppwardenMiddleware(() =>
  getAppwardenConfiguration(appwardenConfig, {
    appwardenApiToken: env.APPWARDEN_API_TOKEN,
  }),
)

export const onRequest = sequence(appwarden)

See the Astro + Cloudflare guide for more details.

React Router on Cloudflare
  • Set future.v8_middleware: true in your react-router.config.ts file
// app/root.tsx
import {
  createAppwardenMiddleware,
  getAppwardenConfiguration,
} from "@appwarden/middleware/cloudflare/react-router"
import { env } from "cloudflare:workers"
import appwardenConfig from "../.appwarden/linked/middleware.json"

export const middleware = [
  createAppwardenMiddleware(() =>
    getAppwardenConfiguration(appwardenConfig, {
      appwardenApiToken: env.APPWARDEN_API_TOKEN,
    }),
  ),
]

See the React Router + Cloudflare guide for more details.

TanStack Start on Cloudflare
// start.ts
import {
  createAppwardenMiddleware,
  getAppwardenConfiguration,
} from "@appwarden/middleware/cloudflare/tanstack-start"
import { createMiddleware, createStart } from "@tanstack/react-start"
import { env } from "cloudflare:workers"
import appwardenConfig from "../.appwarden/linked/middleware.json"

const appwardenMiddleware = createMiddleware().server(
  createAppwardenMiddleware(() =>
    getAppwardenConfiguration(appwardenConfig, {
      appwardenApiToken: env.APPWARDEN_API_TOKEN,
    }),
  ),
)

export const startInstance = createStart(() => ({
  requestMiddleware: [appwardenMiddleware],
}))

See the TanStack Start + Cloudflare guide for more details.

Next.js on Cloudflare (OpenNext)
// middleware.ts or proxy.ts
import {
  createAppwardenMiddleware,
  getAppwardenConfiguration,
} from "@appwarden/middleware/cloudflare/nextjs"
import appwardenConfig from "./.appwarden/linked/middleware.json"

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

export default createAppwardenMiddleware((runtime) =>
  getAppwardenConfiguration(appwardenConfig, {
    appwardenApiToken: runtime.env.APPWARDEN_API_TOKEN,
  }),
)

This adapter applies CSP headers only before origin (no HTML rewriting, no nonce injection). Nonce-based CSP ({{nonce}}) is not supported in this adapter; CSP directives must not include {{nonce}}.

2. Vercel

To use Appwarden as Vercel Edge Middleware, use the @appwarden/middleware/vercel bundle:

// middleware.ts (Next.js app on Vercel)
import {
  createAppwardenMiddleware,
  getAppwardenConfiguration,
} from "@appwarden/middleware/vercel"

const appwardenMiddleware = createAppwardenMiddleware(
  getAppwardenConfiguration(
    {},
    {
      // Edge Config or Upstash KV URL
      cacheUrl: process.env.APPWARDEN_CACHE_URL!,
      // Required when using Vercel Edge Config
      vercelApiToken: process.env.APPWARDEN_VERCEL_API_TOKEN!,
      appwardenApiToken: process.env.APPWARDEN_API_TOKEN!,
      debug: true,
      website: {
        lockPageSlug: "/maintenance",
        cspMode: "report-only",
        cspDirectives: {
          "default-src": ["'self'"],
        },
      },
      api: {
        basePaths: ["/api"],
      },
      bypassPaths: ["/health"],
    },
  ),
)

export default appwardenMiddleware

Nonce-based CSP ({{nonce}}) is not supported in Vercel Edge Middleware; CSP directives must not include {{nonce}}.

Supported platforms

Agent skills

This repository ships TanStack Intent skills under skills/ so coding agents can discover and apply Appwarden installation, configuration, and troubleshooting guidance.

After installing @appwarden/middleware, configure your agent to use the skills:

npx @tanstack/intent@latest install

Optionally, install agent hooks so edits are gated until a skill is loaded (Claude Code and Codex):

npx @tanstack/intent@latest hooks install

Then load a specific skill when working on a task:

npx @tanstack/intent@latest load @appwarden/middleware#appwarden-middleware-get-started

List available skills:

npx @tanstack/intent@latest list

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes using the Conventional Commits format
    • This project enforces commit message format with commitlint
    • Examples:
      • feat: add new feature
      • fix: resolve issue with X
      • docs: update README
      • chore: update dependencies
      • test: add tests for feature X
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development

# Install dependencies
pnpm install

# Build the package
pnpm build

# Run tests
pnpm test

Security

Please review our security policy for details on how we handle vulnerabilities and how to report a security issue.

This package is published with npm trusted publishers, to prevent npm token exfiltration, and provenance enabled, which provides a verifiable link between the published package and its source code. For more information, see npm provenance documentation.

Versioning & dependencies

  • This project uses Conventional Commits and automated release tooling to keep versions and the changelog up to date.
  • Patch releases may include bug fixes and internal maintenance or dependency updates (for example, Cloudflare Workers types, Wrangler, and GitHub Action tooling). New features are shipped in minor releases.
  • See CHANGELOG.md for the complete release history.

License

This project is licensed under the MIT License - see the LICENSE file for details.

版本与发布记录

@appwarden/middleware 共发布 97 个版本,首次发布于 2024/09/11;过去 12 个月发布了 73 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.17.14latest2026/10/308 天前
3.17.132026/10/299 天前
3.17.122026/10/2810 天前
3.17.112026/10/2810 天前
3.17.102026/10/2811 天前
3.17.92026/10/1425 天前

关于 @appwarden/middleware 的常见问题

@appwarden/middleware 是什么?

Instantly disable all user interaction with your app deployed on Cloudflare or Vercel

如何安装 @appwarden/middleware?

在项目目录运行 npm install @appwarden/middleware,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 appwarden-link,可以用 npx appwarden-link 直接运行。

@appwarden/middleware 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@appwarden/middleware 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@appwarden/middleware 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.14.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@appwarden/middleware 可以商用吗?

@appwarden/middleware 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@appwarden/middleware 的下载量有多少?

根据 npm 官方下载统计,@appwarden/middleware 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,060 次,日均约 69 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@appwarden/middleware 还在维护吗?

最新版本 3.17.14 发布于 2026/10/30(8 天前);至今共发布 97 个版本,其中过去 12 个月发布了 73 个;首次发布于 2024/09/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。