# Constile gate The Constile gate runs in front of your site. When an AI agent fetches an eligible page for a person, the gate serves the agent a constile offer instead of the article. When the agent accepts, the gate releases the article. Everyone else, including people, search engines, and crawlers, gets your site as usual. This package installs the gate on JavaScript hosts. It has an adapter for each host: Next.js, Vercel, Netlify, Node, Express, Connect, Koa, Fastify, Hono, Astro, SvelteKit, Nuxt, React Router and Remix, Deno, Bun, Fastly Compute, and CloudFront. ## Before you start You need these from your site's page in the Constile publisher dashboard: | Setting | Environment variable | Example | |---|---|---| | Site id | `CONSTILE_SITE_ID` | `site_…` | | Site secret | `CONSTILE_SITE_SECRET` | Keep it in your host's secret store, never in code or logs. | | Network URL | `CONSTILE_NETWORK_URL` | The network's origin, from the dashboard. | To install the package with npm, you need Node.js 20 or later. ## Install the package To install the package, download it from your dashboard's install page, or install it from the URL there: ```sh npm install https:///install/constile-gate-0.6.0.tgz ``` The package has no dependencies. It doesn't import your framework; each adapter fits the shape your framework already passes it. ## How the gate works with your host Read this section once. Each install section below refers back to it. ### Settings Each adapter takes the same options. Where your host has environment variables that the adapter can read, you can leave out `siteId`, `secret`, and `networkUrl`, and the gate reads `CONSTILE_SITE_ID`, `CONSTILE_SITE_SECRET`, and `CONSTILE_NETWORK_URL`. If a setting is missing, the gate passes every request through and logs one warning. | Option | What it does | |---|---| | `siteId`, `secret`, `networkUrl` | The settings from your dashboard. | | `siteUrl` | Your site's public origin, such as `https://example.com`. The gate names pages by it and fetches pages from it. With it set, the gate passes requests for any other host (other than its `www.` twin) through without gating them. | | `timeoutMs` | How long a call to the network may take before the gate gives up and serves the page as usual. The default is 5000. | | `retryAfterMs` | After a failed call for the site's settings, how long the gate passes everything through before it asks again. The default is 30000. | | `disabled` | `true` turns the gate off: every request goes to your site unchanged, and nothing goes to the network. Without it, the gate reads `CONSTILE_DISABLED` (`1`, `true`, `yes`, or `on`) on every request. | | `bypassToken` | The value of the `Constile-Gate-Bypass` header. See [The gate's own requests](#the-gates-own-requests). | | `origin` | A function that fetches a page from your site, in place of the adapter's default. | ### People never wait on the network The gate calls the network only for candidate agent requests, for the gate's own paths (`/sponsored/…` and `/.well-known/constile`), and once per settings refresh. Every call has a deadline. If the network is slow or down, the gate serves your page as if it weren't installed. ### The gate's own requests To make an offer, the gate reads the page the agent asked for. To release an article, it fetches the article. Where it can, the adapter asks your app for the page in process, with `next()` or `resolve()`. Otherwise, it fetches the page from your site again, with the header `Constile-Gate-Bypass`. A request with the right value goes straight to your app and is never gated again. A request with any other value gets `403`. The value comes from `bypassToken`, then `CONSTILE_GATE_BYPASS`, and otherwise from your site secret. If you run more than one instance of your app, give them all the same site secret, or the same `CONSTILE_GATE_BYPASS`. The gate never fetches the address in a request's `Host` header, which a client can forge: - Node servers fetch the page from the socket the request came in on, and keep the `Host` header. - Next.js and Vercel fetch the request's own address only on Vercel, which serves your project only on its own domains. Elsewhere, Next.js needs `siteUrl`. - A released article's address comes from the network, which accepts only your site's domain, or from `siteUrl`. ### The visitor's address The gate sends the network the visitor's address, and the visitor's network number and country where the host knows them. Each adapter reads them only from a source your host controls, never from a header the client can set, such as `X-Forwarded-For`. The install sections name each source. If your app runs behind a proxy or load balancer, set the adapter's `trustProxy` option to the number of proxies in front of it, such as `constileGate({ trustProxy: 1 })`. The gate doesn't use the framework's own setting (`trust proxy` in Express, `proxy` in Koa, `trustProxy` in Fastify): set to trust every proxy, those take the leftmost `X-Forwarded-For` entry, which the visitor writes. In Astro, pass `getClientAddress` if your adapter reads `X-Forwarded-For`. ### Caches The gate sends offers with `Cache-Control: no-store` and `Vary: User-Agent`. If a cache in front of your app serves a cached page before the gate runs, an agent gets the article without an offer. Put the gate in front of your cache, or keep agent requests out of it. ## Paywalled content Gate 0.6.0 and later can fetch a paywalled article with the release instructions the network sends, so an agent gets the full text and the offer fits it. The network gives the gate a page address on your site's own host and, optionally, headers to send: `Cookie`, `Authorization`, `Constile-Paywall-Key`, or a header starting with `X-`. The gate ignores an address on another host and drops other headers. It strips `Set-Cookie` from what it releases and never logs the headers. To set up a method, open your site's page in the dashboard and choose a content API, a paywall rule, or a Constile login. A paywalled page gets offers only after the method works and the gate is 0.6.0 or later. ## Next.js The adapter runs as Next.js Proxy (`proxy.ts`, Next.js 16) or Middleware (`middleware.ts`, earlier versions). Pass the settings in from `process.env`: ```ts // proxy.ts, next to your app or pages folder import { constileGate } from "constile-gate/next"; export const proxy = constileGate({ siteId: process.env.CONSTILE_SITE_ID, secret: process.env.CONSTILE_SITE_SECRET, networkUrl: process.env.CONSTILE_NETWORK_URL, }); export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"], }; ``` On Next.js 15 and earlier, name the file `middleware.ts` and the export `middleware`. The proxy returns nothing for requests it passes, so you can call it first in a proxy of your own: ```ts import type { NextFetchEvent, NextRequest } from "next/server"; const gate = constileGate({ /* settings */ }); export async function proxy(request: NextRequest, event: NextFetchEvent) { const offer = await gate(request, event); if (offer) return offer; // Your own proxy logic. } ``` - **On Vercel**, the gate reads the visitor's address from `X-Real-IP` and the country from `X-Vercel-IP-Country`, which Vercel sets. - **Elsewhere**, set `siteUrl` to your site's public origin. Without it, the gate passes agents through. To send the visitor's address, set `ipHeader` to the header your proxy sets and overwrites, such as `x-real-ip`. ## Vercel (other frameworks) For frameworks other than Next.js and Astro, use Vercel Routing Middleware. Create `middleware.ts` at your project root: ```ts import { constileGate } from "constile-gate/vercel"; export default constileGate(); ``` Set `CONSTILE_SITE_ID`, `CONSTILE_SITE_SECRET`, and `CONSTILE_NETWORK_URL` in your project's environment variables. The visitor's address comes from `X-Real-IP` and the country from `X-Vercel-IP-Country`. ## Netlify Run the gate as a Netlify Edge Function. Create `netlify/edge-functions/constile-gate.ts`: ```ts import { constileGate } from "constile-gate/netlify"; export default constileGate(); export const config = { path: "/*" }; ``` Set the three environment variables in your site's settings, with a scope that includes Functions. The gate reads the page with `context.next()`, the visitor's address from `context.ip`, and the country from `context.geo`. ## Node.js `http` Wrap your request listener: ```ts import http from "node:http"; import { withConstileGate } from "constile-gate/node"; http.createServer(withConstileGate(app)).listen(3000); ``` The visitor's address is the socket's. If your server runs behind proxies that set `X-Forwarded-For`, set `trustProxy` to how many there are. ## Express Add the middleware before your routes: ```ts import express from "express"; import { constileGate } from "constile-gate/express"; const app = express(); app.use(constileGate()); ``` The visitor's address is `req.ip`, which follows your app's `trust proxy` setting. ## Connect ```ts import connect from "connect"; import { constileGate } from "constile-gate/connect"; const app = connect(); app.use(constileGate()); ``` The visitor's address is the socket's, unless you set `trustProxy`. ## Koa ```ts import Koa from "koa"; import { constileGate } from "constile-gate/koa"; const app = new Koa(); app.use(constileGate()); ``` The visitor's address is `ctx.ip`, which follows your app's `proxy` and `maxIpsCount` settings. ## Fastify Add the gate as an `onRequest` hook: ```ts import Fastify from "fastify"; import { constileGate } from "constile-gate/fastify"; const app = Fastify(); app.addHook("onRequest", constileGate()); ``` The visitor's address is `request.ip`, which follows your app's `trustProxy` setting. ## Hono ```ts import { Hono } from "hono"; import { constileGate } from "constile-gate/hono"; const app = new Hono(); app.use(constileGate()); ``` The gate reads the visitor's address from your runtime: `request.cf` and `CF-Connecting-IP` on Cloudflare Workers, the socket on Node, the server on Bun, and the connection on Deno. On other hosts, pass Hono's `getConnInfo` helper for your runtime: ```ts import { getConnInfo } from "hono/vercel"; app.use(constileGate({ getConnInfo })); ``` On Cloudflare Workers, read the settings from `env` in `cloudflare:workers`: ```ts import { env } from "cloudflare:workers"; app.use(constileGate({ siteId: env.CONSTILE_SITE_ID, secret: env.CONSTILE_SITE_SECRET, networkUrl: env.CONSTILE_NETWORK_URL })); ``` ## Astro Add the gate to `src/middleware.ts`: ```ts import { constileGate } from "constile-gate/astro"; export const onRequest = constileGate(); ``` If you have middleware of your own, run both with `sequence(constileGate(), yours)` from `astro:middleware`. The gate runs on pages rendered on demand. Astro runs middleware for prerendered pages when it builds them, and the gate leaves those alone. The visitor's address is `context.clientAddress`, which your Astro adapter sets. On Node, the gate reads its settings from the environment. On other hosts, pass them with `getSecret` from `astro:env/server`. ## SvelteKit Add the gate to `src/hooks.server.ts`: ```ts import { env } from "$env/dynamic/private"; import { constileGate } from "constile-gate/sveltekit"; export const handle = constileGate({ siteId: env.CONSTILE_SITE_ID, secret: env.CONSTILE_SITE_SECRET, networkUrl: env.CONSTILE_NETWORK_URL }); ``` If you have a `handle` of your own, run both with `sequence(constileGate(), yours)` from `@sveltejs/kit/hooks`. The gate skips prerendering and your app's own requests through `event.fetch`. The visitor's address is `event.getClientAddress()`, which your SvelteKit adapter sets. ## Nuxt Add server middleware in `server/middleware/constile-gate.ts`: ```ts import { constileGate } from "constile-gate/nuxt"; export default constileGate(); ``` The adapter works with h3 version 1, which Nuxt 3 and 4 use. The visitor's address is the one your Nitro preset sets, or the socket's. Behind proxies, set `trustProxy`. ## React Router and Remix Wrap the request handler from `createRequestHandler`, on servers that call it with a web `Request` (Cloudflare, Deno, Bun, or a server of your own): ```ts import { createRequestHandler } from "react-router"; import { withConstileGate } from "constile-gate/react-router"; const handler = withConstileGate(createRequestHandler(build), { // Your host's trusted address for the request, for example from its load context. getClientAddress: (request, context) => context.clientAddress, }); ``` For Remix, import from `constile-gate/remix`. A web `Request` carries no address, so without `getClientAddress` the gate sends none. On Express, use the Express adapter in front of React Router's Express handler instead. ## Deno Install the package into your project with npm, so it's in `node_modules` next to your `package.json`, where Deno finds it. Then wrap your handler: ```ts import { withConstileGate } from "constile-gate/deno"; Deno.serve(withConstileGate((request) => app(request))); ``` Run with `--allow-env` so the gate can read its settings, and `--allow-net`. The visitor's address is the connection's. ## Bun ```ts import { withConstileGate } from "constile-gate/bun"; Bun.serve({ fetch: withConstileGate((request) => app(request)) }); ``` The gate runs for requests that reach `fetch`. Routes in `Bun.serve`'s `routes` option skip it. The visitor's address is the socket's. ## Fastly Compute Fastly sends every request to a named backend. In your service, add a backend for your site and one for the network's host. Fastly Compute has no environment variables, so read the settings from a secret store: ```ts import { SecretStore } from "fastly:secret-store"; import { constileGate } from "constile-gate/fastly"; const store = new SecretStore("constile"); const gate = (async () => constileGate({ siteId: (await store.get("CONSTILE_SITE_ID"))?.plaintext(), secret: (await store.get("CONSTILE_SITE_SECRET"))?.plaintext(), networkUrl: (await store.get("CONSTILE_NETWORK_URL"))?.plaintext(), originBackend: "origin", networkBackend: "constile_network", }))(); addEventListener("fetch", (event) => event.respondWith(gate.then((g) => g(event)))); ``` The visitor's address, network number, and country come from `event.client`. ## CloudFront (Lambda@Edge) Run the gate as a Lambda@Edge function on your distribution's origin-request trigger. Lambda@Edge has no environment variables, so build the settings into the function from your build system's secret store. Don't commit the secret. ```ts import { constileGate } from "constile-gate/cloudfront"; export const handler = constileGate({ siteId: "…", secret: "…", networkUrl: "…", siteUrl: "https://example.com" }); ``` Set `siteUrl` to your site's public address. CloudFront sends the origin's host name to the function unless the origin request policy forwards `Host`, and the network makes no offers on a page under another host name. Bundle the handler into one file, for example with esbuild, and deploy it in `us-east-1`. Then configure the cache behavior: - In the origin request policy, include the `User-Agent`, `Cookie`, `Signature`, `Signature-Input`, and `Signature-Agent` headers, and all query strings. Without `User-Agent`, the gate sees every request as CloudFront's. - To send the country and network number, add `CloudFront-Viewer-Country` and `CloudFront-Viewer-ASN` to the origin request policy, and set `viewerHeaders: true`. Don't set it otherwise: only then does CloudFront overwrite values a viewer sends. - In the cache policy, set the minimum TTL to 0, and leave `User-Agent` out of the cache key. CloudFront caches responses that origin-request functions generate when the minimum TTL is above 0, even with `Cache-Control: no-store`, so a higher minimum could serve one agent's offer to others. With `User-Agent` in the key, every browser version gets its own cache entry, and people's pages stop coming from the cache. - CloudFront calls the function only when it doesn't have the page cached, so an agent that asks for a cached page gets the page, with no offer. To make more offers, give the paths you offer a short TTL. For an agent's request, the function fetches the page from your origin itself, because origin-response events don't carry the page. It works with custom origins, and with S3 origins that allow public reads. A response the function generates, such as a released article, can be at most 1 MB. The visitor's address is the event's `clientIp`. ## Check your install To check your install, open `https:///.well-known/constile`. It names your site id, the gate's version, and the platform. The dashboard's install check uses the same address. ## Tested versions The adapters are tested against Next.js 16.4, Express 5.3, Connect 3.7, Koa 3.3, Fastify 5.12, Hono 4.13, h3 1.15, Astro 7.4, SvelteKit 3.2, React Router 8.5, Deno 2.9, and Bun 1.3. Other versions that keep the same interfaces should work.