# Cloudflare

To use the First-id system via Cloudflare, you can leverage Cloudflare's Workers and Redirect Rules.

The principle is as follows :

  • The Redirect Rule will check if the user has a First-id or not (and if they meet the conditions to obtain one : consent given, etc...).
  • The Redirect Rule will redirect the user to a URL of your choice (for example : https://mysite.tld/first-id) by adding the requested URL path at the base by the user. For example : if the user requests the page /my-page?param1=value1 then the redirection URL will be /first-id/my-page?param1=value1.
  • The Worker will trigger on all routes starting with /first-id/* and redirect the user to the First-id service to obtain their unique identifier.
  • The Worker will then create a Secure first-party cookie on your main domain with the value of the First-id identifier (see Cookie deposit).
  • Finally, the Worker will redirect the user to the initially requested page.

Workers enable the execution of JavaScript code directly on Cloudflare's servers closest to your users. This "serverless" approach (you don't manage the underlying infrastructure, only the code) provides scalability, resilience, and improved processing performance.

CloudFlare Free Plan

This technique is compatible with CloudFlare's free plan. However, note that the free plan includes only 100,000 worker requests per day. If you exceed this quota, requests will be rejected, and you'll need to switch to a paid plan.

Let's see how to set it up :

Prerequisites

We assume here that you have a configured and functional domain with Cloudflare. You must have Node.js v16.13.0 or higher installed. If you are in a Linux / MacOS environment, use NVM (opens new window)

Configuration Order

We recommend setting up the worker first, THEN setting up the Redirect Rule. If you set up the Redirect Rule before the worker, you'll be sending users to pages that don't exist yet.

# Setting up the Worker

# Command Line

Cloudflare has a command-line tool that allows you to develop, test, and deploy the Worker.

Follow Cloudflare's documentation guide (opens new window) to install and configure your working environment.

Important commands for preparation :

npm install -g wrangler
wrangler login

Let's create the worker project :

Example Available

The complete example code is available on our Github (opens new window).

wrangler init firstidworker

You can replace firstidworker with the name you prefer.

The command line will ask you a series of questions. Adapt the answers to your context.

Would you like to use git to manage this Worker? (y/n) Answer y.
Would you like to use TypeScript? (y/n) Answer n to continue with JavaScript for this guide.
No package.json found. Would you like to create one? (y/n) Answer y.
Would you like to create a Worker at <YOUR_WORKER>\src\index.js? Answer y.

Once the package installation is complete, navigate to your working directory :

cd firstidworker

Let's start by editing the worker configuration file : wrangler.toml.

Here's an example file to be adapted according to your Cloudflare usage context :

name = "firstidworker"
main = "src/index.js"
compatibility_date = "2022-09-18"
# adapt the route to your context
route = "*.mysite.tld/first-id/*"

# Override values for `--env preprod` usage
[env.preprod.vars]
FIRST_ID_GATE_URL = "https://gate.preprod.first-id.fr"

# Override values for `--env production` usage
[env.production.vars]
FIRST_ID_GATE_URL = "https://gate.first-id.fr"

We include the URLs of the First-id service as variables in our worker. By default, the URL will be that of our pre-production environment. During deployment in production, the correct URL will be automatically injected.

We need the npm package cookie (opens new window) to facilitate cookie parsing. This is not mandatory; you can do it in native JavaScript. An example is available in the First-id service client-side JavaScript implementation example.

npm i cookie

Now let's edit the index.js file.

import { parse } from 'cookie';

async function handleRequest(request) {
  const COOKIE_LIFETIME_IN_DAY = 180;
  const COOKIE_NAME = 'firstid';
  // extract cookies from request
  const cookie = parse(request.headers.get('Cookie') || '');
  const url = new URL(request.url);

  // parse current request to get queries params
  const queryParams = new URLSearchParams(url.search);

  let firstIdCookie = null;
  if (queryParams.has('firstId') && queryParams.has('redirectUri')) {
    // in this case we just have been redirected from First-id to the home page
    // we will set the cookie with the First-id and go to the final page

    // extract First-id value from query params
    let firstid = queryParams.get('firstId');

    // extract the final uri where we will redirect the user
    const redirectUrl = decodeURIComponent(queryParams.get('redirectUri'));

    // build the firstid cookie header
    firstIdCookie = `${COOKIE_NAME}=${firstid}; path=/; secure; Expires=${new Date(Date.now() + 1000 * 60 * 60 * 24 * COOKIE_LIFETIME_IN_DAY).toUTCString()}`;

    // build the redirect response
    const response = Response.redirect(`${url.protocol}//${url.host}${redirectUrl}`, 302)

    // Clone the response so that it's no longer immutable
    const newResponse = new Response(response.body, response);

    newResponse.headers.set("Set-Cookie", firstIdCookie)

    return newResponse
  }

  if (cookie['firstid'] != null) {
    // in this case, user has already a firstid cookie
    // just continue the request execution
    return await fetch(request);
  } else {
    // extract path in URL
    const urlRedirect = url.pathname.replace('/first-id/', '/')
    // no firstid, go to First-id gate
    const response = Response.redirect(`${FIRST_ID_GATE_URL}?redirectHost=${encodeURIComponent(url.protocol+'//'+url.host + '/first-id/')}&redirectUri=${encodeURIComponent(urlRedirect + (url.search ? '?'+url.search : ''))}`, 302);

    return response
  }
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

Cookie Configuration

You have to create a Secure cookie on your main domain (see Cookie deposit).

You can modify the COOKIE_LIFETIME_IN_DAY constant to adjust the cookie's lifespan on your domain according to your needs.

You can modify the COOKIE_NAME constant to adapt the cookie name to your needs.

URL encoding

The redirectHost and redirectUri parameters must be encoded in urlEncode to be correctly interpreted.

HTTPOnly

To retrieve the firstid cookie in client-side JavaScript, we do not recommend setting the httpOnly attribute.

Now deploy your worker with the command :

Preprod :

wrangler publish --env preprod

Production :

wrangler publish --env production

More information on environments in the CloudFlare documentation (opens new window).

# Via the CloudFlare console

Once the worker has been deployed, you now need to apply it to every route on your site. To do this, go to your Cloudflare dashboard, to the Workers Routes section :

Cloudflare - Menu - Workers Routes

This takes you to the list of routes to which workers apply. Here, we have none :

Cloudflare - List of active worker routes

Click on the button : Add to route.

Here's an example configuration :

Request limit failure mode

We advise you to adapt the Request limit failure mode configuration as shown in the screenshot: Fail open (proceed) This will prevent you from displaying an error to your customers in the event of a Worker service billing / throttling problem. Your users won't have a First-id, but they will arrive at the /first-id/PATH page of your site. Your site must be able to satisfy this page, otherwise your users will get a 404 error.

Cloudflare - Worker route configuration

Here, we apply this worker to routes starting with /first-id/*. Adapt to your needs.

# Command-line deployment

It's possible to automate what we've just done via the Cloudflare Dashboard, using the command line. To do this, we need to adapt our wrangler.toml file as follows :

name = "firstidworker"
main = "src/index.js"
compatibility_date = "2022-09-18"
account_id = "YOUR_ACCOUNT_ID"
# À adapter avec votre route
route = "*.editeur3-first-id.fr/first-id/*"

[env.preprod.vars]
FIRST_ID_GATE_URL = "https://gate.preprod.first-id.fr"

# Override values for `--env production` usage
[env.production.vars]
FIRST_ID_GATE_URL = "https://gate.first-id.fr"

Then, we redeploy :

Preprod :

wrangler publish --env preprod

Production :

wrangler publish --env production

Request limit failure mode

It doesn't seem possible to choose which Request limit failure mode to apply. By default, it will be Fail closed (block), which will display an error page to your users.

# Setting up the Redirect Rule

Go to the Rules tab of your Cloudflare domain, then click on Redirect Rules.

CloudFlare Redirect Rules Menu

Click on the blue Create Rule button.

Complete the form as follows :

CloudFlare Redirect Rules Form

This is the expression to use if you use the Edit expression button :

(http.cookie contains "YOUR_CONSENT_COOKIE" and not http.cookie contains "firstid" and not starts_with(http.request.uri, "/first-id"))

Consent

You must redirect the user once consent has been obtained. In the example above, consent is stored in a cookie named YOUR_CONSENT_COOKIE. You need to adapt the name to your context.

Criteria for triggering the redirect rule

You can adapt the match to your needs. Here, we've chosen to redirect all requests that contain the YOUR_CONSENT_COOKIE cookie, do not contain the firstid cookie, and do not begin with /first-id.

You can add other matches according to your context.

  • The http.cookie variable contains all the HTTP request cookies in string (name=value) separated by a semicolon. Exemple session=8521F670545D7865F79C3D7BEDC29CCE;-background=light.
  • The http.request.uri variable contains the URI of the HTTP request. Example /articles/index?section=539061&expand=comments.

See Cloudflare documentation for variables used in expressions (opens new window)

Here we use 3 conditions :

  • The user has a YOUR_CONSENT_COOKIE this cookie represents the user's consent cookie, and must be adapted to your context.
  • The user doesn't have a firstid cookie (and therefore doesn't have a First-id) adapt the cookie name if you've chosen another name.
  • The user doesn't request a page starting with /first-id (to avoid an infinite loop) adapt the path if you've chosen another path.

If these 3 conditions are met, then the rule will be applied :

  • We redirect the user to the URL of your choice (for example : https://monsite.tld/first-id) by adding the URL requested by the user to the path. Example : The user requests the page /ma-page?param1=value1, so the redirection URL will be /first-id/ma-page?param1=value1.

To achieve this, we use a "Dynamic " type of redirection, which allows the use of variables in the URL (http.request.uri which contains the complete path, including query params) and a (concat) redirection function.

Preserve User Referrer

To preserve the referrer of my user, I must take several actions described here.

Excluding Redirections

Warning, you should not perform redirections for the following file types:

jpe?g|gif|png|json|js|woff2?|map|css|svg|ico|bmp|xml|ttf|txt

Please add a filter on these file types in your configuration.

# Performance

The various tests we've carried out show a media execution time for the above code of 0.8ms (measured by Cloudflare) :

CloudFlare - Worker execution performance

# Cost

For each user you send to the First-id service, you'll consume 2 worker requests :

  • 1 request for the worker preparing the request and redirecting the user to the First-id service.
  • 1 request to deposit the First-id Cookie and redirect the user to the page initially requested.