Nextjs chrome extension
Author: m | 2025-04-25
Template for making chrome extensions with NextJS. Contribute to pondorasti/nextjs-chrome-extension development by creating an account on GitHub. Template for making chrome extensions with NextJS. Contribute to pondorasti/nextjs-chrome-extension development by creating an account on GitHub.
Creating a Chrome Extension with NextJS
Question 💬I am trying to use next-auth authentication from my chrome extension. I have spent numerous hours looking into different approaches but hitting in the wall and couldn't find a way to implement. I have implemented the next-auth as part of my NextJS app and trying to use the endpoint '/api/auth/session' to authorize from the Chrome extension. But this is always throwing CORS error. I have tried bypassing CORS by allowing all origins but no luck.I am using Prisma adapter with MongoDB and JWT strategy.secret: process.env.NEXTAUTH_SECRET, session: { strategy: 'jwt', maxAge: THIRTY_DAYS, updateAge: THIRTY_MINUTES, }, jwt: { secret: process.env.JWT_SECRET, },I have noticed that ShareGPT extension ( somehow got this working, but I couldn't figure it out. I wish there was some guide as part of next-auth docs. Please help me figure this out.How to reproduce ☕️Call the session API from chrome extension which is running in the tab of different origin. { const json = await res.json(); console.log(json)})">fetch(" {mode: "cors",credentials: "include"}).then(async (res) => { const json = await res.json(); console.log(json)})Contributing 🙌🏽Yes, I am willing to help answer this question in a PR Featured Cruip - Beautiful Tailwind CSS Templates Beautifully designed landing pages, websites, and dashboards built on top of Tailwind CSS and fully coded in HTML, React, Next.js, and Vue. A great starting point for your next project, saving you weeks of development time. Egg 24time A Twitter-like news and social server for Egg. 微信小程序社区全栈解决方案 Modular Admin Html ModularAdmin - Free Dashboard Theme Built On Bootstrap 4 | HTML Version Chrome Extension Webpack Boilerplate A basic foundation boilerplate for rich Chrome Extensions using Webpack to help you write modular and modern Javascript code, load CSS easily and automatic reload the browser on code changes. Gatsby Starter Portfolio Bella A bright single-page portfolio starter for Gatsby powered by Prismic.io. The target audience are designers and photographers. Koa Web Kit 🚀A Modern, Production-Ready, and Full-Stack Node Web Framework with React Angular Library Seed 🌾 Seed project for Angular libraries that are AOT/JIT compatible and that use external SCSS-styles and HTML-templates Php Microsite Boilerplate An extremely simple and lightweight PHP framework/boilerplate to spin-up microsites at high speed. Optimized for Performance, Security, SEO, TailwindCSS, and Directus CMS. Nextauri A Next.js + Tauri template, with minimal best practice setup and weekly updates! Practica Node.js solution starter boilerplate that is production-ready, packed with ✅ best practices and built with simplicity in mind Clean React App Set up a modern web app with clean architecture by running one command. Hugoplate Hugoplate is a free starter template built with Hugo and TailwindCSS that will save you hours of work. Relivator Nextjs Starter Next.js 14 Store, Landing, Admin, Dashboard ▲ i18n Stripe Shadcn Tailwind Drizzle Zod Trpc TypeScript Clerk NexAuth, Lucide CSS Radix UI, Responsive React 19 Server Components, MySQL Postgres Neon TS ORM, Intl App Router, Mdx Docs User Actions Kit, SaaS Commerce Shop Pricing Payments, Dark Mode, Modern Full Stack Free ▲ more stars → more features Reactql Universal React+GraphQL starter kit: React 16, Apollo 2, MobX, Emotion, Webpack 4, GraphQL Code Generator, React Router 4, PostCSS, SSR Koa Mobx React Starter A straightforward starter for Node javascript web projects. Using Koa, MobX and ReactJS (with universal /NextJS Chrome Extension: A Developer's
The Google tag API reference.Google tag API reference - consentWeb VitalsTo send Next.js web vitals to Google Analytics you can use a custom event on the reportWebVitals function inside a custom App component:// pages/_app.jsimport { GoogleAnalytics, event } from "nextjs-google-analytics";export function reportWebVitals({ id, name, label, value }) { event(name, { category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers label: id, // id unique to current page load nonInteraction: true, // avoids affecting bounce rate. });}const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics /> Component {...pageProps} /> /> );};export default App;If you are using TypeScript, you can import NextWebVitalsMetric from next/app:import type { NextWebVitalsMetric } from "next/app";export function reportWebVitals(metric: NextWebVitalsMetric) { // ...}Using the gaMeasurementId paramAll exported components, hooks, and functions, accept an optional gaMeasurementId param that can be used in case no environment variable is provided:// pages/_app.jsimport { GoogleAnalytics, event } from "nextjs-google-analytics";import { gaMeasurementId } from "./lib/gtag";export function reportWebVitals({ id, name, label, value,}: NextWebVitalsMetric) { event( name, { category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers label: id, // id unique to current page load nonInteraction: true, // avoids affecting bounce rate. }, gaMeasurementId );}const App = ({ Component, pageProps }) => { usePageViews({ gaMeasurementId }); return ( > GoogleAnalytics gaMeasurementId={gaMeasurementId} /> Component {...pageProps} /> /> );};export default App;Debugging you Google AnalyticsInstall the Google Analytics Debugger.Turn it on by clicking its icon to the right of the address bar.Open the Chrome Javascript console to see the messages.On Windows and Linux, press Control-Shift-J.On Mac, press Command-Option-J.Refresh the page you are on.TypeScriptThe module is written in TypeScript and type definitions are included.ContributingContributions, issues and feature requests are welcome!Show your supportGive a ⭐️ if you like this project!LICENSEMIT. Template for making chrome extensions with NextJS. Contribute to pondorasti/nextjs-chrome-extension development by creating an account on GitHub.NextJS Chrome Extension: A Developer's Guide - NextJs Starter
Open it in your code editor to customize and create your own widget.Notes for developmentYour example project has the foundational code for building Beeper Widgets. We recommend building your widget directly on the codebase.The codebase is in NextJS, with inbuilt support for Tailwind CSS and CSS Modules. You can also use Sass.If you haven't used NextJS, just know that you can write normal React code. NextJS is a layer on top that improves the developer experience through various features.You must use React, but you don't need to use NextJS. If there's another framework you prefer, use the code inside of the example project as a reference.app/page.tsx is rendered when you open your widget.In order to access data inside of a chat, you'll need to add code inside your widget to request permissions. In page.tsx, there's an example of that; just modify the capabilities array to suit your needs.We recommend Vercel for deploying your widget so others can use it. Push your code to a GitHub repo, create an app in Vercel, and add the widget in Beeper Desktop using the Vercel URL.API DocumentationBackground Info on MatrixThe Matrix chat protocol consists of events. Events represent data inside a chat, such as a message, reaction, or list of participants. Each chat in Matrix is called a room. Events are split into two types: room events and state events.In Beeper, the list of chat messages in a room is called a timeline. Room events represent events inside of that timeline that happen one after another. For example, messages being sent, messages being deleted, or reactions being applied. State events represent the current state of a room, for example, the title and the list of participants. State events have a single current value.Room account data is JSON data stored inside of each Beeper account, [!NOTE]You might not need this package. Please check Third Party Libraries first.Nextjs Google AnalyticsGoogle Analytics for Next.jsThis package optimizes script loading using Next.js Script tag, which means that it will only work on apps using Next.js >= 11.0.0.Installationnpm install --save nextjs-google-analyticsTL;DRAdd the GoogleAnalytics component with the trackPageViews prop set to true to your custom App file:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews /> Component {...pageProps} /> /> );};export default App;You can pass your Google Analytics measurement id by setting it on the NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable or using the gaMeasurementId prop on the GoogleAnalytics component. The environment variable will override the prop if both are set.UsageYour Google Analytics measurement id is read from NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable, so make sure it is set in your production environment:VercelNetlifyIf the variable is not set or is empty, nothing will be loaded, making it safe to work in development.To load it and test it on development, add:NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"to your .env.local file.As an alternative, you can use the gaMeasurementId param to pass your Google Analytics measurement id.The NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable will take precedence over the gaMeasurementId param, so if both are set with different values, the environment variable will override the param.ScriptsUse the GoogleAnalytics component to load the gtag scripts. You can add it to a custom App component and this will take care of including the necessary scripts for every page (or you could add it on a per page basis if you need more control):// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics /> Component {...pageProps} /> /> );};export default App;By default, scripts are loaded using the afterInteractive strategy, which means they are injected on the client-side and will run after hydration.If you need more control, the component exposes the strategy prop to control how the scripts are loaded:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics strategy="lazyOnload" /> Component {...pageProps} /> /> );};export default App;also, you can use alternative to defaultNextJS Chrome Extension: A Developer's Guide
Path for googletagmanager script byGoogleAnalytics gtagUrl="/gtag.js" />Page viewsTo track page views set the trackPageViews prop of the GoogleAnalytics component to true.// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews /> Component {...pageProps} /> /> );};export default App;By default it will be trigger on hash changes if trackPageViews is enabled, but you can ignore hash changes by providing an object to the trackPageViews prop:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews={{ ignoreHashChange: true }} /> Component {...pageProps} /> /> );};export default App;As an alternative, you can directly call the usePageViews hook inside a custom App component, do not set trackPageViews prop on the GoogleAnalytics component or set it to false (default):// pages/_app.jsimport { GoogleAnalytics, usePageViews } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { usePageViews(); // IgnoreHashChange defaults to false // usePageViews({ ignoreHashChange: true }); return ( > GoogleAnalytics /> {/* or */} Component {...pageProps} /> /> );};export default App;The module also exports a pageView function that you can use if you need more control.Custom eventYou can use the event function to track a custom event:import { useState } from "react";import Page from "../components/Page";import { event } from "nextjs-google-analytics";export function Contact() { const [message, setMessage] = useState(""); const handleInput = (e) => { setMessage(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); event("submit_form", { category: "Contact", label: message, }); setState(""); }; return ( Page> h1>This is the Contact page/h1> form onSubmit={handleSubmit}> label> span>Message:/span> textarea onChange={handleInput} value={message} /> /label> button type="submit">submit/button> /form> /Page> );}For the possible parameters that can be specified in the event, please refer to the event command in the Google tag API reference.Google tag API reference - eventConsentYou can use the consent function to update your users' cookie preferences (GDPR). const consentValue: 'denied' | 'granted' = getUserCookiePreferenceFromLocalStorage(); // 'denied' or 'granted' consent({ arg: 'update', params: { ad_storage: consentValue, analytics_storage: consentValue, ad_user_data: conentValue, ad_personalization: conentValue }, });For the possible values that can be specified in arg and params, please refer to the consent command inmjleitch/nextjs-chrome-extension - GitHub
0.2.8 • Public • Published a year ago ReadmeCode Beta0 Dependencies1 Dependents39 VersionsQuill ImageHandler Module for NextJSA modifed alternative of Quill Image Upload Plugin to support NextJSThe original plugin uses css import in node_modules, which is not supported by the latest NextJS.CreditsThe full credit for the editor plugin goes to Quill Image Upload Plugin and this is a modificaion to support the NextJS.Therefore, keep upto date on its issue tracker whether the issue is fixed.InstallInstall with npm:npm install @writergate/quill-image-uploader-nextjs --saveWebpack/ES6import Quill from "quill";import ImageUploader from "quill.imageUploader.js";import '@writergate/quill-image-uploader-nextjs/dist/quill.imageUploader.min.css';Quill.register("modules/imageUploader", ImageUploader);const quill = new Quill(editor, { // ... modules: { // ... imageUploader: { upload: (file) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve( " ); }, 3500); }); }, }, },});Note: It's also important that you create a quill component and dynamically import the component with SSR: false for NextJS.e.g: No SSR Editor component includes all the above code.const QuillNoSSR = dynamic( () => import('src/components/no-ssr-editor').then(md => md.default), { ssr: false });. Template for making chrome extensions with NextJS. Contribute to pondorasti/nextjs-chrome-extension development by creating an account on GitHub.NextJS not viable for Chrome extension development?
Installing Chrome extensions is easy, just click the “Add to Chrome” button on the extension page, and Chrome will both download and install the extension. However, what if you want to manually install the Chrome extensions? Maybe you want to download the extension but install it on a different PC. Or you are having trouble installing Chrome extensions directly.Whatever your reasoning is, you can manually download Chrome extensions and install them whenever you like. In this post, I’ll show you how to download a Chrome extension CRX file and then install it in Chrome manually.Download the Chrome extension CRX fileCRX file is basically the name of the Chrome extension package (zipped file) that chrome unzips and installs as a Chrome extension when you click the “Add to Chrome” button. You can download the CRX file of any extension separately with the help of another Chrome extension, here’s how.You can install a CRX downloader Chrome extension that will help you download the CRX file of any Chrome extension. There are many extensions for this purpose, but I like CRX Extractor/Downloader for its intuitive usage so I’ll recommend that.Just install this Chrome extension and move to the Chrome web store page of the extension of which you need the CRX file. Now click on the extension button and then click on “Download as CRX”. Depending on the extension size it may take a few seconds for the download to begin.That’s it, the extension CRX file will be downloaded to your PC and you can even move it to a different PC to install.Manually install a Chrome extensionNow that you have downloaded the CRX file, let’s see how you can install it in Chrome. Click on the Chrome main menu and select “Extensions” from the “More tools” option.Here click on the “Developer mode” toggle at the top-right corner to enable it. You cannot install Chrome extensions manually without enabling this option.Now drag and drop the CRX file of the extension in the Chrome extensions page and you’ll be asked to add the extension like you are usually asked. To drag and drop, you can either decrease the size of the Chrome window or drag the CRX file on the Chrome taskbar button to maximize Chrome and drop it.This will install the extension and you don’t even need an internet connection to complete the installation. Ending thoughtsBefore I end, I should mention that you can use the same process to install Chrome extensions in other Chromium-based browsers as well, such as Opera. Also, make sure you drag and drop the CRX file in Chrome and don’t just open it using Chrome as the default app. Otherwise, Chrome will not allow the installation.Comments
Question 💬I am trying to use next-auth authentication from my chrome extension. I have spent numerous hours looking into different approaches but hitting in the wall and couldn't find a way to implement. I have implemented the next-auth as part of my NextJS app and trying to use the endpoint '/api/auth/session' to authorize from the Chrome extension. But this is always throwing CORS error. I have tried bypassing CORS by allowing all origins but no luck.I am using Prisma adapter with MongoDB and JWT strategy.secret: process.env.NEXTAUTH_SECRET, session: { strategy: 'jwt', maxAge: THIRTY_DAYS, updateAge: THIRTY_MINUTES, }, jwt: { secret: process.env.JWT_SECRET, },I have noticed that ShareGPT extension ( somehow got this working, but I couldn't figure it out. I wish there was some guide as part of next-auth docs. Please help me figure this out.How to reproduce ☕️Call the session API from chrome extension which is running in the tab of different origin. { const json = await res.json(); console.log(json)})">fetch(" {mode: "cors",credentials: "include"}).then(async (res) => { const json = await res.json(); console.log(json)})Contributing 🙌🏽Yes, I am willing to help answer this question in a PR
2025-04-20Featured Cruip - Beautiful Tailwind CSS Templates Beautifully designed landing pages, websites, and dashboards built on top of Tailwind CSS and fully coded in HTML, React, Next.js, and Vue. A great starting point for your next project, saving you weeks of development time. Egg 24time A Twitter-like news and social server for Egg. 微信小程序社区全栈解决方案 Modular Admin Html ModularAdmin - Free Dashboard Theme Built On Bootstrap 4 | HTML Version Chrome Extension Webpack Boilerplate A basic foundation boilerplate for rich Chrome Extensions using Webpack to help you write modular and modern Javascript code, load CSS easily and automatic reload the browser on code changes. Gatsby Starter Portfolio Bella A bright single-page portfolio starter for Gatsby powered by Prismic.io. The target audience are designers and photographers. Koa Web Kit 🚀A Modern, Production-Ready, and Full-Stack Node Web Framework with React Angular Library Seed 🌾 Seed project for Angular libraries that are AOT/JIT compatible and that use external SCSS-styles and HTML-templates Php Microsite Boilerplate An extremely simple and lightweight PHP framework/boilerplate to spin-up microsites at high speed. Optimized for Performance, Security, SEO, TailwindCSS, and Directus CMS. Nextauri A Next.js + Tauri template, with minimal best practice setup and weekly updates! Practica Node.js solution starter boilerplate that is production-ready, packed with ✅ best practices and built with simplicity in mind Clean React App Set up a modern web app with clean architecture by running one command. Hugoplate Hugoplate is a free starter template built with Hugo and TailwindCSS that will save you hours of work. Relivator Nextjs Starter Next.js 14 Store, Landing, Admin, Dashboard ▲ i18n Stripe Shadcn Tailwind Drizzle Zod Trpc TypeScript Clerk NexAuth, Lucide CSS Radix UI, Responsive React 19 Server Components, MySQL Postgres Neon TS ORM, Intl App Router, Mdx Docs User Actions Kit, SaaS Commerce Shop Pricing Payments, Dark Mode, Modern Full Stack Free ▲ more stars → more features Reactql Universal React+GraphQL starter kit: React 16, Apollo 2, MobX, Emotion, Webpack 4, GraphQL Code Generator, React Router 4, PostCSS, SSR Koa Mobx React Starter A straightforward starter for Node javascript web projects. Using Koa, MobX and ReactJS (with universal /
2025-04-19The Google tag API reference.Google tag API reference - consentWeb VitalsTo send Next.js web vitals to Google Analytics you can use a custom event on the reportWebVitals function inside a custom App component:// pages/_app.jsimport { GoogleAnalytics, event } from "nextjs-google-analytics";export function reportWebVitals({ id, name, label, value }) { event(name, { category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers label: id, // id unique to current page load nonInteraction: true, // avoids affecting bounce rate. });}const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics /> Component {...pageProps} /> /> );};export default App;If you are using TypeScript, you can import NextWebVitalsMetric from next/app:import type { NextWebVitalsMetric } from "next/app";export function reportWebVitals(metric: NextWebVitalsMetric) { // ...}Using the gaMeasurementId paramAll exported components, hooks, and functions, accept an optional gaMeasurementId param that can be used in case no environment variable is provided:// pages/_app.jsimport { GoogleAnalytics, event } from "nextjs-google-analytics";import { gaMeasurementId } from "./lib/gtag";export function reportWebVitals({ id, name, label, value,}: NextWebVitalsMetric) { event( name, { category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric", value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers label: id, // id unique to current page load nonInteraction: true, // avoids affecting bounce rate. }, gaMeasurementId );}const App = ({ Component, pageProps }) => { usePageViews({ gaMeasurementId }); return ( > GoogleAnalytics gaMeasurementId={gaMeasurementId} /> Component {...pageProps} /> /> );};export default App;Debugging you Google AnalyticsInstall the Google Analytics Debugger.Turn it on by clicking its icon to the right of the address bar.Open the Chrome Javascript console to see the messages.On Windows and Linux, press Control-Shift-J.On Mac, press Command-Option-J.Refresh the page you are on.TypeScriptThe module is written in TypeScript and type definitions are included.ContributingContributions, issues and feature requests are welcome!Show your supportGive a ⭐️ if you like this project!LICENSEMIT
2025-04-06Open it in your code editor to customize and create your own widget.Notes for developmentYour example project has the foundational code for building Beeper Widgets. We recommend building your widget directly on the codebase.The codebase is in NextJS, with inbuilt support for Tailwind CSS and CSS Modules. You can also use Sass.If you haven't used NextJS, just know that you can write normal React code. NextJS is a layer on top that improves the developer experience through various features.You must use React, but you don't need to use NextJS. If there's another framework you prefer, use the code inside of the example project as a reference.app/page.tsx is rendered when you open your widget.In order to access data inside of a chat, you'll need to add code inside your widget to request permissions. In page.tsx, there's an example of that; just modify the capabilities array to suit your needs.We recommend Vercel for deploying your widget so others can use it. Push your code to a GitHub repo, create an app in Vercel, and add the widget in Beeper Desktop using the Vercel URL.API DocumentationBackground Info on MatrixThe Matrix chat protocol consists of events. Events represent data inside a chat, such as a message, reaction, or list of participants. Each chat in Matrix is called a room. Events are split into two types: room events and state events.In Beeper, the list of chat messages in a room is called a timeline. Room events represent events inside of that timeline that happen one after another. For example, messages being sent, messages being deleted, or reactions being applied. State events represent the current state of a room, for example, the title and the list of participants. State events have a single current value.Room account data is JSON data stored inside of each Beeper account,
2025-04-22[!NOTE]You might not need this package. Please check Third Party Libraries first.Nextjs Google AnalyticsGoogle Analytics for Next.jsThis package optimizes script loading using Next.js Script tag, which means that it will only work on apps using Next.js >= 11.0.0.Installationnpm install --save nextjs-google-analyticsTL;DRAdd the GoogleAnalytics component with the trackPageViews prop set to true to your custom App file:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews /> Component {...pageProps} /> /> );};export default App;You can pass your Google Analytics measurement id by setting it on the NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable or using the gaMeasurementId prop on the GoogleAnalytics component. The environment variable will override the prop if both are set.UsageYour Google Analytics measurement id is read from NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable, so make sure it is set in your production environment:VercelNetlifyIf the variable is not set or is empty, nothing will be loaded, making it safe to work in development.To load it and test it on development, add:NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"to your .env.local file.As an alternative, you can use the gaMeasurementId param to pass your Google Analytics measurement id.The NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable will take precedence over the gaMeasurementId param, so if both are set with different values, the environment variable will override the param.ScriptsUse the GoogleAnalytics component to load the gtag scripts. You can add it to a custom App component and this will take care of including the necessary scripts for every page (or you could add it on a per page basis if you need more control):// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics /> Component {...pageProps} /> /> );};export default App;By default, scripts are loaded using the afterInteractive strategy, which means they are injected on the client-side and will run after hydration.If you need more control, the component exposes the strategy prop to control how the scripts are loaded:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics strategy="lazyOnload" /> Component {...pageProps} /> /> );};export default App;also, you can use alternative to default
2025-03-29Path for googletagmanager script byGoogleAnalytics gtagUrl="/gtag.js" />Page viewsTo track page views set the trackPageViews prop of the GoogleAnalytics component to true.// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews /> Component {...pageProps} /> /> );};export default App;By default it will be trigger on hash changes if trackPageViews is enabled, but you can ignore hash changes by providing an object to the trackPageViews prop:// pages/_app.jsimport { GoogleAnalytics } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { return ( > GoogleAnalytics trackPageViews={{ ignoreHashChange: true }} /> Component {...pageProps} /> /> );};export default App;As an alternative, you can directly call the usePageViews hook inside a custom App component, do not set trackPageViews prop on the GoogleAnalytics component or set it to false (default):// pages/_app.jsimport { GoogleAnalytics, usePageViews } from "nextjs-google-analytics";const App = ({ Component, pageProps }) => { usePageViews(); // IgnoreHashChange defaults to false // usePageViews({ ignoreHashChange: true }); return ( > GoogleAnalytics /> {/* or */} Component {...pageProps} /> /> );};export default App;The module also exports a pageView function that you can use if you need more control.Custom eventYou can use the event function to track a custom event:import { useState } from "react";import Page from "../components/Page";import { event } from "nextjs-google-analytics";export function Contact() { const [message, setMessage] = useState(""); const handleInput = (e) => { setMessage(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); event("submit_form", { category: "Contact", label: message, }); setState(""); }; return ( Page> h1>This is the Contact page/h1> form onSubmit={handleSubmit}> label> span>Message:/span> textarea onChange={handleInput} value={message} /> /label> button type="submit">submit/button> /form> /Page> );}For the possible parameters that can be specified in the event, please refer to the event command in the Google tag API reference.Google tag API reference - eventConsentYou can use the consent function to update your users' cookie preferences (GDPR). const consentValue: 'denied' | 'granted' = getUserCookiePreferenceFromLocalStorage(); // 'denied' or 'granted' consent({ arg: 'update', params: { ad_storage: consentValue, analytics_storage: consentValue, ad_user_data: conentValue, ad_personalization: conentValue }, });For the possible values that can be specified in arg and params, please refer to the consent command in
2025-04-04