AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, multi-step procedure for integrating the PostHog SDK into a wide range of web, mobile, and backend frameworks. It handles the detection of the project environment, installation of the appropriate SDK, initialization, user identification, and secure configuration of environment variables. The skill emphasizes following framework-specific patterns and maintaining an analytics contract, ensuring that PostHog is implemented consistently without disrupting existing application logic.
What it does
- Detects the project's framework, language, and package manager.
- Installs the correct PostHog SDK for the identified platform.
- Configures PostHog initialization and provider setup based on framework-specific references.
- Implements user identification logic for login and signup events.
- Manages environment variables for project tokens and host URLs securely.
- Verifies the integration and performs minimal cleanup.
When to use it
- When setting up PostHog in a project for the first time.
- When reviewing pull requests that require PostHog initialization.
- When adding analytics to a new application across supported frameworks.
- When migrating or updating PostHog configurations in an existing codebase.
Advantages
- Ensures consistent implementation across diverse technology stacks.
- Prevents hardcoding of sensitive project tokens and host URLs.
- Follows established framework-specific best practices and patterns.
- Minimizes the risk of breaking application boot or build processes.
- Automates the repetitive aspects of SDK setup and environment configuration.
Usage examples
- “Set up PostHog in my Next.js project.”
- The agent will detect the Next.js environment, install the PostHog SDK, configure the necessary provider, and set up environment variables in .env.local.
- “Integrate PostHog into this Android app.”
- The agent will identify the Android/Kotlin structure, initialize PostHog in the Application class, and guide the setup of local.properties for configuration.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/posthog/instrument-integration/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-integration.zip -d .agents/skills
Documentation by PostHog
Add PostHog SDK integration
Use this skill to add the PostHog SDK to an application. Use it when setting up PostHog for the first time, or reviewing PRs that need PostHog initialization. Covers SDK installation, provider setup, and basic configuration. Supports any framework or language.
Supported frameworks and languages: Next.js, React, React Router, Vue, Nuxt, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, PHP, Ruby on Rails, Go, Elixir, Android, iOS, Swift, Flutter, React Native, Expo, Node.js, and vanilla JavaScript.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Look for dependency files (package.json, pubspec.yaml, Podfile, Package.swift, requirements.txt, Gemfile, composer.json, go.mod, mix.exs, etc.) to determine the framework and language.
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) to determine the package manager.
Check for existing PostHog setup. If PostHog is already installed and initialized, do not modify its code. Inform the user and skip to verification.
STEP 2: Research integration. 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and configuration patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.
STEP 3: Install the PostHog SDK.
Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.
STEP 4: Initialize PostHog.
Follow the framework reference for where and how to initialize. This varies significantly by framework (e.g., instrumentation-client.ts for Next.js 15.3+, AppConfig.ready() for Django, create_app() for Flask).
Set up the PostHog provider/wrapper component if the framework requires one.
STEP 5: Identify users.
Add PostHog
identify()calls on the client side during login and signup events.If both frontend and backend exist, pass the client-side session and distinct ID using
X-POSTHOG-DISTINCT-IDandX-POSTHOG-SESSION-IDheaders to the server-side code.
STEP 6: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.Write these values to the appropriate env file (e.g.
.env.localfor Next.js,.envfor others) using the framework's naming convention.Reference these environment variables in code instead of hardcoding them.
STEP 7: Verify and clean up.
Check the project for errors. Look for type checking or build scripts in package.json.
Ensure any components created were actually used.
Run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Never run formatting or linting across the entire project's codebase.
Reference files
references/EXAMPLE-next-app-router.md- next-app-router example project codereferences/EXAMPLE-next-pages-router.md- next-pages-router example project codereferences/EXAMPLE-react-react-router-6.md- react-react-router-6 example project codereferences/EXAMPLE-react-react-router-7-framework.md- react-react-router-7-framework example project codereferences/EXAMPLE-react-react-router-7-data.md- react-react-router-7-data example project codereferences/EXAMPLE-react-react-router-7-declarative.md- react-react-router-7-declarative example project codereferences/EXAMPLE-react-vite.md- react-vite example project codereferences/EXAMPLE-nuxt-3-6.md- nuxt-3-6 example project codereferences/EXAMPLE-nuxt-4.md- nuxt-4 example project codereferences/EXAMPLE-vue-3.md- vue-3 example project codereferences/EXAMPLE-react-tanstack-router-file-based.md- react-tanstack-router-file-based example project codereferences/EXAMPLE-react-tanstack-router-code-based.md- react-tanstack-router-code-based example project codereferences/EXAMPLE-tanstack-start.md- tanstack-start example project codereferences/EXAMPLE-sveltekit.md- sveltekit example project codereferences/EXAMPLE-astro-static.md- astro-static example project codereferences/EXAMPLE-astro-view-transitions.md- astro-view-transitions example project codereferences/EXAMPLE-astro-ssr.md- astro-ssr example project codereferences/EXAMPLE-astro-hybrid.md- astro-hybrid example project codereferences/EXAMPLE-angular.md- angular example project codereferences/EXAMPLE-javascript-node.md- javascript-node example project codereferences/EXAMPLE-javascript-web.md- javascript-web example project codereferences/EXAMPLE-django.md- django example project codereferences/EXAMPLE-flask.md- flask example project codereferences/EXAMPLE-fastapi.md- fastapi example project codereferences/EXAMPLE-python.md- python example project codereferences/EXAMPLE-laravel.md- laravel example project codereferences/EXAMPLE-php.md- php example project codereferences/EXAMPLE-ruby-on-rails.md- ruby-on-rails example project codereferences/EXAMPLE-ruby.md- ruby example project codereferences/EXAMPLE-android.md- android example project codereferences/EXAMPLE-swift.md- swift example project codereferences/EXAMPLE-react-native.md- react-native example project codereferences/EXAMPLE-expo.md- expo example project codereferences/next-js.md- Next.jsreferences/react.md- Reactreferences/react-router-v6.md- React router v6references/react-router-v7-framework-mode.md- React router v7 framework mode (remix v3)references/react-router-v7-data-mode.md- React router v7 data modereferences/react-router-v7-declarative-mode.md- React router v7 declarative modereferences/nuxt-js-3-6.md- Nuxt.js (v3.0 to v3.6)references/nuxt-js.md- Nuxt.jsreferences/vue-js.md- Vue.jsreferences/tanstack-start.md- Tanstack startreferences/svelte.md- Sveltereferences/astro.md- Astroreferences/angular.md- Angularreferences/js.md- JavaScript webreferences/posthog-js.md- PostHog JavaScript web SDKreferences/node.md- Node.jsreferences/posthog-node.md- PostHog Node.js SDKreferences/django.md- Djangoreferences/flask.md- Flaskreferences/python.md- Pythonreferences/posthog-python.md- PostHog python SDKreferences/dotnet.md- .netreferences/elixir.md- Elixirreferences/go.md- Goreferences/laravel.md- Laravelreferences/php.md- Phpreferences/ruby-on-rails.md- Ruby on railsreferences/ruby.md- Rubyreferences/android.md- Androidreferences/ios.md- Iosreferences/usage.md- Ios SDK usagereferences/configuration.md- Ios SDK configurationreferences/flutter.md- Flutterreferences/react-native.md- React nativereferences/identify-users.md- Identify usersreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each framework reference contains SDK-specific installation, initialization, and usage patterns. Find the one matching the user's stack.
Key principles
Environment variables: Always use environment variables for PostHog keys. Never hardcode them.
Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.
Match the example: Your implementation should follow the example project's patterns as closely as possible.
Analytics contract: Treat event names, property names, and feature flag keys as part of an analytics contract. Reuse existing names and patterns found in the project. When introducing new ones, make them clear, descriptive, and consistent with existing conventions.
Files
- ATTRIBUTION.mdAdded by AutoGineer952 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.8 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/EXAMPLE-android.md49.8 KiB
- references/EXAMPLE-angular.md23.1 KiB
- references/EXAMPLE-astro-hybrid.md27.5 KiB
- references/EXAMPLE-astro-ssr.md27.6 KiB
- references/EXAMPLE-astro-static.md19.6 KiB
- references/EXAMPLE-astro-view-transitions.md23.3 KiB
- references/EXAMPLE-django.md30.7 KiB
- references/EXAMPLE-expo.md35.1 KiB
- references/EXAMPLE-fastapi.md40.9 KiB
- references/EXAMPLE-flask.md32.4 KiB
- references/EXAMPLE-javascript-node.md9.0 KiB
- references/EXAMPLE-javascript-web.md11.8 KiB
- references/EXAMPLE-laravel.md59.3 KiB
- references/EXAMPLE-next-app-router.md17.6 KiB
- references/EXAMPLE-next-pages-router.md19.1 KiB
- references/EXAMPLE-nuxt-3-6.md22.3 KiB
- references/EXAMPLE-nuxt-4.md28.9 KiB
- references/EXAMPLE-php.md13.0 KiB
- references/EXAMPLE-python.md11.6 KiB
- references/EXAMPLE-react-native.md46.0 KiB
- references/EXAMPLE-react-react-router-6.md13.5 KiB
- references/EXAMPLE-react-react-router-7-data.md20.1 KiB
- references/EXAMPLE-react-react-router-7-declarative.md15.0 KiB
- references/EXAMPLE-react-react-router-7-framework.md32.5 KiB
- references/EXAMPLE-react-tanstack-router-code-based.md19.6 KiB
- references/EXAMPLE-react-tanstack-router-file-based.md18.3 KiB
- references/EXAMPLE-react-vite.md12.4 KiB
- references/EXAMPLE-ruby-on-rails.md38.0 KiB
- references/EXAMPLE-ruby.md10.0 KiB
- references/EXAMPLE-sveltekit.md18.6 KiB
- references/EXAMPLE-swift.md18.8 KiB
- references/EXAMPLE-tanstack-start.md29.9 KiB
- references/EXAMPLE-vue-3.md17.9 KiB
- references/android.md33.3 KiB
- references/angular.md16.5 KiB
- references/astro.md15.8 KiB
- references/configuration.md17.2 KiB
- references/django.md14.9 KiB
- references/dotnet.md25.8 KiB
- references/elixir.md17.6 KiB
- references/flask.md8.1 KiB
- references/flutter.md42.8 KiB
- references/go.md20.1 KiB
- references/identify-users.md12.2 KiB
- references/ios.md8.0 KiB
- references/js.md16.1 KiB
- references/laravel.md13.1 KiB
- references/next-js.md18.3 KiB
- references/node.md45.6 KiB
- references/nuxt-js-3-6.md11.4 KiB
- references/nuxt-js.md15.1 KiB
- references/php.md23.7 KiB
- references/posthog-js.md51.6 KiB
- references/posthog-node.md33.9 KiB
- references/posthog-python.md69.3 KiB
- references/python.md52.2 KiB
- references/react-native.md59.9 KiB
- references/react-router-v6.md13.6 KiB
- references/react-router-v7-data-mode.md13.5 KiB
- references/react-router-v7-declarative-mode.md13.7 KiB
- references/react-router-v7-framework-mode.md20.2 KiB
- references/react.md21.9 KiB
- references/ruby-on-rails.md19.7 KiB
- references/ruby.md25.5 KiB
- references/svelte.md14.6 KiB
- references/tanstack-start.md12.8 KiB
- references/usage.md29.2 KiB
- references/vue-js.md13.4 KiB
references/EXAMPLE-react-react-router-7-framework.md
PostHog react-react-router-7-framework Example Project
Repository: https://github.com/PostHog/context-mill Path: example-apps/react-react-router-7-framework
README.md
PostHog React Router 7 Framework example
This is a React Router 7 Framework example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking.
Features
Product Analytics: Track user events and behaviors
Session Replay: Record and replay user sessions
Error Tracking: Capture and track errors
User Authentication: Demo login system with PostHog user identification
Server-side & Client-side Tracking: Examples of both tracking methods
SSR Support: Server-side rendering with React Router 7 Framework
Getting Started
1. Install Dependencies
npm install
# or
pnpm install2. Configure Environment Variables
Create a .env file in the root directory:
VITE_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token
VITE_PUBLIC_POSTHOG_HOST=https://us.i.posthog.comGet your PostHog project token from your PostHog project settings.
3. Run the Development Server
npm run dev
# or
pnpm devOpen http://localhost:5173 with your browser to see the app.
Project Structure
app/
├── components/
│ └── Header.tsx # Navigation header with auth state
├── contexts/
│ └── AuthContext.tsx # Authentication context
├── lib/
│ ├── posthog-middleware.ts # Server-side PostHog middleware
│ └── db.ts # Database utilities
├── routes/
│ ├── home.tsx # Home/Login page
│ ├── burrito.tsx # Demo feature page with event tracking
│ ├── profile.tsx # User profile with error tracking demo
│ ├── api.auth.login.ts # Login API with server-side tracking
│ └── api.burrito.consider.ts # Burrito API with server-side tracking
├── entry.client.tsx # Client entry with PostHog initialization
├── entry.server.tsx # Server entry
└── root.tsx # Root route with error boundaryKey Integration Points
Client-side initialization (entry.client.tsx)
import posthog from 'posthog-js';
import { PostHogProvider } from '@posthog/react'
posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN, {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
defaults: '2026-01-30',
tracing_headers: [ window.location.hostname ],
});
<PostHogProvider client={posthog}>
<HydratedRouter />
</PostHogProvider>User identification (home.tsx)
The user is identified when the user logs in on the client-side.
posthog?.identify(username, {
username: username,
});
posthog?.capture('user_logged_in', {
username: username,
});The session and distinct ID are automatically passed to the backend via the X-POSTHOG-SESSION-ID and X-POSTHOG-DISTINCT-ID headers because we set the tracing_headers option in the PostHog initialization.
Important: do not identify users on the server-side.
Server-side middleware (posthog-middleware.ts)
The PostHog middleware creates a server-side PostHog client for each request and extracts session and user context from request headers:
export const posthogMiddleware: Route.MiddlewareFunction = async ({ request, context }, next) => {
const posthog = new PostHog(process.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
host: process.env.VITE_PUBLIC_POSTHOG_HOST!,
flushAt: 1,
flushInterval: 0,
});
const sessionId = request.headers.get('X-POSTHOG-SESSION-ID');
const distinctId = request.headers.get('X-POSTHOG-DISTINCT-ID');
context.posthog = posthog;
const response = await posthog.withContext(
{ sessionId: sessionId ?? undefined, distinctId: distinctId ?? undefined },
next
);
await posthog.shutdown().catch(() => {});
return response;
};Key Points:
Creates a new PostHog Node client for each request
Extracts
sessionIdanddistinctIdfrom request headers (automatically set by the client-side SDK)Sets the PostHog client on the request context for use in route handlers
Uses
withContext()to associate server-side events with the correct session/userProperly shuts down the client after each request
Event tracking (burrito.tsx)
posthog?.capture('burrito_considered', {
total_considerations: count,
username: username,
});Error tracking (root.tsx, profile.tsx)
Errors are captured in two ways:
Error boundary - The
ErrorBoundaryinroot.tsxautomatically captures unhandled React Router errors:
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
const posthog = usePostHog();
posthog.captureException(error);
// ... error UI
}Manual error capture in components (profile.tsx):
posthog.captureException(err);Server-side tracking (api.auth.login.ts, api.burrito.consider.ts)
Server-side events use the PostHog client from the request context (set by the middleware):
const posthog = (context as any).posthog as PostHog | undefined;
if (posthog) {
posthog.capture({ event: 'server_login' });
}Key Points:
The PostHog client is available via
context.posthog(set by the middleware)Events are automatically associated with the correct user/session via the middleware's
withContext()callThe
distinctIdandsessionIdare extracted from request headers and used to maintain context between client and server
Learn More
.env.example
VITE_PUBLIC_POSTHOG_PROJECT_TOKEN=
VITE_PUBLIC_POSTHOG_HOST=
PROJECT_ID=app/components/Header.tsx
import { Link } from 'react-router';
import { useAuth } from '../contexts/AuthContext';
import { usePostHog } from '@posthog/react';
export default function Header() {
const { user, logout } = useAuth();
const posthog = usePostHog();
const handleLogout = () => {
posthog?.capture('user_logged_out');
posthog?.reset();
logout();
};
return (
<header className="header">
<div className="header-container">
<nav>
<Link to="/">Home</Link>
{user && (
<>
<Link to="/burrito">Burrito Consideration</Link>
<Link to="/profile">Profile</Link>
<Link to="/error">Error</Link>
</>
)}
</nav>
<div className="user-section">
{user ? (
<>
<span>Welcome, {user.username}!</span>
<button onClick={handleLogout} className="btn-logout">
Logout
</button>
</>
) : (
<span>Not logged in</span>
)}
</div>
</div>
</header>
);
}
app/contexts/AuthContext.tsx
import { createContext, useContext, useState, type ReactNode } from 'react';
interface User {
username: string;
burritoConsiderations: number;
}
interface AuthContextType {
user: User | null;
login: (username: string, password: string) => Promise<boolean>;
logout: () => void;
incrementBurritoConsiderations: () => void;
setUser: (user: User) => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const users: Map<string, User> = new Map();
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(() => {
if (typeof window === 'undefined') return null;
const storedUsername = localStorage.getItem('currentUser');
if (storedUsername) {
const existingUser = users.get(storedUsername);
if (existingUser) {
return existingUser;
}
}
return null;
});
const login = async (username: string, password: string): Promise<boolean> => {
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
const { user: userData } = await response.json();
let localUser = users.get(username);
if (!localUser) {
localUser = userData as User;
users.set(username, localUser);
}
setUser(localUser);
localStorage.setItem('currentUser', username);
return true;
}
return false;
} catch (error) {
console.error('Login error:', error);
return false;
}
};
const logout = () => {
setUser(null);
localStorage.removeItem('currentUser');
};
const incrementBurritoConsiderations = () => {
if (user) {
user.burritoConsiderations++;
users.set(user.username, user);
setUser({ ...user });
}
};
const setUserState = (newUser: User) => {
setUser(newUser);
users.set(newUser.username, newUser);
};
return (
<AuthContext.Provider value={{ user, login, logout, incrementBurritoConsiderations, setUser: setUserState }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
app/entry.client.tsx
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
import posthog from 'posthog-js';
import { PostHogProvider } from '@posthog/react'
posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN, {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
defaults: '2026-01-30',
tracing_headers: [ window.location.hostname ],
});
startTransition(() => {
hydrateRoot(
document,
<PostHogProvider client={posthog}>
<StrictMode>
<HydratedRouter />
</StrictMode>
</PostHogProvider>,
);
});
app/entry.server.tsx
import { PassThrough } from "node:stream";
import type { EntryContext, RouterContextProvider } from "react-router";
import { createReadableStreamFromReadable } from "@react-router/node";
import { ServerRouter } from "react-router";
import { isbot } from "isbot";
import type { RenderToPipeableStreamOptions } from "react-dom/server";
import { renderToPipeableStream } from "react-dom/server";
export const streamTimeout = 5_000;
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
loadContext: RouterContextProvider,
) {
// https://httpwg.org/specs/rfc9110.html#HEAD
if (request.method.toUpperCase() === "HEAD") {
return new Response(null, {
status: responseStatusCode,
headers: responseHeaders,
});
}
return new Promise((resolve, reject) => {
let shellRendered = false;
let userAgent = request.headers.get("user-agent");
// Ensure requests from bots and SPA Mode renders wait for all content to load before responding
// https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
let readyOption: keyof RenderToPipeableStreamOptions =
(userAgent && isbot(userAgent)) || routerContext.isSpaMode
? "onAllReady"
: "onShellReady";
// Abort the rendering stream after the `streamTimeout` so it has time to
// flush down the rejected boundaries
let timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(
() => abort(),
streamTimeout + 1000,
);
const { pipe, abort } = renderToPipeableStream(
<ServerRouter context={routerContext} url={request.url} />,
{
[readyOption]() {
shellRendered = true;
const body = new PassThrough({
final(callback) {
// Clear the timeout to prevent retaining the closure and memory leak
clearTimeout(timeoutId);
timeoutId = undefined;
callback();
},
});
const stream = createReadableStreamFromReadable(body);
responseHeaders.set("Content-Type", "text/html");
pipe(body);
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
},
);
});
}
app/lib/db.ts
import sqlite3 from "sqlite3";
import { join } from "node:path";
import { promisify } from "node:util";
const dbPath = join(process.cwd(), "burrito-considerations.db");
const db = new sqlite3.Database(dbPath);
// Initialize schema
db.serialize(() => {
db.run(`
CREATE TABLE IF NOT EXISTS burrito_considerations (
username TEXT PRIMARY KEY,
count INTEGER NOT NULL DEFAULT 0
)
`);
});
const dbGet = promisify(db.get.bind(db));
const dbRun = promisify(db.run.bind(db));
export function getBurritoConsiderations(username: string): Promise<number> {
return dbGet("SELECT count FROM burrito_considerations WHERE username = ?", [username])
.then((row: any) => row?.count ?? 0);
}
export function incrementBurritoConsiderations(username: string): Promise<number> {
return dbRun(`
INSERT INTO burrito_considerations (username, count)
VALUES (?, 1)
ON CONFLICT(username) DO UPDATE SET count = count + 1
`, [username])
.then(() => {
return dbGet("SELECT count FROM burrito_considerations WHERE username = ?", [username]);
})
.then((row: any) => row.count);
}
app/lib/posthog-middleware.ts
import { PostHog } from "posthog-node";
import type { RouterContextProvider } from "react-router";
import type { Route } from "../+types/root";
export interface PostHogContext extends RouterContextProvider {
posthog?: PostHog;
}
export const posthogMiddleware: Route.MiddlewareFunction = async ({ request, context }, next) => {
const posthog = new PostHog(process.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
host: process.env.VITE_PUBLIC_POSTHOG_HOST!,
flushAt: 1,
flushInterval: 0,
});
const sessionId = request.headers.get('X-POSTHOG-SESSION-ID');
const distinctId = request.headers.get('X-POSTHOG-DISTINCT-ID');
(context as PostHogContext).posthog = posthog;
const response = await posthog.withContext(
{ sessionId: sessionId ?? undefined, distinctId: distinctId ?? undefined },
next
);
await posthog.shutdown().catch(() => {});
return response;
};
app/root.tsx
import { usePostHog } from '@posthog/react';
import {
isRouteErrorResponse,
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "react-router";
import type { Route } from "./+types/root";
import "./app.css";
import "./globals.css";
import Header from "./components/Header";
import { AuthProvider } from "./contexts/AuthContext";
import { posthogMiddleware } from "./lib/posthog-middleware";
export const middleware: Route.MiddlewareFunction[] = [
posthogMiddleware,
];
export const links: Route.LinksFunction = () => [
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
{
rel: "preconnect",
href: "https://fonts.gstatic.com",
crossOrigin: "anonymous",
},
{
rel: "stylesheet",
href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
},
];
export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}
export default function App() {
return (
<AuthProvider>
<Header />
<main>
<Outlet />
</main>
</AuthProvider>
);
}
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
let message = "Oops!";
let details = "An unexpected error occurred.";
let stack: string | undefined;
const posthog = usePostHog();
posthog.captureException(error);
if (isRouteErrorResponse(error)) {
message = error.status === 404 ? "404" : "Error";
details =
error.status === 404
? "The requested page could not be found."
: error.statusText || details;
} else if (import.meta.env.DEV && error && error instanceof Error) {
details = error.message;
stack = error.stack;
}
return (
<main className="pt-16 p-4 container mx-auto">
<h1>{message}</h1>
<p>{details}</p>
{stack && (
<pre className="w-full p-4 overflow-x-auto">
<code>{stack}</code>
</pre>
)}
</main>
);
}
app/routes.ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";
export default [
index("routes/home.tsx"),
route("burrito", "routes/burrito.tsx"),
route("profile", "routes/profile.tsx"),
route("error", "routes/error.tsx"),
route("api/auth/login", "routes/api.auth.login.ts"),
route("api/burrito/consider", "routes/api.burrito.consider.ts"),
] satisfies RouteConfig;
app/routes/api.auth.login.ts
import type { Route } from "./+types/api.auth.login";
import { getBurritoConsiderations } from "../lib/db";
import type { PostHogContext } from "../lib/posthog-middleware";
const users = new Map<string, { username: string }>();
export { users };
export async function action({ request, context }: Route.ActionArgs) {
const body = await request.json();
const { username, password } = body;
if (!username || !password) {
return Response.json({ error: 'Username and password required' }, { status: 400 });
}
let user = users.get(username);
if (!user) {
user = { username };
users.set(username, user);
}
const posthog = (context as PostHogContext).posthog;
if (posthog) {
posthog.capture({ event: 'server_login' });
}
const burritoConsiderations = await getBurritoConsiderations(username);
return Response.json({
success: true,
user: { ...user, burritoConsiderations }
});
}
app/routes/api.burrito.consider.ts
import type { Route } from "./+types/api.burrito.consider";
import { users } from "./api.auth.login";
import { incrementBurritoConsiderations } from "../lib/db";
import type { PostHogContext } from "../lib/posthog-middleware";
export async function action({ request, context }: Route.ActionArgs) {
const body = await request.json();
const { username } = body;
if (!username) {
return Response.json({ error: 'Username required' }, { status: 400 });
}
const user = users.get(username);
if (!user) {
return Response.json({ error: 'User not found' }, { status: 404 });
}
const burritoConsiderations = await incrementBurritoConsiderations(username);
const posthog = (context as PostHogContext).posthog;
posthog?.capture({ event: 'burrito_considered' });
return Response.json({
success: true,
user: { ...user, burritoConsiderations }
});
}
app/routes/burrito.tsx
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';
import type { Route } from "./+types/burrito";
import { useAuth } from '../contexts/AuthContext';
export function meta({}: Route.MetaArgs) {
return [
{ title: "Burrito Consideration - Burrito Consideration App" },
{ name: "description", content: "Consider the potential of burritos" },
];
}
export default function BurritoPage() {
const { user, setUser } = useAuth();
const navigate = useNavigate();
const [hasConsidered, setHasConsidered] = useState(false);
useEffect(() => {
if (!user) {
navigate('/');
}
}, [user, navigate]);
if (!user) {
return null;
}
const handleConsideration = async () => {
try {
const response = await fetch('/api/burrito/consider', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: user.username }),
});
if (response.ok) {
const { user: updatedUser } = await response.json();
setUser(updatedUser);
setHasConsidered(true);
setTimeout(() => setHasConsidered(false), 2000);
} else {
console.error('Failed to increment burrito considerations');
}
} catch (err) {
console.error('Error considering burrito:', err);
}
};
return (
<div className="container">
<h1>Burrito consideration zone</h1>
<p>Take a moment to truly consider the potential of burritos.</p>
<div style={{ textAlign: 'center' }}>
<button
onClick={handleConsideration}
className="btn-burrito"
>
I have considered the burrito potential
</button>
{hasConsidered && (
<p className="success">
Thank you for your consideration! Count: {user.burritoConsiderations}
</p>
)}
</div>
<div className="stats">
<h3>Consideration stats</h3>
<p>Total considerations: {user.burritoConsiderations}</p>
</div>
</div>
);
}
app/routes/error.tsx
import type { Route } from "./+types/error";
export function meta({}: Route.MetaArgs) {
return [
{ title: "Error Test - Burrito Consideration App" },
{ name: "description", content: "Test error boundary" },
];
}
export default function ErrorPage() {
// This will throw an error during render, which will be caught by ErrorBoundary
throw new Error('Test error for ErrorBoundary - this is a render-time error');
}
app/routes/home.tsx
import { useState } from 'react';
import type { Route } from "./+types/home";
import { useAuth } from '../contexts/AuthContext';
import { usePostHog } from '@posthog/react';
export function meta({}: Route.MetaArgs) {
return [
{ title: "Burrito Consideration App" },
{ name: "description", content: "Consider the potential of burritos" },
];
}
export default function Home() {
const { user, login } = useAuth();
const posthog = usePostHog();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
try {
const success = await login(username, password);
if (success) {
// Identifying the user once on login/sign up is enough.
posthog?.identify(username);
// Capture login event
posthog?.capture('user_logged_in');
setUsername('');
setPassword('');
} else {
setError('Please provide both username and password');
}
} catch (err) {
console.error('Login failed:', err);
setError('An error occurred during login');
}
};
if (user) {
return (
<div className="container">
<h1>Welcome back, {user.username}!</h1>
<p>You are logged in. Feel free to explore:</p>
<ul>
<li>Consider the potential of burritos</li>
<li>View your profile and statistics</li>
</ul>
</div>
);
}
return (
<div className="container">
<h1>Welcome to Burrito Consideration App</h1>
<p>Please sign in to begin your burrito journey</p>
<form onSubmit={handleSubmit} className="form">
<div className="form-group">
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter any username"
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter any password"
/>
</div>
{error && <p className="error">{error}</p>}
<button type="submit" className="btn-primary">Sign In</button>
</form>
<p className="note">
Note: This is a demo app. Use any username and password to sign in.
</p>
</div>
);
}
app/routes/profile.tsx
import { useEffect } from 'react';
import { useNavigate } from 'react-router';
import type { Route } from "./+types/profile";
import { useAuth } from '../contexts/AuthContext';
import posthog from 'posthog-js';
import { usePostHog } from '@posthog/react';
export function meta({}: Route.MetaArgs) {
return [
{ title: "User Profile - Burrito Consideration App" },
{ name: "description", content: "View your profile and burrito consideration stats" },
];
}
export default function ProfilePage() {
const { user } = useAuth();
const navigate = useNavigate();
const posthog = usePostHog();
useEffect(() => {
if (!user) {
navigate('/');
}
}, [user, navigate]);
if (!user) {
return null;
}
const triggerTestError = () => {
try {
throw new Error('Test error for PostHog error tracking');
} catch (err) {
console.error('Captured error:', err);
posthog.captureException(err);
}
};
return (
<div className="container">
<h1>User Profile</h1>
<div className="stats">
<h2>Your Information</h2>
<p><strong>Username:</strong> {user.username}</p>
<p><strong>Burrito Considerations:</strong> {user.burritoConsiderations}</p>
</div>
<div style={{ marginTop: '2rem' }}>
<button onClick={triggerTestError} className="btn-primary" style={{ backgroundColor: '#dc3545' }}>
Trigger Test Error (for PostHog)
</button>
</div>
<div style={{ marginTop: '2rem' }}>
<h3>Your Burrito Journey</h3>
{user.burritoConsiderations === 0 ? (
<p>You haven't considered any burritos yet. Visit the Burrito Consideration page to start!</p>
) : user.burritoConsiderations === 1 ? (
<p>You've considered the burrito potential once. Keep going!</p>
) : user.burritoConsiderations < 5 ? (
<p>You're getting the hang of burrito consideration!</p>
) : user.burritoConsiderations < 10 ? (
<p>You're becoming a burrito consideration expert!</p>
) : (
<p>You are a true burrito consideration master! 🌯</p>
)}
</div>
</div>
);
}
app/welcome/welcome.tsx
import logoDark from "./logo-dark.svg";
import logoLight from "./logo-light.svg";
export function Welcome() {
return (
<main className="flex items-center justify-center pt-16 pb-4">
<div className="flex-1 flex flex-col items-center gap-16 min-h-0">
<header className="flex flex-col items-center gap-9">
<div className="w-[500px] max-w-[100vw] p-4">
<img
src={logoLight}
alt="React Router"
className="block w-full dark:hidden"
/>
<img
src={logoDark}
alt="React Router"
className="hidden w-full dark:block"
/>
</div>
</header>
<div className="max-w-[300px] w-full space-y-6 px-4">
<nav className="rounded-3xl border border-gray-200 p-6 dark:border-gray-700 space-y-4">
<p className="leading-6 text-gray-700 dark:text-gray-200 text-center">
What's next?
</p>
<ul>
{resources.map(({ href, text, icon }) => (
<li key={href}>
<a
className="group flex items-center gap-3 self-stretch p-3 leading-normal text-blue-700 hover:underline dark:text-blue-500"
href={href}
target="_blank"
rel="noreferrer"
>
{icon}
{text}
</a>
</li>
))}
</ul>
</nav>
</div>
</div>
</main>
);
}
const resources = [
{
href: "https://reactrouter.com/docs",
text: "React Router Docs",
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="20"
viewBox="0 0 20 20"
fill="none"
className="stroke-gray-600 group-hover:stroke-current dark:stroke-gray-300"
>
<path
d="M9.99981 10.0751V9.99992M17.4688 17.4688C15.889 19.0485 11.2645 16.9853 7.13958 12.8604C3.01467 8.73546 0.951405 4.11091 2.53116 2.53116C4.11091 0.951405 8.73546 3.01467 12.8604 7.13958C16.9853 11.2645 19.0485 15.889 17.4688 17.4688ZM2.53132 17.4688C0.951566 15.8891 3.01483 11.2645 7.13974 7.13963C11.2647 3.01471 15.8892 0.951453 17.469 2.53121C19.0487 4.11096 16.9854 8.73551 12.8605 12.8604C8.73562 16.9853 4.11107 19.0486 2.53132 17.4688Z"
strokeWidth="1.5"
strokeLinecap="round"
/>
</svg>
),
},
{
href: "https://rmx.as/discord",
text: "Join Discord",
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="20"
viewBox="0 0 24 20"
fill="none"
className="stroke-gray-600 group-hover:stroke-current dark:stroke-gray-300"
>
<path
d="M15.0686 1.25995L14.5477 1.17423L14.2913 1.63578C14.1754 1.84439 14.0545 2.08275 13.9422 2.31963C12.6461 2.16488 11.3406 2.16505 10.0445 2.32014C9.92822 2.08178 9.80478 1.84975 9.67412 1.62413L9.41449 1.17584L8.90333 1.25995C7.33547 1.51794 5.80717 1.99419 4.37748 2.66939L4.19 2.75793L4.07461 2.93019C1.23864 7.16437 0.46302 11.3053 0.838165 15.3924L0.868838 15.7266L1.13844 15.9264C2.81818 17.1714 4.68053 18.1233 6.68582 18.719L7.18892 18.8684L7.50166 18.4469C7.96179 17.8268 8.36504 17.1824 8.709 16.4944L8.71099 16.4904C10.8645 17.0471 13.128 17.0485 15.2821 16.4947C15.6261 17.1826 16.0293 17.8269 16.4892 18.4469L16.805 18.8725L17.3116 18.717C19.3056 18.105 21.1876 17.1751 22.8559 15.9238L23.1224 15.724L23.1528 15.3923C23.5873 10.6524 22.3579 6.53306 19.8947 2.90714L19.7759 2.73227L19.5833 2.64518C18.1437 1.99439 16.6386 1.51826 15.0686 1.25995ZM16.6074 10.7755L16.6074 10.7756C16.5934 11.6409 16.0212 12.1444 15.4783 12.1444C14.9297 12.1444 14.3493 11.6173 14.3493 10.7877C14.3493 9.94885 14.9378 9.41192 15.4783 9.41192C16.0471 9.41192 16.6209 9.93851 16.6074 10.7755ZM8.49373 12.1444C7.94513 12.1444 7.36471 11.6173 7.36471 10.7877C7.36471 9.94885 7.95323 9.41192 8.49373 9.41192C9.06038 9.41192 9.63892 9.93712 9.6417 10.7815C9.62517 11.6239 9.05462 12.1444 8.49373 12.1444Z"
strokeWidth="1.5"
/>
</svg>
),
},
];
react-router.config.ts
import type { Config } from "@react-router/dev/config";
export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
},
} satisfies Config;
vite.config.ts
import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig, loadEnv } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
ssr: {
noExternal: ['posthog-js', '@posthog/react'],
},
server: {
proxy: {
'/ingest/static': {
target: 'https://us-assets.i.posthog.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/ingest/, ''),
},
'/ingest/array': {
target: 'https://us-assets.i.posthog.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/ingest/, ''),
},
'/ingest': {
target: env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/ingest/, ''),
},
},
},
};
});
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-integration · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-integration.zip