How to use Cloudflare Web Analytics
21 January 2022
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
- Create a Cloudflare account.
- Verify your email address.
- Go to Cloudflare Dashboard.
- From the left navigation bar, select Web Analytics.
- Enter your hostname. For example,
example.com
. - Click Done.
- Copy the JavaScript Snippet.
- 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