Skip to content

Commit

Permalink
Update Next.js instructions per #46
Browse files Browse the repository at this point in the history
  • Loading branch information
derrickreimer authored Jun 30, 2023
1 parent 7b5a312 commit e68b379
Showing 1 changed file with 31 additions and 21 deletions.
52 changes: 31 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,55 +228,65 @@ Create a `Fathom` client component:

```tsx
// Fathom.tsx
'use client'
"use client";

import { load, trackPageview } from 'fathom-client'
import { useEffect, Suspense } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
import { load, trackPageview } from "fathom-client";
import { useEffect, Suspense } from "react";
import { usePathname, useSearchParams } from "next/navigation";

function TrackPageView() {
const pathname = usePathname()
const searchParams = useSearchParams()
const pathname = usePathname();
const searchParams = useSearchParams();

// Load the Fathom script on mount
useEffect(() => {
load('MY_FATHOM_ID', {
includedDomains: ['yourwebsite.com'],
auto: false
})
}, [])
load("MY_FATHOM_ID", {
includedDomains: ["yourwebsite.com"],
auto: false,
});
}, []);

// Record a pageview when route changes
useEffect(() => {
trackPageview();
}, [pathname, searchParams])
if (!pathname) return;

trackPageview({
url: pathname + searchParams.toString(),
referrer: document.referrer,
});
}, [pathname, searchParams]);

return null;
}

export default function Fathom() {
return <Suspense fallback={null}>
<TrackPageView />
</Suspense>
return (
<Suspense fallback={null}>
<TrackPageView />
</Suspense>
);
}
```

Note that we explicitly pass the `url` to `trackPageview` to avoid race conditions that occur when we allow the Fathom script to infer the URL from the browser.

Then, add the client component to your root `layout.tsx` file:

```tsx
// layout.tsx

import Fathom from "./Fathom"
import Fathom from "./Fathom";

export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
</head>
<head></head>
<body>
<Fathom />
<Page>{children}</Page>
</body>
</html>
)
);
}
```

Expand Down

0 comments on commit e68b379

Please sign in to comment.