Analytics
We use PostHog
for analytics, feel free to use any other analytics
tool.
Here is how to set it up.
Setup PostHog
- Create an account on
PostHog
by visiting this link - Select the free tier it is usually more than enough
- Chose the cloud region closer to you
- On
PostHog
dashboard click settingbottom left corner
- In the
Web snippet
section
<script>
//...
// this is your api key
posthog.init("phc_xxxxxxxxxxxxxxxxxxxxxxxxxxx", {
// this is your host xx is either us or eu depending on which one you chose
api_host: "https://xx.i.posthog.com",
//...
});
</script>
- Add these information to
.env.local
if you haven't already
.env.local
NEXT_PUBLIC_POSTHOG_KEY= # Your posthog api key
NEXT_PUBLIC_POSTHOG_HOST= # Posthog host you are using e.g. https://us.i.posthog.com or https://eu.i.posthog.com
Note that PostHog
is initialized under src/app/(site)/_layout/client-providers.tsx
so it only captures the
public pages.
Prevent ad-blockers from blocking your analytics
- Navigate to
next.config.ts
and update it with this code. (make sure to update region prefixeu
/us
)
next.config.ts
const nextConfig: NextConfig = {
// ...
// PostHog rewrites to prevent ad-blockers from stopping tracking
async rewrites() {
return [
{
source: "/ingest/static/:path*",
destination: "https://xx-assets.i.posthog.com/static/:path*",
},
{
source: "/ingest/:path*",
destination: "https://xx.i.posthog.com/:path*",
},
{
source: "/ingest/decide",
destination: "https://xx.i.posthog.com/decide",
},
];
},
// This is required to support PostHog trailing slash API requests
skipTrailingSlashRedirect: true,
};
Note you can replace /ingest
with any word you want
- Update
PostHog
initialization code undersrc/app/(site)/_layout/client-providers.tsx
src/app/(site)/_layout/client-providers.tsx
// init posthog
const NEXT_PUBLIC_POSTHOG_KEY = process.env.NEXT_PUBLIC_POSTHOG_KEY;
if (typeof window !== "undefined" && NEXT_PUBLIC_POSTHOG_KEY) {
posthog.init(NEXT_PUBLIC_POSTHOG_KEY, {
api_host: "/ingest", // update path to your chosen one I am using /ingest
ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, // add the actual host to ui_host key
// ...
});
}
// ...
That's it! 🎉
Remove PostHog
You might want to use a different analytics tool follow this guide
to remove everything related to PostHog
- Remove
PostHog
environment variables from.env.local
- Navigate to
/src/app/(site)/_layout/client-providers.tsx
- Remove any code related to
PostHog
so it becomes like this
"use client";
import { FC, PropsWithChildren } from "react";
import CustomerSupport from "../_components/customer-support";
const ClientProviders: FC<PropsWithChildren> = ({ children }) => {
return (
<>
{children}
<CustomerSupport />
</>
);
};
export default ClientProviders;
- In terminal run this command
npm uninstall posthog-js # with npm
yarn remove posthog-js # with yarn
- Add your own analytics tool if you want to