Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Implement analytics in Nuxt (#844)

Dhruv Bhanushali235a32799262
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index f5e888acd..310249e8f 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -147,6 +147,8 @@ const openverseLocales = [
...(locales ?? []),
].filter((l) => Boolean(l.iso)) as LocaleObject[]
+const port = process.env.PORT || 8443
+
const config: NuxtConfig = {
// eslint-disable-next-line no-undef
version: pkg.version, // used to purge cache :)
@@ -161,7 +163,7 @@ const config: NuxtConfig = {
srcDir: "src/",
modern: "client",
server: {
- port: process.env.PORT || 8443,
+ port,
https: process.env.LOCAL_SSL
? {
key: fs.readFileSync(path.resolve(__dirname, "localhost+1-key.pem")),
@@ -203,9 +205,11 @@ const config: NuxtConfig = {
modules: [
"portal-vue/nuxt",
"@nuxtjs/i18n",
+ "@nuxtjs/proxy",
"@nuxtjs/redirect-module",
"@nuxtjs/sentry",
"cookie-universal-nuxt",
+ "vue-plausible",
"~/modules/prometheus.ts",
// Sitemap must be last to ensure that even routes created by other modules are added
"@nuxtjs/sitemap",
@@ -328,6 +332,26 @@ const config: NuxtConfig = {
},
},
},
+ proxy: {
+ // The key is appended to the address in the value.
+ "/api/event":
+ process.env.PLAUSIBLE_ORIGIN ?? isProd
+ ? "https://plausible.io"
+ : "http://localhost:50288",
+ },
+ plausible: {
+ trackLocalhost: !isProd,
+ },
+ publicRuntimeConfig: {
+ plausible: {
+ // This is the current domain of the site.
+ domain: process.env.SITE_DOMAIN ?? isProd ? "openverse.org" : "localhost",
+ apiHost:
+ process.env.SITE_DOMAIN ?? isProd
+ ? "https://openverse.org"
+ : `http://localhost:${port}`,
+ },
+ },
}
export default config
diff --git a/frontend/package.json b/frontend/package.json
index 8324f6d3b..f25d656ae 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -64,6 +64,7 @@
"@nuxt/vue-app": "^2.15.8",
"@nuxtjs/composition-api": "^0.33.1",
"@nuxtjs/i18n": "^7.0.3",
+ "@nuxtjs/proxy": "^2.1.0",
"@nuxtjs/redirect-module": "^0.3.1",
"@nuxtjs/sentry": "^7.1.4",
"@nuxtjs/sitemap": "^2.4.0",
@@ -99,7 +100,8 @@
"throttle-debounce": "^5.0.0",
"uuid": "^8.3.2",
"vue": "^2.7.14",
- "vue-i18n": "^8.26.7"
+ "vue-i18n": "^8.26.7",
+ "vue-plausible": "^1.3.2"
},
"devDependencies": {
"@babel/core": "^7.20.12",
diff --git a/frontend/src/components/VHomeGallery/VHomeGallery.vue b/frontend/src/components/VHomeGallery/VHomeGallery.vue
index a51bbb363..8fdc6f831 100644
--- a/frontend/src/components/VHomeGallery/VHomeGallery.vue
+++ b/frontend/src/components/VHomeGallery/VHomeGallery.vue
@@ -29,6 +29,7 @@
:class="idx >= imageCount ? 'hidden' : 'block'"
:style="{ '--delay': `${idx * 0.05}s` }"
:href="image.url"
+ @click="handleClick(image.identifier)"
>
<img
:height="dimens"
@@ -49,6 +50,7 @@ import { computed, defineComponent, PropType, ref } from "vue"
import { useContext, useRouter } from "@nuxtjs/composition-api"
import { useReducedMotion } from "~/composables/use-media-query"
+import { useAnalytics } from "~/composables/use-analytics"
import useResizeObserver from "~/composables/use-resize-observer"
import VLink from "~/components/VLink.vue"
@@ -101,14 +103,18 @@ export default defineComponent({
const el = ref<HTMLElement | null>(null) // template ref
const { dimens: gridDimens } = useResizeObserver(el)
+ const imageSet = computed(() =>
+ props.set === "random"
+ ? imageInfo.sets[Math.floor(Math.random() * imageInfo.sets.length)]
+ : imageInfo.sets.find((item) => (item.key = props.set)) ??
+ imageInfo.sets[0]
+ )
const imageList = computed(() => {
- const imageSet =
- props.set === "random"
- ? imageInfo.sets[Math.floor(Math.random() * imageInfo.sets.length)]
- : imageInfo.sets.find((item) => (item.key = props.set))
- return imageSet?.images.map((image, idx) => ({
+ return imageSet.value.images.map((image, idx) => ({
...image,
- src: require(`~/assets/homepage_images/${imageSet.key}/${idx + 1}.png`),
+ src: require(`~/assets/homepage_images/${imageSet.value.key}/${
+ idx + 1
+ }.png`),
url: router.resolve(
app.localePath({
name: "image-id",
@@ -119,6 +125,14 @@ export default defineComponent({
})
const imageCount = computed(() => columnCount.value * rowCount)
+ const { sendCustomEvent } = useAnalytics()
+ const handleClick = (identifier: string) => {
+ sendCustomEvent("CLICK_HOME_GALLERY_IMAGE", {
+ set: imageSet.value.key,
+ identifier,
+ })
+ }
+
return {
el,
@@ -130,6 +144,8 @@ export default defineComponent({
imageList,
prefersReducedMotion,
+
+ handleClick,
}
},
})
diff --git a/frontend/src/composables/use-analytics.ts b/frontend/src/composables/use-analytics.ts
new file mode 100644
index 000000000..09f9e6733
--- /dev/null
+++ b/frontend/src/composables/use-analytics.ts
@@ -0,0 +1,73 @@
+import { computed } from "vue"
+import { useContext } from "@nuxtjs/composition-api"
+
+import type { Events, EventName } from "~/types/analytics"
+import { useUiStore } from "~/stores/ui"
+
+/**
+ * The `ctx` parameter must be supplied if using this composable outside the
+ * bounds of the composition API.
+ */
+export const useAnalytics = () => {
+ const { $plausible, $ua, i18n } = useContext()
+ const uiStore = useUiStore()
+
+ /**
+ * the Plausible props that work identically on the server-side and the
+ * client-side; This excludes props that need `window`.
+ */
+ const isomorphicProps = computed(() => ({
+ timestamp: new Date().toISOString(),
+ language: i18n.locale,
+ breakpoint: uiStore.breakpoint,
+ ...($ua
+ ? {
+ ua: $ua.source,
+ os: $ua.os,
+ platform: $ua.platform,
+ browser: $ua.browser,
+ version: $ua.version,
+ }
+ : {}),
+ }))
+
+ /**
+ * the Plausible props that work only on the client-side; This only includes
+ * props that need `window`.
+ */
+ const windowProps = computed(() =>
+ window
+ ? {
+ origin: window.location.origin,
+ pathname: window.location.pathname,
+ referrer: window.document.referrer,
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }
+ : {}
+ )
+
+ /**
+ * Send a custom event to Plausible. Mandatory props are automatically merged
+ * with the event-specific props.
+ *
+ * @param name - the name of the event being recorded
+ * @param payload - the additional information to record about the event
+ */
+ const sendCustomEvent = <T extends EventName>(
+ name: T,
+ payload: Events[T]
+ ) => {
+ $plausible.trackEvent(name, {
+ props: {
+ ...isomorphicProps.value,
+ ...windowProps.value,
+ ...payload, // can override mandatory props
+ },
+ })
+ }
+
+ return {
+ sendCustomEvent,
+ }
+}
diff --git a/frontend/src/stores/feature-flag.ts b/frontend/src/stores/feature-flag.ts
index d8afbd645..ae418b390 100644
--- a/frontend/src/stores/feature-flag.ts
+++ b/frontend/src/stores/feature-flag.ts
@@ -1,5 +1,7 @@
import { defineStore } from "pinia"
+import { useStorage } from "@vueuse/core"
+
import featureData from "~~/feat/feature-flags.json"
import { warn } from "~/utils/console"
@@ -156,8 +158,16 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {
*/
toggleFeature(name: FlagName, targetState: FeatureState) {
const flag = this.flags[name]
- if (getFlagStatus(flag) === SWITCHABLE) flag.preferredState = targetState
- else warn(`Cannot set preferred state for non-switchable flag: ${name}`)
+ if (getFlagStatus(flag) === SWITCHABLE) {
+ flag.preferredState = targetState
+
+ // For Plausible to stop tracking `plausible_ignore` must be set.
+ // Ref: https://plausible.io/docs/excluding-localstorage
+ if (name === "analytics") {
+ const storage = useStorage<boolean | null>("plausible_ignore", null)
+ storage.value = targetState === ON ? null : true
+ }
+ } else warn(`Cannot set preferred state for non-switchable flag: ${name}`)
},
},
})
diff --git a/frontend/src/types/analytics.ts b/frontend/src/types/analytics.ts
new file mode 100644
index 000000000..67bbebcb8
--- /dev/null
+++ b/frontend/src/types/analytics.ts
@@ -0,0 +1,31 @@
+/**
+ * compound type of all custom events sent from the site; Index with `EventName`
+ * to get the type of the payload for a specific event.
+ *
+ * Conventions:
+ * - Names should be in SCREAMING_SNAKE_CASE.
+ * - Names should be imperative for events associated with user action.
+ * - Names should be in past tense for events not associated with user action.
+ * - Documentation must be the step to emit the event, followed by a line break.
+ * - Questions that are answered by the event must be listed as bullet points.
+ */
+export type Events = {
+ /**
+ * Click on one of the images in the gallery on the homepage.
+ *
+ * - Do users know homepage images are links?
+ * - Do users find these images interesting?
+ * - Which set is most interesting for the users?
+ */
+ CLICK_HOME_GALLERY_IMAGE: {
+ /** the set to which the image belongs */
+ set: string
+ /** the identifier of the image */
+ identifier: string
+ }
+}
+
+/**
+ * the name of a custom event sent from the site
+ */
+export type EventName = keyof Events
diff --git a/frontend/typings/nuxt__types/index.d.ts b/frontend/typings/nuxt__types/index.d.ts
index 3b6b3ea11..b048c9902 100644
--- a/frontend/typings/nuxt__types/index.d.ts
+++ b/frontend/typings/nuxt__types/index.d.ts
@@ -5,6 +5,7 @@ import { CookieSerializeOptions } from "cookie"
import type { OpenverseCookieState } from "~/types/cookies"
import type { Details as UADetails } from "express-useragent"
+import type { Plausible } from "plausible-tracker"
export interface SetParams<Key extends keyof OpenverseCookieState> {
name: Key
@@ -35,6 +36,7 @@ declare module "@nuxt/types" {
export interface Context {
$ua: UADetails | null
$cookies: NuxtCookies
+ $plausible: ReturnType<typeof Plausible>
}
export interface NuxtAppOptions {
$ua: UADetails | null
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7573049c5..714ab38a1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -37,6 +37,7 @@ importers:
'@nuxtjs/composition-api': ^0.33.1
'@nuxtjs/eslint-module': ^3.1.0
'@nuxtjs/i18n': ^7.0.3
+ '@nuxtjs/proxy': ^2.1.0
'@nuxtjs/redirect-module': ^0.3.1
'@nuxtjs/sentry': ^7.1.4
'@nuxtjs/sitemap': ^2.4.0
@@ -130,6 +131,7 @@ importers:
vue-i18n-extract: ^2.0.7
vue-jest: ^3.0.7
vue-loader: ^15.10.0
+ vue-plausible: ^1.3.2
vue-server-renderer: ^2.7.14
vue-template-compiler: ^2.7.14
vue-tsc: 1.2.0
@@ -140,6 +142,7 @@ importers:
'@nuxt/vue-app': 2.15.8
'@nuxtjs/composition-api': 0.33.1_3nn3s7bk4bbuxifdqrg5p5wmtq
'@nuxtjs/i18n': [email protected]
+ '@nuxtjs/proxy': 2.1.0
'@nuxtjs/redirect-module': 0.3.1
'@nuxtjs/sentry': [email protected]
'@nuxtjs/sitemap': 2.4.0
@@ -176,6 +179,7 @@ importers:
uuid: 8.3.2
vue: 2.7.14
+ vue-plausible: 1.3.2
devDependencies:
'@babel/core': 7.20.12
'@babel/eslint-parser': 7.19.1_gt4pwn2eja2rc4osqr3kyuwnm4
@@ -2791,6 +2795,14 @@ packages:
- vue
dev: false
+ /@nuxtjs/proxy/2.1.0:
+ resolution: {integrity: sha512-/qtoeqXgZ4Mg6LRg/gDUZQrFpOlOdHrol/vQYMnKu3aN3bP90UfOUB3QSDghUUK7OISAJ0xp8Ld78aHyCTcKCQ==}
+ dependencies:
+ http-proxy-middleware: 1.3.1
+ transitivePeerDependencies:
+ - debug
+ dev: false
+
/@nuxtjs/redirect-module/0.3.1:
resolution: {integrity: sha512-yL2unrYfUSqs+4cUtkQvEQMsuTeCOlQd+Y5sTqMZzWBadF8h01tCVDG95zmOTNIiCupb+sQho2Tixwl1f826aw==}
dev: false
@@ -4943,6 +4955,12 @@ packages:
'@types/uglify-js': 3.13.1
dev: true
+ /@types/http-proxy/1.17.10:
+ resolution: {integrity: sha512-Qs5aULi+zV1bwKAg5z1PWnDXWmsn+LxIvUGv6E2+OOMYhclZMO+OXd9pYVf2gLykf2I7IV2u7oTHwChPNsvJ7g==}
+ dependencies:
+ '@types/node': 17.0.32
+ dev: false
+
/@types/is-function/1.0.1:
resolution: {integrity: sha512-A79HEEiwXTFtfY+Bcbo58M2GRYzCr9itHWzbzHVFNEYCcoU/MMGwYYf721gBrnhpj1s6RGVVha/IgNFnR0Iw/Q==}
dev: true
@@ -9392,6 +9410,10 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
+ /eventemitter3/4.0.7:
+ resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
+ dev: false
+
/events/3.3.0:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
@@ -10650,6 +10672,30 @@ packages:
- supports-color
dev: true
+ /http-proxy-middleware/1.3.1:
+ resolution: {integrity: sha512-13eVVDYS4z79w7f1+NPllJtOQFx/FdUW4btIvVRMaRlUY9VGstAbo5MOhLEuUgZFRHn3x50ufn25zkj/boZnEg==}
+ engines: {node: '>=8.0.0'}
+ dependencies:
+ '@types/http-proxy': 1.17.10
+ http-proxy: 1.18.1
+ is-glob: 4.0.3
+ is-plain-obj: 3.0.0
+ micromatch: 4.0.5
+ transitivePeerDependencies:
+ - debug
+ dev: false
+
+ /http-proxy/1.18.1:
+ resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==}
+ engines: {node: '>=8.0.0'}
+ dependencies:
+ eventemitter3: 4.0.7
+ follow-redirects: 1.14.9
+ requires-port: 1.0.0
+ transitivePeerDependencies:
+ - debug
+ dev: false
+
/https-browserify/1.0.0:
resolution: {integrity: sha512-J+FkSdyD+0mA0N+81tMotaRMfSL9SGi+xpD3T6YApKsc3bGSXJlfXri3VyFOeYkfLRQisDk1W+jIFFKBeUBbBg==}
@@ -11160,6 +11206,11 @@ packages:
engines: {node: '>=8'}
dev: true
+ /is-plain-obj/3.0.0:
+ resolution: {integrity: sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==}
+ engines: {node: '>=10'}
+ dev: false
+
/is-plain-object/2.0.4:
resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==}
engines: {node: '>=0.10.0'}
@@ -13894,6 +13945,11 @@ packages:
find-up: 2.1.0
dev: true
+ /plausible-tracker/0.3.8:
+ resolution: {integrity: sha512-lmOWYQ7s9KOUJ1R+YTOR3HrjdbxIS2Z4de0P/Jx2dQPteznJl2eX3tXxKClpvbfyGP59B5bbhW8ftN59HbbFSg==}
+ engines: {node: '>=10'}
+ dev: false
+
/playwright-core/1.29.1:
resolution: {integrity: sha512-20Ai3d+lMkWpI9YZYlxk8gxatfgax5STW8GaMozAHwigLiyiKQrdkt7gaoT9UQR8FIVDg6qVXs9IoZUQrDjIIg==}
engines: {node: '>=14'}
@@ -15659,6 +15715,10 @@ packages:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
dev: true
+ /requires-port/1.0.0:
+ resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==}
+ dev: false
+
/resolve-cwd/3.0.0:
resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==}
engines: {node: '>=8'}
@@ -17910,6 +17970,12 @@ packages:
resolution: {integrity: sha512-ZMjqRpWabMPqPc7gIrG0Nw6vRf1+itwf0Itft7LbMXs2g3Zs/NFmevjZGN1x7K3Q95GmIjWbQZTVerxiBxI+0g==}
dev: false
+ /vue-plausible/1.3.2:
+ resolution: {integrity: sha512-7hdLrDjw0+qjdM9hxowOirQSHPCljWwd8scW0tRFHyXAQSE/yBWrJ3EPuEiZlJUoth9ac0KLbHM+wSSkWHttiA==}
+ dependencies:
+ plausible-tracker: 0.3.8
+ dev: false
+
/vue-router/[email protected]:
resolution: {integrity: sha512-FUlILrW3DGitS2h+Xaw8aRNvGTwtuaxrRkNSHWTizOfLUie7wuYwezeZ50iflRn8YPV5kxmU2LQuu3nM/b3Zsg==}
peerDependencies: