How to use Cloudflare Web Analytics

21 January 2022

Cloudflare Web Analytics introduction

Why Cloudflare Web Analytics?

Cloudflare Web Analytics is lighter than Google Analytics. It's privacy-focused, easy-to-use, and free. It also tracks Core Web Vitals such as Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS).

How to use

  1. Create a Cloudflare account.
  2. Verify your email address.
  3. Go to Cloudflare Dashboard.
  4. From the left navigation bar, select Web Analytics.
  5. Enter your hostname. For example, example.com.
  6. Click Done.
  7. Copy the JavaScript Snippet.
  8. On every page of your website, paste the JavaScript Snippet before the closing </body> tag.

For Next.js projects, you can create _document.jsx or _document.tsx file in the pages folder. Paste in the following code.

pages/_document.jsx
import Document, { Head, Html, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang='en'>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Paste the Cloudflare's JavaScript Snippet before the closing </body> tag.

pages/_document.jsx
import Document, { Head, Html, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang='en'>
        <Head />
        <body>
          <Main />
          <NextScript />
          <script
            defer
            src='https://static.cloudflareinsights.com/beacon.min.js'
            data-cf-beacon='{"token": "your-cloudflare-token"}'
          ></script>
        </body>
      </Html>
    )
  }
}
Read other blogs