• Stars
    star
    506
  • Rank 85,050 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple integration for https://nextjs.org and https://plausible.io analytics

Next-Plausible Β· npm version

Simple integration for https://nextjs.org and https://plausible.io analytics.

See it in action at https://next-plausible.vercel.app, and this commit for a real world example.

Important: If you're using a version of next lower than 11.1.0 please use next-plausible@2 to avoid type checking errors (see #25).

Usage

Include the Analytics Script

To enable Plausible analytics in your Next.js app you'll need to expose the Plausible context, <PlausibleProvider />, at the top level of your application inside _app.js:

// pages/_app.js
import PlausibleProvider from 'next-plausible'

export default function MyApp({ Component, pageProps }) {
  return (
    <PlausibleProvider domain="example.com">
      <Component {...pageProps} />
    </PlausibleProvider>
  )
}

If you want to enable Plausible analytics only on a single page you can wrap the page in a PlausibleProvider component:

// pages/home.js
import PlausibleProvider from 'next-plausible'

export default Home() {
  return (
    <PlausibleProvider domain="example.com">
      <h1>My Site</h1>
      {/* ... */}
    </PlausibleProvider>
  )
}

If are using the app directory include PlausibleProvider inside the root layout:

// app/layout.js
import PlausibleProvider from 'next-plausible'

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <PlausibleProvider domain="example.com" />
      </head>
      <body>{children}</body>
    </html>
  )
}

PlausibleProvider Props

Name Description
domain The domain of the site you want to monitor.
customDomain Set this if you use a custom domain to serve the analytics script. Defaults to https://plausible.io. See https://plausible.io/docs/custom-domain for more details.
trackOutboundLinks Set this to true if you want to enable outbound link click tracking.
trackFileDownloads Set this to true if you want to enable file download tracking.
taggedEvents Set this to true if you want to enable custom event tracking in HTML elements.
trackLocalhost Set this to true if you want to enable localhost tracking as described here.
manualPageviews Set this to true if you want to disable automatic pageview events as described here.
exclude Set this if you want to exclude a set of pages from being tracked. See https://plausible.io/docs/excluding-pages for more details.
selfHosted Set this to true if you are self hosting your Plausible instance. Otherwise you will get a 404 when requesting the script.
enabled Use this to explicitly decide whether or not to render script. If not passed the script will be rendered in production environments.
integrity Optionally define the subresource integrity attribute for extra security.
scriptProps Optionally override any of the props passed to the script element. See example.

Proxy the Analytics Script

To avoid being blocked by adblockers plausible recommends proxying the script. To do this you need to wrap your next.config.js with the withPlausibleProxy function:

const { withPlausibleProxy } = require('next-plausible')

module.exports = withPlausibleProxy()({
  // ...your next js config, if any
  // Important! it is mandatory to pass a config object, even if empty
})

This will set up the necessary rewrites as described here and configure PlausibleProvider to use the local URLs so you can keep using it like this:

  <PlausibleProvider domain="example.com">
    ...
  </PlausibleProvider>
}

Optionally you can overwrite the proxied script subdirectory and name, as well as the custom domain for the original script:

const { withPlausibleProxy } = require('next-plausible')

module.exports = withPlausibleProxy({
  subdirectory: 'yoursubdirectory',
  scriptName: 'scriptName',
  customDomain: 'http://example.com',
})({
  // ...your next js config, if any
  // Important! it is mandatory to pass a config object, even if empty
})

This will load the script from /yoursubdirectory/js/scriptName.js and fetch it from http://example.com/js/script.js.

Notes:

  • Proxying will only work if you serve your site using next start. Statically generated sites won't be able to rewrite the requests.

  • If you are self hosting plausible, you need to set customDomain to your instance otherwise no data will be sent.

  • Bear in mind that tracking requests will be made to the same domain, so cookies will be forwarded. See #67. If this is an issue for you, from [email protected] you can use middleware to strip the cookies like this:

    import { NextResponse } from 'next/server'
    
    export function middleware(request) {
      const requestHeaders = new Headers(request.headers)
      requestHeaders.set('cookie', '')
      return NextResponse.next({
        request: {
          headers: requestHeaders,
        },
      })
    }
    
    export const config = {
      matcher: '/proxy/api/event',
    }

Send Custom Events

Plausible supports custom events as described at https://plausible.io/docs/custom-event-goals. This package provides the usePlausible hook to safely access the plausible function like this:

import { usePlausible } from 'next-plausible'

export default function PlausibleButton() {
  const plausible = usePlausible()

  return (
    <>
      <button onClick={() => plausible('customEventName')}>Send</button>

      <button
        id="foo"
        onClick={() =>
          plausible('customEventName', {
            props: {
              buttonId: 'foo',
            },
          })
        }
      >
        Send with props
      </button>
    </>
  )
}

If you use Typescript you can type check your custom events like this:

import { usePlausible } from 'next-plausible'

type MyEvents = {
  event1: { prop1: string }
  event2: { prop2: string }
  event3: never
}

const plausible = usePlausible<MyEvents>()

Only those events with the right props will be allowed to be sent using the plausible function.

Developing

  • npm run build will generate the production scripts under the dist folder.

More Repositories

1

react-guitar

A beautiful and accessible guitar component for React. βš›οΈ 🎸
TypeScript
618
star
2

creepyface

The JavaScript library that makes your face look at the pointer. πŸ€ͺπŸ–±οΈπŸ‘†
TypeScript
486
star
3

fetchbook

Run and test your HTTP requests. Git friendly, 100% local.
TypeScript
147
star
4

rollup-plugin-browsersync

Serve your bundle via Browser Sync
JavaScript
19
star
5

liferay-pokemon-item-selector

Code for Liferay's /dev/24 talk
Java
12
star
6

storybook-tailwind2

Sample setup for Storybook and Tailwind@2
JavaScript
7
star
7

liferay-super-deploy

Deploy all changed modules at once (hopefully).
Shell
6
star
8

liferequest

From http://localhost:8080 to HTML
4
star
9

liferay-devcon-headless-2023

Liferay Devcon 2023 Headless Talk
FreeMarker
4
star
10

uptimerobot-node-client

NodeJS client for the uptimerobot API
JavaScript
3
star
11

elm-music-player

Music player written in Elm at a Haskell Madrid Meetup
Elm
2
star
12

emoji-chat

Emoji chat for WeDeploy Hackathon
JavaScript
2
star
13

npm-card

My NPM card πŸ’³
JavaScript
1
star
14

react-creepyface

React component for https://github.com/4lejandrito/creepyface.
1
star
15

me

My personal site
TypeScript
1
star
16

try_git

1
star
17

liferay-rest-client-for-templates

Example of a template migration from serviceLocator to restClient
FreeMarker
1
star
18

creepyface-firefly

A point provider for Creepyface
1
star
19

c2t-chrome

Car to Trello Chrome Extension
JavaScript
1
star
20

wercker-box-play

Wercker box for play 2.2.x apps
1
star
21

cliferay

Daily scripts to work with Liferay
Shell
1
star
22

liferay-headless-playwright

Playwright first steps for the Headless team
TypeScript
1
star