Generated banner for Instrument Feature Flags
Generated logo for Instrument Feature Flags

Instrument Feature Flags

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog feature flags to gate new functionality. Use after implementing features or reviewing PRs to ensure safe rollouts with feature flag controls. Also handles initial PostHog SDK setup if not yet installed.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to instrumenting PostHog feature flags within your codebase. It handles the end-to-end process, including detecting your platform, setting up the PostHog SDK if necessary, configuring environment variables, and implementing the code required to gate features. It emphasizes best practices such as using environment variables for configuration, preferring server-side evaluation to prevent UI flicker, and ensuring minimal, non-intrusive code changes.

What it does

  • Detects your project's platform and language automatically.
  • Initializes the PostHog SDK if it is not already present in the project.
  • Configures required environment variables securely without hardcoding.
  • Provides platform-specific code patterns for implementing feature flag checks.
  • Guides the integration of boolean and multivariate feature flags.
  • Ensures PostHog configuration does not break application boot or runtime stability.

When to use it

  • When you need to gate new functionality for controlled releases.
  • After implementing a new feature that requires a safe rollout strategy.
  • When reviewing pull requests that introduce features needing toggle controls.
  • When you need to set up PostHog instrumentation in a new or existing project.

Advantages

  • Supports a wide range of languages, frameworks, and platforms.
  • Promotes safe, production-ready instrumentation patterns.
  • Prevents common issues like UI flicker through server-side evaluation.
  • Maintains clean code by avoiding hardcoded configuration keys.

Usage examples

“Add a PostHog feature flag to gate the new checkout button in my React app.”
The agent will analyze your React project, verify PostHog setup, and provide the code snippet using posthog.isFeatureEnabled to conditionally render the button.
“I need to instrument a new feature flag for my Node.js backend.”
The agent will detect the Node.js environment, ensure the SDK is initialized, and guide you through adding the flag check logic to your server-side code.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/instrument-feature-flags/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip instrument-feature-flags.zip -d .agents/skills

Documentation by PostHog

Add PostHog feature flags

Use this skill to add PostHog feature flags that gate new or changed functionality. Use it after implementing features or reviewing PRs to ensure safe rollouts with feature flag controls. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any platform or language.

Supported platforms: React, Next.js, React Native, Web (JavaScript), Node.js, Python, PHP, Ruby, Go, Java, Rust, .NET, Elixir, Android, iOS, Flutter, and the REST API.

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, go.mod, Gemfile, composer.json, mix.exs, etc.) to determine the language and framework.

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 (SDK initialization, env vars, etc.). If PostHog is already installed and initialized, skip to STEP 3.

STEP 2: Research instrumentation. (Skip if PostHog is already set up.) 2.1. Find the reference file below that matches the detected platform — it is the source of truth for SDK initialization, flag evaluation methods, and framework-specific 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: Create or find the feature flag.

  • Check if a PostHog MCP server is connected. If available, use its tools to search for an existing feature flag the user wants to instrument, or create a new one.

  • If no MCP server is available, instruct the user to create the flag in the PostHog dashboard.

STEP 4: Plan release conditions.

  • Determine the rollout strategy (percentage rollout, user targeting, group targeting, etc.).

  • Plan how the feature flag will gate the new functionality in code.

STEP 5: Instrument the feature.

  • Add the feature flag code following the platform-specific reference patterns.

  • Use server-side evaluation when possible to avoid UI flicker.

  • Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.

  • You must read a file immediately before attempting to write it.

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-get tool to retrieve the project's api_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-get MCP response for a region field — US maps to https://us.i.posthog.com, EU maps to https://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 using the framework's naming convention.

  • Reference these environment variables in code instead of hardcoding them.

Reference files

  • references/react.md - React feature flags installation

  • references/react-native.md - React native feature flags installation

  • references/web.md - Web feature flags installation

  • references/nodejs.md - Node.js feature flags installation

  • references/python.md - Python feature flags installation

  • references/django.md - Django

  • references/flask.md - Flask

  • references/php.md - Php feature flags installation

  • references/laravel.md - Laravel

  • references/ruby.md - Ruby feature flags installation

  • references/ruby-on-rails.md - Ruby on rails

  • references/go.md - Go feature flags installation

  • references/java.md - Java feature flags installation

  • references/rust.md - Rust feature flags installation

  • references/dotnet.md - .net feature flags installation

  • references/dotnet.md - .net

  • references/elixir.md - Elixir feature flags installation

  • references/android.md - Android feature flags installation

  • references/ios.md - Ios feature flags installation

  • references/usage.md - Ios SDK usage

  • references/flutter.md - Flutter feature flags installation

  • references/api.md - API feature flags installation

  • references/next-js.md - Next.js

  • references/adding-feature-flag-code.md - Adding feature flag code

  • references/best-practices.md - Best practices for production-ready flags

  • references/COMMANDMENTS.md - Framework-specific rules the integration must follow

Each platform reference contains SDK-specific installation, flag evaluation, and code examples. Find the one matching the user's stack. If unlisted, use the API reference as a fallback.

Key principles

  • Environment variables: Always use environment variables for PostHog keys. Never hardcode them.

  • Minimal changes: Add feature flag code alongside existing logic. Don't replace or restructure existing code.

  • Boolean flags first: Default to boolean flag checks unless the user specifically asks for multivariate flags.

  • Server-side when possible: Prefer server-side flag evaluation to avoid UI flicker.

Files

references/laravel.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

Laravel

Canonical URL: https://posthog.com/docs/libraries/laravel

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.i.posthog.com instead of https://us.i.posthog.com (ingestion host).

On this page

  • Laravel SDK (experimental)

  • Manual setup with the PHP SDK

  • Install with the wizard

  • Next steps

You can integrate PostHog with Laravel using the experimental Laravel SDK or the PHP SDK with manual instrumentation. Both approaches are supported. The Laravel SDK builds on the PHP SDK and adds automatic request context, exception reporting, and worker lifecycle management.

Laravel SDK (experimental)

Experimental: The Laravel SDK is under active development, and its API may change. If you prefer to instrument your application yourself, the manual PHP SDK setup remains supported.

The PostHog Laravel SDK supports Laravel 12 and 13. It requires PHP 8.2 or later (PHP 8.3 or later for Laravel 13).

Installation

Install posthog/posthog-laravel and publish its configuration:

composer require posthog/posthog-laravel
php artisan posthog:install

Add your project token and ingestion host to your server's .env:

.env

POSTHOG_API_KEY=<ph_project_token>
POSTHOG_HOST=https://us.i.posthog.com

Laravel's package discovery registers the service provider and facade automatically. If discovery is disabled, register PostHog\Laravel\PostHogServiceProvider manually. No PHP SDK initialization or custom middleware is needed.

Configure the SDK in config/posthog.php. It's enabled by default; set POSTHOG_ENABLED=false to disable it.

For browser events and session replay, install the JavaScript SDK separately.

Capturing events and identifying users

Use the Laravel facade, not the PHP SDK's PostHog\PostHog class:

use PostHog\Laravel\Facades\PostHog;

PostHog::capture("checkout_completed", ["items" => 2]);
PostHog::capture("import_completed", ["rows" => 42], "account-123");
PostHog::identify([
    "distinctId" => "account-123",
    "properties" => ["plan" => "paid"],
]);

The SDK uses the authenticated user's ID automatically, or you can pass a distinct ID explicitly as shown above. Without an identity, each event gets a new random ID without a person profile; these IDs don't identify returning visitors.

To link browser sessions to backend events, configure the JavaScript SDK's tracing headers. These headers are untrusted analytics input, not authentication. Pass an authenticated identity explicitly for security-sensitive events or flag decisions.

The SDK doesn't collect request bodies, query strings, email, or IP addresses by default. Check your own event properties and exception messages for sensitive data.

Feature flags

Evaluate flags using the current request identity, or pass a distinct ID explicitly:

use PostHog\Laravel\Facades\PostHog;

$flags = PostHog::evaluateFlags(distinctId: "account-123");
$isEnabled = $flags->isEnabled("new-checkout");
$variant = $flags->getFlag("checkout-layout");
$payload = $flags->getFlagPayload("checkout-layout");

You can omit distinctId to use the current request identity. Without an identity, flag evaluation returns an empty result.

For local evaluation, set POSTHOG_SECRET_KEY to your feature flags secure API key. Keep it on the server. In production, enable flag_cache.enabled and select a shared Laravel cache store with flag_cache.store in config/posthog.php.

Laravel Pennant

The SDK includes an optional read-only Pennant store. Install Pennant and select the PostHog store:

composer require laravel/pennant:^1.26

.env

PENNANT_STORE=posthog

Read flags using their PostHog keys:

use Laravel\Pennant\Feature;

$isEnabled = Feature::for("account-123")->active("new-checkout");
$variant = Feature::for("account-123")->value("checkout-layout");

Pennant uses the authenticated user by default, or an explicit scope as shown above. The store is read-only: create and manage flags in PostHog, not through Pennant write operations. You don't need a Pennant migration.

Capturing exceptions

The SDK automatically captures exceptions reported through Laravel's reportable exception path. It respects dontReport and callbacks that stop reporting. Set capture_exceptions to false in config/posthog.php to disable automatic reporting.

To capture a handled exception explicitly:

use PostHog\Laravel\Facades\PostHog;

PostHog::captureException($exception, properties: ["component" => "import"]);

Don't add the manual PHP SDK report callback below when using the Laravel SDK, as this can report exceptions twice.

Optional server event collectors

All automatic server event collectors are off by default. They capture Laravel lifecycle events, not browser clicks or $autocapture events.

Publish the collector configuration:

php artisan vendor:publish --tag=posthog-autocapture-config

Enable only the collectors you need in config/posthog-autocapture.php. For example, update the auth section to capture registrations, logins, and logouts:

config/posthog-autocapture.php

"auth" => [
    "enabled" => true,
    "events" => ["registered", "login", "logout"],
],

Set requests.enabled to true for laravel_request events with route, method, status code, and duration. Keep the generated health-check and static-asset exclusions. Other collectors cover model changes, mapped domain events, jobs, commands, and scheduled tasks. Model attributes and domain-event properties must be explicitly allowlisted.

Server $pageview events are a separate opt-in through pageviews.enabled. Leave them disabled if your browser SDK already captures pageviews to avoid duplicates.

Blade flag conditionals

Set blade.enabled to true in config/posthog-autocapture.php to enable the optional Blade conditional:

@posthogFeature("new-checkout")
    <x-checkout />
@else
    <x-classic-checkout />
@endposthogFeature

This uses evaluateFlags()->isEnabled() with the current analytics context. Repeated checks share the evaluation snapshot and exposure deduplication. Disabled or unavailable flags select the @else branch. This is a presentation helper, not authorization.

Queue workers and Octane

The SDK automatically flushes events and clears context between requests, queue jobs, console commands, and sequential Octane lifecycles. Identity and session context propagate to jobs by default; set queue_context to false to disable this.

Don't store scoped PostHog services in application singletons. Overlapping Swoole coroutines sharing one Laravel container aren't supported.

Testing and diagnostics

Use the fake to test instrumentation without sending events:

use PostHog\Laravel\Facades\PostHog;

$fake = PostHog::fake();
PostHog::capture("checkout_completed", ["items" => 2], "account-123");
$fake->assertCaptured("checkout_completed");
$fake->assertCapturedCount(1);

Run php artisan posthog:doctor to validate local configuration without sending a diagnostic event. To send a test event explicitly, run php artisan posthog:test --send.

Manual setup with the PHP SDK

Using the PHP SDK directly remains supported. Use this approach if you want to manage initialization, request context, exception reporting, and flushing yourself. The examples below use PostHog\PostHog, not the Laravel facade. Don't combine this setup with the Laravel SDK's automatic integration.

The wizard installs the PHP SDK, not the experimental Laravel SDK.

Install with the wizard

Run this command in your project directory to add PostHog to your Laravel project. The wizard detects your framework, installs the SDK, and sets up your first events.

npx @posthog/wizard

Or set it up manually by following the rest of this guide.

Initialize the PHP SDK

Install the PHP SDK as described in the PHP installation guide, then add your project token and host to .env:

.env

POSTHOG_API_KEY=<ph_project_token>
POSTHOG_HOST=https://us.i.posthog.com

Add PostHog to Laravel's services config:

config/services.php

'posthog' => [
    'api_key' => env('POSTHOG_API_KEY'),
    'host' => env('POSTHOG_HOST', 'https://us.i.posthog.com'),
],

Initialize PostHog in the boot method of app/Providers/AppServiceProvider.php:

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use PostHog\PostHog;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        if (! config('services.posthog.api_key')) {
            return;
        }

        PostHog::init(
            config('services.posthog.api_key'),
            [
                'host' => config('services.posthog.host'),
            ]
        );
    }
}
Request context middleware

Client SDKs such as PostHog JS can send tracing headers to your Laravel backend. Configure tracing_headers for your Laravel backend hostname so browser requests include the session and distinct ID headers.

The PHP SDK can read X-PostHog-Distinct-Id and X-PostHog-Session-Id headers and apply them to events captured during the request. Tracing headers are client-controlled analytics context, not authentication or authorization. For security-sensitive server-side events or decisions, pass an authenticated distinctId explicitly, such as auth()->id(). For the lower-level context APIs, see the PHP request context docs.

Add middleware like this:

app/Http/Middleware/PostHogRequestContext.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use PostHog\PostHog;
use Symfony\Component\HttpFoundation\Response;

final class PostHogRequestContext
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! config('services.posthog.api_key')) {
            return $next($request);
        }

        $context = PostHog::contextFromHeaders($request->headers->all());

        $context['properties'] = array_merge(
            $context['properties'] ?? [],
            array_filter([
                '$current_url' => $request->fullUrl(),
                '$request_method' => $request->method(),
                '$request_path' => $request->getPathInfo(),
                '$user_agent' => $request->userAgent(),
                '$ip' => $request->ip(),
            ], static fn ($value): bool => $value !== null && $value !== '')
        );

        return PostHog::withContext(
            $context,
            static fn (): Response => $next($request),
            ['fresh' => true]
        );
    }
}

Register this middleware using your Laravel version's normal middleware registration.

Error tracking in Laravel

The PHP SDK supports error tracking, but Laravel handles most request exceptions before they become uncaught PHP exceptions. Capture Laravel-reported exceptions explicitly.

In Laravel 11 and later, add a report callback in bootstrap/app.php:

bootstrap/app.php

use Illuminate\Foundation\Configuration\Exceptions;
use PostHog\PostHog;
use Throwable;

->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->report(function (Throwable $e): void {
        if (! config('services.posthog.api_key')) {
            return;
        }

        PostHog::captureException(
            $e,
            auth()->id() !== null ? (string) auth()->id() : null,
            [
                '$current_url' => request()->fullUrl(),
                '$request_method' => request()->method(),
            ]
        );
    });
})

For older Laravel versions, call PostHog::captureException() from your exception handler's report method.

Long-running processes

In normal PHP request lifecycles, queued events flush when the client is destroyed. In long-running Laravel processes such as queue workers, Horizon, or Octane, call PostHog::flush() after capturing important events or at the end of a job/request.

If you prefer immediate delivery in queue workers, configure the PHP SDK with batch_size set to 1 for those workers:

PostHog::init(
    '<ph_project_token>',
    [
        'host' => config('services.posthog.host'),
        'batch_size' => 1,
    ]
);

Next steps

See the PHP SDK docs for usage examples and the full API reference.

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-feature-flags · 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-feature-flags.zip