Page Views Module Personal Project
Nuxt module that provides page views tracking using the Google Analytics Data API.
Built with Nuxt/Vue 3, TypeScript, and H3.
Features
- Quick setup if you're already running Google Analytics
- SSR Support
- Cached responses from the Google Analytics Data API
- Expose usePageViews() composable
Installation
Add nuxt-pageviews dependency to your project
# Using pnpm
pnpm add -D nuxt-pageviews
# Using yarn
yarn add --dev nuxt-pageviews
# Using npm
npm install --save-dev nuxt-pageviews
Add nuxt-pageviews to the modules section of nuxt.config.ts
export default defineNuxtConfig({
modules: [
'nuxt-pageviews'
]
})
Configuration
Google Analytics Setup
You will need to configure a new service account, and add its email address to the GA property you would like to access.
Nuxt Configuration
To use this plugin, you need to provide a Google service account credentials file, a Google Analytics property ID, and an endpoint for the API that will serve the data.
In your nuxt.config.ts file, configure the options for the module:
export default defineNuxtConfig({
pageViews: {
credentialsFile: "./src/creds.json",
propertyId: "12345678",
endpoint: "/api/views"
}
})
Using
You can use the usePageViews composable to access the page views count for a specific page:
<script lang="ts" setup>
const views = await usePageViews()
</script>
<template>
<div>
<div>Blog views: {{ views }}</div>
</div>
</template>
You can also pull the counts for other paths:
<template>
<div>
<div>Page views: {{ views }}</div>
<div>Blog views: {{ blogViews }}</div>
<div>Project List views: {{ projectViews }}</div>
</div>
</template>
<script setup>
const views = await usePageViews()
const blogViews = await usePageViews("/blog")
const projectViews = await usePageViews("/projects")
</script>
License
This module is licensed under the MIT License. See the LICENSE file for more information.