> ## Documentation Index
> Fetch the complete documentation index at: https://docs.botshield.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Self-Hosted Gateway

> Deploy and customize the BotShield Gate on your own edge infrastructure

# Self-Hosted Gateway

For partners who want full control over their bot protection layer, BotShield provides an open-source gateway template that you deploy on your own infrastructure. Same verification flow, fully customizable.

<Info>
  The self-hosted gateway uses the same BotShield verification as the managed option. You still need an active BotShield account and gate credentials from your [Partner Dashboard](https://console.botshield.ai).
</Info>

## Why Self-Host?

The [managed gateway](/integrations/gate) is the fastest way to get protected -- zero code, managed infrastructure. The self-hosted option is for teams that need:

| Need                        | Self-Hosted Advantage                                                                                            |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **Path-based rules**        | Skip verification for API routes, static assets, health checks, webhooks                                         |
| **Custom branding**         | Match the verification page to your brand -- colors, logo, copy                                                  |
| **Your own infrastructure** | Deploy on your Cloudflare account, or port to Vercel Edge, Deno Deploy, Fastly Compute, AWS CloudFront Functions |
| **Audit and compliance**    | Full visibility into the proxy code -- no hidden behavior, no data collection                                    |
| **Advanced routing**        | Rate limiting, geo-blocking, A/B testing, custom headers before or after verification                            |

## Get the Template

The gateway template is available on GitHub. Clone it, configure it, deploy it.

<CardGroup cols={2}>
  <Card title="View on GitHub" icon="github" href="https://github.com/Bot-Shield/botshield-gate-public">
    Browse the source code, examples, and documentation
  </Card>

  <Card title="Download ZIP" icon="download" href="https://github.com/Bot-Shield/botshield-gate-public/archive/refs/heads/main.zip">
    Download the latest release as a ZIP archive
  </Card>
</CardGroup>

## Quick Start

### 1. Clone the repository

```bash theme={null}
git clone https://github.com/Bot-Shield/botshield-gate-public.git
cd botshield-gate-public
npm install
```

### 2. Get your credentials

From your [Partner Dashboard](https://console.botshield.ai), navigate to **Storefront Gate** and note your:

* **Gate ID** -- identifies your gate configuration
* **JWT Secret** -- the HS256 signing key for session tokens

### 3. Configure

Update `wrangler.toml` with your settings:

```toml theme={null}
[vars]
ORIGIN_HOST = "origin.yourstore.com"   # Your real server
GATE_ID = "gate_abc123"                # From your dashboard
```

Set the JWT secret (never commit this to source control):

```bash theme={null}
npx wrangler secret put BOTSHIELD_JWT_SECRET
# Paste the HS256 key from your dashboard
```

### 4. Create a KV namespace

The gateway caches configuration in Cloudflare KV:

```bash theme={null}
npx wrangler kv namespace create GATE_CACHE
```

Copy the returned `id` into `wrangler.toml`.

### 5. Deploy

```bash theme={null}
npm run deploy
```

Point your domain's DNS to the deployed worker (custom domain or worker route).

## Customization

### Skip verification for specific paths

The template includes an example for bypassing the gate on certain routes -- useful for API endpoints, static assets, health checks, and webhooks.

```typescript theme={null}
// examples/path-allowlist.ts

const ALLOWED_PATHS = [
  '/api/',          // Your API endpoints
  '/health',        // Health checks
  '/favicon.ico',
  '/robots.txt',
];

const ALLOWED_EXTENSIONS = [
  '.css', '.js', '.png', '.jpg', '.svg', '.woff2',
];

export function shouldBypass(url: URL): boolean {
  const path = url.pathname.toLowerCase();
  if (ALLOWED_PATHS.some(p => path === p || path.startsWith(p))) return true;
  if (ALLOWED_EXTENSIONS.some(ext => path.endsWith(ext))) return true;
  return false;
}
```

Import it in `worker/index.ts` and call `shouldBypass(url)` before the session check to proxy matching requests without verification.

### Custom verification page

The verification page is a single function in `worker/gateHtml.ts`. Replace the HTML and CSS to match your brand:

```typescript theme={null}
// worker/gateHtml.ts

export function renderGatePage(host: string, returnTo: string, gateId: string): string {
  const verifyUrl = `https://app.botshield.ai/verify?gate_id=${encodeURIComponent(gateId)}&...`;

  return `<!DOCTYPE html>
<html>
  <body>
    <!-- Your custom branded page here -->
    <h1>Verify to access ${host}</h1>
    <a href="${verifyUrl}">Verify Now</a>
  </body>
</html>`;
}
```

The only requirement is that the verify link points to the BotShield verify URL with the correct parameters. Everything else -- layout, styling, copy, logo -- is yours to customize.

A complete branded example is included at `examples/custom-branding.ts`.

## Platform Compatibility

The gateway template is built for Cloudflare Workers but uses only standard Web APIs (`fetch`, `crypto.subtle`, `Request`, `Response`). It can be adapted to run on any edge platform that supports these APIs:

| Platform                     | Compatibility   | Notes                                                    |
| ---------------------------- | --------------- | -------------------------------------------------------- |
| **Cloudflare Workers**       | Ready to deploy | Template default -- uses `wrangler` CLI                  |
| **Vercel Edge Functions**    | Portable        | Replace KV with Vercel KV or Edge Config                 |
| **Deno Deploy**              | Portable        | Native Web API support, swap KV for Deno KV              |
| **Fastly Compute**           | Portable        | Requires Fastly's Wasm adapter for `crypto.subtle`       |
| **AWS CloudFront Functions** | Partial         | Limited `crypto.subtle` support -- may need Lambda\@Edge |

The core logic (JWT verification, cookie handling, proxying) is \~200 lines of TypeScript with zero npm dependencies beyond dev tooling.

## Architecture

```mermaid theme={null}
flowchart TD
    A["Visitor hits your domain"] --> B["Your Edge Worker"]
    B --> C{"Route?"}
    C -- "Regular path" --> D{"Valid session cookie?"}
    C -- "/gate" --> F["Serve verification page"]
    C -- "/gate/callback" --> H["Validate JWT token"]
    D -- Yes --> E["Proxy to origin server"]
    D -- No --> R["Redirect to /gate"]
    R --> F
    F --> G["User verifies in BotShield app"]
    G --> H
    H --> I["Set session cookie"]
    I --> E

    style A fill:#1a1a2e,stroke:#147baa,color:#fff
    style B fill:#0d2235,stroke:#147baa,color:#147baa
    style C fill:#1a1a2e,stroke:#303030,color:#fff
    style D fill:#1a1a2e,stroke:#303030,color:#fff
    style E fill:#0a3d1a,stroke:#40D78C,color:#40D78C
    style F fill:#1a1a2e,stroke:#303030,color:#fff
    style G fill:#1a1a2e,stroke:#303030,color:#fff
    style H fill:#1a1a2e,stroke:#303030,color:#fff
    style I fill:#0a3d1a,stroke:#40D78C,color:#40D78C
    style R fill:#1a1a2e,stroke:#303030,color:#fff
```

Your edge worker handles everything. The only external dependency is the BotShield verification flow itself -- when a visitor needs to verify, they're directed to `app.botshield.ai` and redirected back with a signed token.

## Security

The self-hosted gateway inherits the same security model as the managed option:

* **HS256 JWT validation** -- tokens are signed with your secret and verified using the Web Crypto API
* **HttpOnly, Secure cookies** -- session tokens can't be accessed by client-side code
* **Header sanitization** -- internal headers and the gate cookie are stripped before proxying to your origin
* **No PII** -- no personal data is stored, logged, or transmitted
* **Open source** -- inspect every line of code that runs in front of your traffic

## Next Steps

<CardGroup cols={2}>
  <Card title="Managed Gateway" icon="toggle-on" href="/integrations/gate">
    Prefer zero-config? Use the managed gateway instead.
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/Bot-Shield/botshield-gate-public">
    Full source code, examples, and setup instructions.
  </Card>

  <Card title="SDK Overview" icon="code" href="/sdk/overview">
    Build deeper integrations with the BotShield API.
  </Card>

  <Card title="Shopify Integration" icon="shop" href="/integrations/shopify">
    Running Shopify? Use the native checkout extension.
  </Card>
</CardGroup>
