---
title: "Monitorare le richieste dei crawler IA su AWS con HitKeep | HitKeep"
description: "Raccogli le richieste dei crawler IA per i siti serviti da CloudFront o da altri servizi edge di AWS e inoltrale a HitKeep AI Visibility."
canonical: "https://hitkeep.com/it/guides/tracking/ai-fetch-aws/"
---

# Monitorare le richieste dei crawler IA su AWS con HitKeep

Se il sito è servito tramite **AWS CloudFront**, **S3** o un servizio edge di AWS simile, HitKeep non vede direttamente le richieste dei crawler IA. Inoltra le richieste lato server a:

`POST /api/sites/{id}/ingest/ai-fetch`

Per il contratto di acquisizione indipendente dal fornitore, i campi, la convalida e le integrazioni al di fuori di AWS, consulta la [raccolta delle richieste IA](https://hitkeep.com/it/guides/tracking/ai-fetch-ingest/). Qui trovi l’implementazione con CloudFront, S3 e Lambda.

La configurazione più semplice per la produzione funziona così:

1. CloudFront invia i log standard a S3.
2. Una funzione AWS Lambda analizza ciascun oggetto di log.
3. Inoltra le richieste dei crawler IA a HitKeep con un token API ad ambito limitato.

Usiamo questa configurazione per siti statici come `hitkeep.com`.

## Prerequisiti

- Un sito già creato in HitKeep per il dominio da monitorare
- Un **client API del team** o un client API personale con accesso al sito
- Una distribuzione CloudFront che serve il sito
- Un bucket S3 per i log standard di CloudFront
- Una funzione Lambda nello stesso account AWS

## Creare il token HitKeep

Per prima cosa crea un token API limitato al sito:

1. Apri **Settings → API Clients** per un token personale oppure **Administration → Team → Settings** per un token del team.
2. Crea un token con accesso al sito di destinazione.
3. Copia subito il token.

Guida ai [client API](https://hitkeep.com/it/guides/security/api-clients/)

Prepara questi valori:

- `HITKEEP_BASE_URL` Esempio: `https://cloud.hitkeep.eu`
- `HITKEEP_SITE_ID` Esempio: `6d5f9e7b-...`
- `HITKEEP_API_TOKEN`
- `HITKEEP_HOSTNAME` Esempio: `hitkeep.com`

## Attivare i log standard di CloudFront

Nella distribuzione CloudFront:

1. Apri **Monitoring and logging**.
2. Attiva **Standard logging**.
3. Scegli un bucket S3 e, se necessario, un prefisso.
4. Mantieni il formato predefinito delimitato da tabulazioni.

A HitKeep bastano questi campi, già presenti nei log standard:

- `cs(User-Agent)`
- `cs-uri-stem`
- `cs-uri-query`
- `x-host-header`
- `sc-status`
- `sc-bytes`
- `time-taken`
- `sc-content-type`

CloudFront consegna i log in lotti, quindi le richieste dei crawler compaiono in HitKeep con un breve ritardo.

## Distribuire la funzione Lambda di inoltro

Ecco un esempio di funzione Lambda:

```
import { gunzipSync } from "node:zlib";
import { buffer } from "node:stream/consumers";

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";

const s3 = new S3Client({});

// for example
const botMatchers = [
  "chatgpt-user",
  "gptbot",
  "claudebot",
  "claude-web",
  "perplexitybot",
  "google-extended",
  "googleother",
  "google-safety",
  "applebot-extended",
  "bytespider",
  "ccbot",
  "meta-externalagent",
  "meta-externalfetcher",
  "amazonbot",
  "cohere-ai",
  "youbot",
  "ai2bot",
  "diffbot",
  "timpibot",
  "imagesiftbot",
  "deepseekbot",
  "petalbot",
];

function getRequiredEnv(name) {
  const value = process.env[name]?.trim();
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

const hitkeepBaseUrl = getRequiredEnv("HITKEEP_BASE_URL").replace(/\/+$/, "");
const hitkeepSiteId = getRequiredEnv("HITKEEP_SITE_ID");
const hitkeepApiToken = getRequiredEnv("HITKEEP_API_TOKEN");
const defaultHostname = process.env.HITKEEP_HOSTNAME?.trim().toLowerCase() || "";
const requestTimeoutMs = Number.parseInt(process.env.HITKEEP_TIMEOUT_MS ?? "10000", 10);

function safeDecode(value) {
  if (!value || value === "-") {
    return "";
  }

  try {
    return decodeURIComponent(value);
  } catch {
    return value;
  }
}

function parseInteger(value) {
  if (!value || value === "-") {
    return undefined;
  }

  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) ? parsed : undefined;
}

function parseDurationMs(value) {
  if (!value || value === "-") {
    return undefined;
  }

  const parsed = Number.parseFloat(value);
  if (!Number.isFinite(parsed) || parsed < 0) {
    return undefined;
  }

  return Math.round(parsed * 1000);
}

function looksLikeAIBot(userAgent) {
  const normalized = userAgent.trim().toLowerCase();
  return botMatchers.some((token) => normalized.includes(token));
}

function normalizePath(stem, query) {
  const base = stem && stem !== "-" ? stem : "/";
  if (!query || query === "-") {
    return base;
  }
  return `${base}?${query}`;
}

function parseCloudFrontLog(content) {
  const lines = content.split("\n").map((line) => line.trim()).filter(Boolean);
  const fieldsLine = lines.find((line) => line.startsWith("#Fields:"));
  if (!fieldsLine) {
    throw new Error("CloudFront log is missing #Fields header");
  }

  const fieldNames = fieldsLine.replace(/^#Fields:\s*/, "").split(/\s+/);
  const records = [];

  for (const line of lines) {
    if (line.startsWith("#")) {
      continue;
    }

    const values = line.split("\t");
    if (values.length !== fieldNames.length) {
      continue;
    }

    const row = Object.fromEntries(fieldNames.map((field, index) => [field, values[index]]));
    const userAgent = safeDecode(row["cs(User-Agent)"]);
    if (!looksLikeAIBot(userAgent)) {
      continue;
    }

    const path = normalizePath(
      safeDecode(row["cs-uri-stem"]),
      safeDecode(row["cs-uri-query"]),
    );
    const statusCode = parseInteger(row["sc-status"]);
    if (!statusCode) {
      continue;
    }

    const hostname =
      safeDecode(row["x-host-header"]) ||
      safeDecode(row["cs(Host)"]) ||
      defaultHostname;
    const normalizedHostname = hostname ? hostname.toLowerCase() : "";

    if (defaultHostname && normalizedHostname && normalizedHostname !== defaultHostname) {
      continue;
    }

    records.push({
      path,
      hostname: normalizedHostname || undefined,
      status_code: statusCode,
      content_type: safeDecode(row["sc-content-type"]) || undefined,
      response_ms: parseDurationMs(row["time-taken"]),
      bytes_served: parseInteger(row["sc-bytes"]),
      user_agent: userAgent,
    });
  }

  return records;
}

async function loadLogObject(bucket, key) {
  const response = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
  const body = await buffer(response.Body);
  const raw = key.endsWith(".gz") ? gunzipSync(body) : body;
  return raw.toString("utf8");
}

async function postFetchRecord(record) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);

  try {
    const response = await fetch(
      `${hitkeepBaseUrl}/api/sites/${hitkeepSiteId}/ingest/ai-fetch`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${hitkeepApiToken}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(record),
        signal: controller.signal,
      },
    );

    if (!response.ok) {
      const message = await response.text();
      throw new Error(`HitKeep ingest failed with ${response.status}: ${message}`);
    }
  } finally {
    clearTimeout(timeout);
  }
}

export const handler = async (event) => {
  let processedFiles = 0;
  let forwardedRecords = 0;

  for (const s3Record of event.Records ?? []) {
    const bucket = s3Record.s3?.bucket?.name;
    const key = s3Record.s3?.object?.key
      ? decodeURIComponent(s3Record.s3.object.key.replace(/\+/g, " "))
      : "";

    if (!bucket || !key) {
      continue;
    }

    const content = await loadLogObject(bucket, key);
    const records = parseCloudFrontLog(content);

    for (const record of records) {
      await postFetchRecord(record);
      forwardedRecords += 1;
    }

    processedFiles += 1;
  }

  return {
    processedFiles,
    forwardedRecords,
  };
};
```

La funzione:

- scarica ogni oggetto di log CloudFront da S3,
- analizza dinamicamente l’intestazione `#Fields`,
- filtra gli user agent dei crawler IA conosciuti, per esempio `GPTBot`, `ClaudeBot`, `PerplexityBot`, `Google-Extended` e `Amazonbot`,
- inoltra le richieste corrispondenti all’endpoint di raccolta IA di HitKeep.

### Ambiente di esecuzione Lambda

Usa:

- **Node.js 22.x** o successivo

### Variabili d’ambiente Lambda

Imposta queste variabili sulla funzione:

```
HITKEEP_BASE_URL=https://cloud.hitkeep.eu
HITKEEP_SITE_ID=YOUR_SITE_UUID
HITKEEP_API_TOKEN=YOUR_BEARER_TOKEN
HITKEEP_HOSTNAME=hitkeep.com
HITKEEP_TIMEOUT_MS=10000
```

### Autorizzazioni IAM

La funzione richiede:

- `s3:GetObject` sul bucket o sul prefisso dei log CloudFront
- autorizzazioni di scrittura standard per CloudWatch Logs

Esempio minimo di policy inline:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::YOUR_LOG_BUCKET/YOUR_PREFIX/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "*"
    }
  ]
}
```

### Creare e caricare il pacchetto

Se usi solo l’esempio a file singolo, crea un archivio ZIP e direttamente la funzione Lambda:

```
aws lambda create-function \
  --function-name hitkeep-ai-fetch-forwarder \
  --runtime nodejs22.x \
  --handler index.handler \
  --zip-file fileb://ai-fetch-cloudfront-forwarder.zip \
  --role arn:aws:iam::123456789012:role/hitkeep-ai-fetch-forwarder \
  --timeout 60 \
  --memory-size 256
```

Per aggiornare una funzione esistente:

```
aws lambda update-function-code \
  --function-name hitkeep-ai-fetch-forwarder \
  --zip-file fileb://ai-fetch-cloudfront-forwarder.zip
```

Configura l’ambiente:

```
aws lambda update-function-configuration \
  --function-name hitkeep-ai-fetch-forwarder \
  --environment "Variables={HITKEEP_BASE_URL=https://cloud.hitkeep.eu,HITKEEP_SITE_ID=YOUR_SITE_UUID,HITKEEP_API_TOKEN=YOUR_BEARER_TOKEN,HITKEEP_HOSTNAME=hitkeep.com,HITKEEP_TIMEOUT_MS=10000}"
```

## Collegare le notifiche di eventi S3

Configura il bucket dei log CloudFront per richiamare Lambda alla creazione di un oggetto:

- Tipo di evento: `s3:ObjectCreated:*`
- Prefisso: quello dei log, se presente
- Suffisso: `.gz`

Il filtro limita così l’elaborazione ai file di log completi, escludendo gli altri oggetti del bucket.

## Dati inviati a HitKeep

Ogni richiesta di un crawler IA che supera il filtro viene inviata in questa forma:

```
{
  "path": "/guides/analytics/ai-visibility/",
  "hostname": "hitkeep.com",
  "status_code": 200,
  "content_type": "text/html",
  "response_ms": 143,
  "bytes_served": 48231,
  "user_agent": "Mozilla/5.0 (compatible; GPTBot/1.0; +https://openai.com/gptbot)"
}
```

HitKeep ricava automaticamente i seguenti campi dallo user agent e dal tipo di contenuto:

- `assistant_name`
- `assistant_family`
- `resource_type`

L’endpoint usa l’ora di acquisizione come timestamp della richiesta del crawler. Se ti serve l’ora esatta delle richieste storiche, conserva i log originali per l’audit e inoltra i nuovi lotti il prima possibile dopo la creazione.

## Verificare la configurazione

Esegui questi controlli:

1. Verifica che CloudFront scriva file `.gz` in S3.
2. Verifica che i nuovi oggetti attivino Lambda.
3. Cerca `forwardedRecords` in CloudWatch Logs.
4. In HitKeep apri **AI Agents**, passa alla scheda **Crawlers** e attendi le prime righe di richieste.

Se la funzione viene eseguita ma non compaiono righe:

- verifica che il token abbia accesso al sito,
- verifica che `HITKEEP_SITE_ID` sia l’UUID corretto del sito,
- verifica che l’host sia quello del sito monitorato,
- controlla che gli user agent corrispondano effettivamente a crawler IA e non a crawler generici.

Una visita può comparire tra i [visitatori in tempo reale](https://hitkeep.com/it/guides/analytics/comparison/#visitatori-in-tempo-reale) prima della consegna del log CloudFront. Dopo l’arrivo di un lotto, chiedi a un assistente con [accesso in sola lettura al sito](https://hitkeep.com/it/guides/integrations/mcp/) i totali e i codici di stato dei crawler nel periodo di consegna. Verifica separatamente l’inoltro da Lambda.

## Note e limiti

- Il ritardo nella consegna a lotti dei log standard di CloudFront è normale.
- La configurazione è particolarmente adatta ai **siti statici** e alle **origini servite tramite edge**, dove è difficile aggiungere direttamente il monitoraggio al server applicativo.
- Con **ALB**, **nginx** o **Caddy** davanti al server di origine, i log dell’origine sono spesso preferibili perché permettono di inoltrare subito le singole voci.
- Lambda e le notifiche S3 prevedono una consegna almeno una volta. In rari casi un nuovo tentativo può quindi duplicare una riga di richiesta IA.

## Guide correlate

- [Raccolta delle richieste dei crawler IA](https://hitkeep.com/it/guides/tracking/ai-fetch-ingest/)
- [Analizzare i crawler IA lato server](https://hitkeep.com/it/use-cases/ai-visibility-analytics/)
- [Analisi della visibilità nei servizi di IA](https://hitkeep.com/it/guides/analytics/ai-visibility/)
- [Client API](https://hitkeep.com/it/guides/security/api-clients/)
- [Proxy attendibili](https://hitkeep.com/it/guides/installation/trusted-proxies/)

[Indietro Raccogliere le richieste dei crawler IA in HitKeep](https://hitkeep.com/it/guides/tracking/ai-fetch-ingest/)[Avanti Monitorare i crawler IA con CloudFront e HitKeep](https://hitkeep.com/it/guides/tracking/cloudfront-ai-crawler-tracking/)
