lark

next

Code Create Life
telegram
tg_channel
x
github
zhihu
email
follow

Web visitor statistics service based on Cloudflare+D1

Project Address#

Deployment Steps#

Install Dependencies#

npm install -g wrangler
npm install hono

Create D1 Database: web_analytics#

The database name is web_analytics, which should match the one in package.json.

npx wrangler d1 create web_analytics

After running, the console will display:

✅ Successfully created DB 'web_analytics' in region APAC
Created your new D1 database.

[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "web_analytics"
database_id = "xxx"

Modify the database_id in wrangler.toml.

Initialize the Table Structure of D1 Database#

npm run initSql

Bind Custom Domain#

routes = [{ pattern = "analytics.xbxin.com", custom_domain = true }]

Deploy#

npm run deploy

Usage#

<template>
  Page Visits:<span>{{webviso.uv}}</span><br>
  Unique Visitors:<span>{{ webviso.pv }}</span>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const webvisoLoaded = ref(false);
const webviso = ref({
  uv: '',
  pv: '',
});

const loadWebviso = async () => {
  const apiUrl = 'https://analytics.xbxin.com/api/visit'

  const requestData = {
    url: window.location.pathname,
    hostname: window.location.hostname,
    referrer: document.referrer,
    pv: true,
    uv: true,
  }

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })

    if (response.ok) {
      const data = await response.json();
      webviso.value = data.data;
    } else {
      console.error('Error loading analytics data:', response.statusText);
    }
  } catch (err) {
    console.error('Error loading analytics script:', err);
  }
}

onMounted(() => {
  loadWebviso();
});
</script>
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.