Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_PUBLIC_POSTHOG_PROJECT_TOKEN=<ph_project_token>
VITE_PUBLIC_POSTHOG_HOST=<ph_client_api_host>
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@
"start": "node .output/server/index.mjs"
},
"dependencies": {
"@opentelemetry/api-logs": "^0.223.0",
"@opentelemetry/exporter-logs-otlp-http": "^0.300.0",
"@opentelemetry/resources": "^3.0.0",
"@opentelemetry/sdk-logs": "^3.0.0",
"@opentelemetry/sdk-node": "^0.300.0",
"@posthog/react": "^1.11.3",
"@tanstack/react-router": "^1.158.1",
"@tanstack/react-router-devtools": "^1.158.1",
"@tanstack/react-start": "^1.158.1",
"posthog-js": "^1.441.2",
"posthog-node": "^5.59.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^2.6.0",
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@ import {
useMatch,
useRouter,
} from '@tanstack/react-router'
import { usePostHog } from '@posthog/react'
import type { ErrorComponentProps } from '@tanstack/react-router'
import { useEffect } from 'react'

export function DefaultCatchBoundary({ error }: ErrorComponentProps) {
const router = useRouter()
const posthog = usePostHog()

useEffect(() => {
posthog?.captureException(error)
}, [error, posthog])
const isRoot = useMatch({
strict: false,
select: (state) => state.id === rootRouteId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createRootRoute,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { PostHogProvider } from '@posthog/react'
import * as React from 'react'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary'
import { NotFound } from '~/components/NotFound'
Expand Down Expand Up @@ -58,14 +59,46 @@ export const Route = createRootRoute({
})

function RootDocument({ children }: { children: React.ReactNode }) {
const posthogKey = import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN
const posthogHost = import.meta.env.VITE_PUBLIC_POSTHOG_HOST

if ((!posthogKey || !posthogHost) && import.meta.env.DEV) {
const missingVariable = posthogKey
? 'VITE_PUBLIC_POSTHOG_HOST'
: 'VITE_PUBLIC_POSTHOG_PROJECT_TOKEN'
throw new Error(
`${missingVariable} variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once ${missingVariable} is configured`,
)
}

const content =
posthogKey && posthogHost ? (
<PostHogProvider
apiKey={posthogKey}
options={{
api_host: posthogHost,
defaults: '2025-05-24',
capture_exceptions: true,
debug: import.meta.env.DEV,
}}
>
{children}
<TanStackRouterDevtools position="bottom-right" />
</PostHogProvider>
) : (
<>
{children}
<TanStackRouterDevtools position="bottom-right" />
</>
)

return (
<html>
<head>
<HeadContent />
</head>
<body>
{children}
<TanStackRouterDevtools position="bottom-right" />
{content}
<Scripts />
</body>
</html>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePostHog } from '@posthog/react'
import { Link, createFileRoute, useRouter } from '@tanstack/react-router'
import { NotFound } from '~/components/NotFound'
import { PostErrorComponent } from '~/components/PostError'
Expand All @@ -15,9 +16,11 @@ export const Route = createFileRoute('/posts/$postId')({
function PostComponent() {
const invoice = Route.useLoaderData()
const router = useRouter()
const posthog = usePostHog()

const handleMarkAsPaid = async () => {
await markInvoicePaid({ data: String(invoice.id) })
posthog.capture('invoice_marked_paid')
router.invalidate()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePostHog } from '@posthog/react'
import { createFileRoute, useRouter } from '@tanstack/react-router'
import { useState } from 'react'
import { createInvoiceFn } from '~/utils/invoices'
Expand All @@ -8,6 +9,7 @@ export const Route = createFileRoute('/posts/')({

function PostsIndexComponent() {
const router = useRouter()
const posthog = usePostHog()
const [isCreating, setIsCreating] = useState(false)
const [formData, setFormData] = useState({
title: '',
Expand All @@ -29,6 +31,7 @@ function PostsIndexComponent() {
dueDate: formData.dueDate,
},
})
posthog.capture('invoice_created')
setFormData({ title: '', description: '', amount: '', dueDate: '' })
router.invalidate()
} finally {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePostHog } from '@posthog/react'
import { Link, createFileRoute, useRouter } from '@tanstack/react-router'
import { NotFound } from '~/components/NotFound'
import { PostErrorComponent } from '~/components/PostError'
Expand All @@ -12,9 +13,11 @@ export const Route = createFileRoute('/posts_/$postId/deep')({
function PostDeepComponent() {
const invoice = Route.useLoaderData()
const router = useRouter()
const posthog = usePostHog()

const handleMarkAsPaid = async () => {
await markInvoicePaid({ data: String(invoice.id) })
posthog.capture('invoice_marked_paid')
router.invalidate()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ export const createInvoiceFn = createServerFn({ method: 'POST' })
)
.handler(async ({ data }) => {
console.info('Creating invoice...', data)
return createInvoice(data)
const invoice = createInvoice(data)
const { logInvoiceCreated } = await import('./posthog-logs.server')
logInvoiceCreated()
return invoice
})

export const markInvoicePaid = createServerFn({ method: 'POST' })
Expand All @@ -145,5 +148,7 @@ export const markInvoicePaid = createServerFn({ method: 'POST' })
if (!invoice) {
throw new Error('Invoice not found')
}
const { logInvoiceMarkedPaid } = await import('./posthog-logs.server')
logInvoiceMarkedPaid()
return invoice
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { logs, type Logger } from '@opentelemetry/api-logs'
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { NodeSDK } from '@opentelemetry/sdk-node'
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'

let logger: Logger | undefined

function getPostHogLogLogger() {
if (logger) return logger

const projectToken =
process.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN ||
import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN
const host =
process.env.VITE_PUBLIC_POSTHOG_HOST || import.meta.env.VITE_PUBLIC_POSTHOG_HOST

if (!projectToken || !host) {
if (import.meta.env.DEV) {
const missingVariable = projectToken
? 'VITE_PUBLIC_POSTHOG_HOST'
: 'VITE_PUBLIC_POSTHOG_PROJECT_TOKEN'
throw new Error(
`${missingVariable} variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once ${missingVariable} is configured`,
)
}

return undefined
}

const sdk = new NodeSDK({
resource: resourceFromAttributes({
'service.name': 'tanstack-start-example-basic',
}),
logRecordProcessors: [
new BatchLogRecordProcessor({
exporter: new OTLPLogExporter({
url: `${host.replace(/\/$/, '')}/i/v1/logs`,
headers: {
Authorization: `Bearer ${projectToken}`,
},
}),
}),
],
})

sdk.start()
logger = logs.getLogger('posthog-integration')
return logger
}

export function logInvoiceCreated() {
getPostHogLogLogger()?.emit({
severityText: 'INFO',
body: 'invoice_creation_completed',
attributes: {
operation: 'create_invoice',
source: 'server_function',
},
})
}

export function logInvoiceMarkedPaid() {
getPostHogLogLogger()?.emit({
severityText: 'INFO',
body: 'invoice_payment_completed',
attributes: {
operation: 'mark_invoice_paid',
source: 'server_function',
},
})
}
Loading