> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# Manually install the Cloudflare Enforcer

If your organization uses **Cloudflare,** you can use HUMAN's Cloudflare **Enforcer** to protect against malicious behavior. The Cloudflare Enforcer is installed using a Cloudflare **Worker,** or a snippet of code, and is deployed to your content delivery network (CDN). The Enforcer dictates how traffic should be handled per your organization's standards.

You can learn how to install the Cloudflare Enforcer with this article.

> **Warning**
>
> We **highly recommend** using the [Deploy Tool](/applications/general/deploy-tool) method instead of a manual installation if possible. See [Cloudflare's primary installation article](/applications/install-the-cloudflare-enforcer) for more information.

## Prerequisites

* A **Cloudflare account.** You can sign up for an account from [Cloudflare's website.](https://www.cloudflare.com/)
* A **command-line interface (CLI)**.
* A text editor.
* **Node Version Manager (nvm)** installed on your device. See nvm’s [GitHub repository](https://github.com/nvm-sh/nvm?tab=readme-ov-file#installing-and-updating) to learn how to install it.
* The latest version of **Node.js.** After installing nvm, enter `nvm install stable` in your CLI to install it.
* **Wrangler** installed on your device. You can enter `npm install -g wrangler` in your CLI to install it.
* Your unique HUMAN information:
  * Your **Application ID.** You can find this under **Platform Settings > Applications > Overview** in the HUMAN console. If you have multiple environments, you will also have multiple Application IDs, so be sure to choose the correct ID for the environment you want to install on.
  * Your **Server Token.** You can find this under **Platform Settings > Applications > Status & Settings > Server Token.**
  * Your **Risk Cookie Key.** You can find this under **Bot Defender > Policies > Policy Settings > Policy Information.**

## Installation

There are two parts to the Cloudflare Enforcer installation:

1. [Create the Cloudflare worker](#create-the-cloudflare-worker)
2. [Install the HUMAN Enforcer](#install-the-human-enforcer)

The majority of the installation process is done through a CLI.

### Create the Cloudflare Worker

1. In your CLI, enter `npm create cloudflare@latest`. If you’re prompted to install additional packages to complete the installation, hit `y` to do so.

```shell
Need to install the following packages:
create-cloudflare@2.XX.Y
Ok to proceed? y/n
```

2. When prompted, enter a folder name to create your Worker in. This will also be the Worker’s name in your Cloudflare dashboard. In the example below, we've named our folder `human-cloudflare-enforcer`.

```shell
npm create cloudflare@latest

using create-cloudflare version 2.XX.Y
╭ Create an application with Cloudflare Step 1 of 3
│
╰ In which directory do you want to create your application? also used as application name
  ./human-cloudflare-enforcer
```

3. When prompted, select the `Hello World example` option and hit `return` to proceed.

```shell
│ dir ./human-cloudflare-enforcer
│
╰ What type of application do you want to create?
  ● Hello World example
  ○ Framework Starter
  ○ Application Starter
  ○ Template from a GitHub repo
  ◁ Go back

  Select from barebones examples to get started with Workers 
```

4. When prompted, select the `Worker only` option and hit `return` to proceed.

```shell
│ category Hello World example
│
╰ Which template would you like to use?
  ● Worker only
  ○ Static site
  ○ SSR / full-stack app
  ○ Worker + Durable Objects
  ○ Worker + Durable Objects + Assets
  ○ Scheduled Worker (Cron Trigger)
  ○ Queue consumer & producer Worker
  ○ API starter (OpenAPI compliant)
  ◁ Go back
```

5. Select whether to install the Worker using TypeScript or JavaScript. Do not choose Python. By default, the Worker will install in JavaScript.

> **Note**
>
> Whether you use TypeScript or JavaScript is up to you, but be sure to **remember what you choose.** Later in the installation, you will need to choose the code snippet that corresponds to the language you installed in.

```shell
│ type Worker only
│
╰ Which language do you want to use?
  ● TypeScript
  ○ JavaScript
  ○ Python (beta)
  ◁ Go back
```

6. When prompted, select `No` to deploying your application.

```shell
╭ Deploy with Cloudflare Step 3 of 3
│
╰ Do you want to deploy your application?
  Yes / No
```

Afterwards, you should receive a success message that reads `APPLICATION CREATED`. This means you created a basic Cloudflare Worker, and you're ready to move on to installing the HUMAN Enforcer.

### Install the HUMAN Enforcer

1. In your CLI, enter `cd folder_name` to open the folder you created in **Create the Cloudflare Worker, Step 2.** Based on our earlier example, we would enter `cd human-cloudflare-enforcer`.
2. Enter `npm i --save @humansecurity/cloudflare-enforcer`. This will install the latest Cloudflare Enforcer from HUMAN.
3. Enter `cd src`.
4. In your preferred text editor, open either `index.ts` or `index.js` depending on your choice in **Create the Cloudflare Worker, Step 4**. The `.ts` file is for TypeScript installations, while `.js` is for JavaScript.

> **Note**
>
> You can check the file type you have by entering `ls` while inside the `src` folder. This will show you your `index` file's type.

5. Delete all the code currently in the `index` file. The following snippet shows all the default code you should delete.

```shell
/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */
export default {
        async fetch(request, env, ctx) {
                return new Response('Hello World!');
        },
};
```

6. Copy the appropriate code snippet, either TypeScript or JavaScript, from below and paste it into your `index` file.

> **Note**
>
> In addition to choosing between TypeScript and JavaScript, you must also make sure to pick the right type of Worker. This can either be an ES Module or Service Module, and it depends on your Cloudflare configuration. You can see some examples from both Workers in [Cloudflare's documentation.](https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/)

**`ES Modules Syntax: JavaScript`**

```javascript title="ES Modules Syntax: JavaScript"
import {
    HumanSecurityEnforcer
} from "@humansecurity/cloudflare-enforcer";

const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

export default {
    async fetch(request, env, ctx) {
        // create a new enforcer
        const enforcer = await HumanSecurityEnforcer.initialize(config, env);

        // call enforce
        const retVal = await enforcer.enforce(ctx, request);

        // if enforce returned a response, return that response
        if (retVal instanceof Response) {
            return retVal;
        }

        // retrieve the resource from the cache or origin server
        // make sure to use the value returned from enforce
        const response = await fetch(retVal);

        // call postEnforce and return the resulting response
        return await enforcer.postEnforce(ctx, response);
    },
};
```

**`ES Modules Syntax: TypeScript`**

```typescript title="ES Modules Syntax: TypeScript"
import {
    HumanSecurityEnforcer,
    HumanSecurityConfiguration
} from '@humansecurity/cloudflare-enforcer';

const config: HumanSecurityConfiguration = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

interface Env {
    // If using Human Security features that require the PXKV Namespace
    PXKV: KVNamespace;
}

export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise < Response > {
        // create a new enforcer
        const enforcer = await HumanSecurityEnforcer.initialize(config, env);

        // call enforce
        const retVal = await enforcer.enforce(ctx, request);

        // if enforce returned a response, return that response
        if (retVal instanceof Response) {
            return retVal;
        }

        // retrieve the resource from the cache or origin server
        // make sure to use the value returned from enforce
        const response = await fetch(retVal);

        // call postEnforce and return the resulting response
        return await enforcer.postEnforce(ctx, response);
    },
};
```

**`Service Worker Syntax: JavaScript`**

```javascript title="Service Worker Syntax: JavaScript"
import {
    HumanSecurityEnforcer
} from '@humansecurity/cloudflare-enforcer';

// define an enforcer configuration however you see fit
const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

async function handleEvent(event) {
    // provide the enforcer configuration as an argument and await the returned Promise
    // to receive an instance of the HumanSecurityEnforcer
    const enforcer = await HumanSecurityEnforcer.initialize(config);

    // call enforce
    const retVal = await enforcer.enforce(event);

    // if enforce returned a response, return that response
    if (retVal instanceof Response) {
        return retVal;
    }

    // retrieve the resource from the cache or origin server
    // make sure to use the value returned from enforce
    const response = await fetch(retVal);

    // call postEnforce and return the resulting response
    return await enforcer.postEnforce(event, response);
}

addEventListener('fetch', (event) => {
    event.respondWith(handleEvent(event));
});
```

**`Service Worker Syntax: TypeScript`**

```typescript title="Service Worker Syntax: TypeScript"
import {
    HumanSecurityEnforcer,
    HumanSecurityConfiguration
} from "@humansecurity/cloudflare-enforcer";

const config: HumanSecurityConfiguration = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

async function handleEvent(event: FetchEvent): Promise < Response > {
    // create a new enforcer
    const enforcer = await HumanSecurityEnforcer.initialize(config);

    // call enforce
    const retVal = await enforcer.enforce(event);

    // if enforce returned a response, return that response
    if (retVal instanceof Response) {
        return retVal;
    }

    // retrieve the resource from the cache or origin server
    // make sure to use the value returned from enforce
    const response = await fetch(retVal);

    // call postEnforce and return the resulting response
    return await enforcer.postEnforce(event, response);
}

addEventListener('fetch', (event) => {
    event.respondWith(handleEvent(event));
});
```

7. Update the `px_app_id`, `px_auth_token`, and `px_cookie_secret` fields with your **Application ID, Server Token,** and **Risk Cookie Key** respectively.

> **Note**
>
> These are the **minimum** required fields that **must be completed** in order for the Enforcer to work. You can always return to this file to customize your Enforcer later with our [optional configurations.](/applications/configuration-cloudflare)

```shell
// define an enforcer configuration however you see fit
const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};
```

8. Save and close the file.

9. Enter `npx wrangler deploy` to deploy your Worker. You may be prompted to log in to your Wrangler or Cloudflare account.

10. Navigate to your Cloudflare dashboard and open **Workers & Pages.** Your new Worker with the HUMAN Enforcer should appear with the same name you gave it in **Create the Cloudflare Worker, Step 2.** In our case, the Worker is named **human-cloudflare-enforcer.**

11. Select the **Worker,** then select **Settings > Triggers > Add route** under **Routes**. This is where you can you add URL routes and zones to monitor with the Cloudflare Enforcer. We recommend protecting your full domain, including all pages on your domain, with the pattern `subdomain.apex.com/*`. For example, to protect the full domain of a site with the URL `www.example.com`, you would provide the following fields:

    * **Route:** `www.example.com/*`
    * **Zone:** `example.com`

12. Navigate to the Worker’s **Settings > Variables > KV Namespace Bindings** and select **Create a KV namespace.**

13. Select **Create a namespace** and enter a **name** for it, then select **Add.**

14. Return to your Worker’s **Settings > Variables > KV Namespace Bindings** and select **Add binding.**

15. Create a KV variable with the following fields:

    * **Variable name:** Enter **PXKV**. You **must** set the name to PXKV.
    * **KV Namespace:** Select the Namespace you created in **Step 3.**

16. Select **Deploy.**

17. Navigate back the Cloudflare **dashboard > Websites** and select the domain to trigger the Enforcer’s Worker.

18. Navigate to **Workers Routes** and select **Edit** next to the **Route** to bind your Worker to.

19. In the **Edit route** window that appears, select the **Worker** you created from the dropdown menu and select **Save.**

20. From the route you bound the Worker to, share the **full website address** with HUMAN’s Support team. Once we receive your URL, we will complete the setup for you.

Your Cloudflare Enforcer has been successfully installed with the minimum requirements to monitor activity on your Cloudflare CDN. You can further customize the Enforcer’s behavior by referencing our [configuration options.](/applications/configuration-cloudflare)

Once you finish installing, be sure to contact HUMAN to complete your tuning process.