Skip to content

feat(django): opt-in posthog-js cookie fallback for request context - #1045

Open
DanielVisca wants to merge 7 commits into
mainfrom
posthog/django-posthog-js-cookie
Open

DanielVisca wants to merge 7 commits into
mainfrom
posthog/django-posthog-js-cookie

Conversation

@DanielVisca

@DanielVisca DanielVisca commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Backend events only link to a browser session when the frontend sets tracing_headers for the backend hostname. Most apps never set it, so their Django events have no $session_id and do not show with session replays.

posthog-js already stores the distinct ID and the session ID in its first-party cookie ph_<project token>_posthog (default persistence localStorage+cookie). The browser sends this cookie on every same-site request, so the middleware can link the request with no frontend change.

Changes:

  • New setting POSTHOG_MW_READ_POSTHOG_COOKIE (default False). When it is True, PosthogContextMiddleware reads the posthog-js cookie, but only when the request has neither tracing header. A request never mixes header and cookie values.
  • From the cookie it takes the session ID, and the distinct ID only when $user_state is identified. Anonymous visitors stay personless on the backend, as they are with posthog-js's default identified_only profiles. An authenticated user ID still wins over the cookie distinct ID.
  • The session ID is used only when its last activity is within the posthog-js default idle timeout (30 minutes) and the session is shorter than 24 hours. Timestamps use an absolute difference, like posthog-js. The older two-item $sesid format is accepted.
  • The cookie name comes from the middleware client key or the module key (trimmed), with the same +, /, = replacement that posthog-js uses. When no key is known, the cookie is used only when exactly one ph_*_posthog cookie is present.
  • The cookie is ignored when the posthog-js consent cookie (__ph_opt_in_out_<token>) opts the visitor out.

Why opt-in: posthog-js keeps opt-out consent in localStorage by default, and the server cannot read that. A default-on fallback would keep linking backend events to a visitor who rejected tracking. Teams that store consent in a cookie, or that do not use opt-out, can turn it on.

A custom posthog-js session_idle_timeout_seconds (clamped to 60 seconds through 10 hours, like posthog-js) and opt_out_capturing_by_default are supported through POSTHOG_MW_COOKIE_SESSION_IDLE_TIMEOUT_SECONDS and POSTHOG_MW_COOKIE_OPT_OUT_BY_DEFAULT.

Known limits: a custom persistence_name, custom consent cookie names, respect_dnt, and non-cookie posthog-js persistence are not handled. The option docs list these.

Spec: the tracing headers spec lists only headers as server-side input. PostHog/sdk-specs#116 adds the optional cookie fallback this PR implements.

Like the headers, the cookie is analytics context only and is never used for authentication.

💚 How did you test it?

I ran these (agent): pytest posthog/test/integrations/ passes. The new parameterized test covers a live cookie session, headers that win over the cookie, an authenticated user that wins over the cookie distinct ID, idle, too-long and future-dated sessions that are dropped, another project's cookie, the opt-out cookie, POSTHOG_MW_READ_POSTHOG_COOKIE off by default and set to False, an anonymous visitor, and the older two-item session. ruff passes, and mypy shows only errors that already exist in this file on main. I did not test in a running Django app.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Written by the PostHog Slack app (Claude Code, claude-opus-5-5), as one of a small set of PRs that link backend events to sessions without customer setup. Related: feat(replay): match backend events to recordings by person and time posthog#114733 matches existing events without a session ID to recordings at query time.
  • I read the cookie format from posthog-js (COOKIE_PERSISTED_PROPERTIES, $sesid = [lastActivity, sessionId, sessionStart]).
  • The docs need a short note on the Django page after this merges.

Created with PostHog from a Slack thread

🤖 Generated with Claude Code

…sing

The middleware reads the distinct ID and the live session ID from the ph_<token>_posthog cookie as a fallback. Headers still win, and an authenticated user ID still wins over the cookie distinct ID. POSTHOG_MW_READ_POSTHOG_COOKIE = False turns it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-09T20:34:28.669446+00:00
Duration: 259887ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 511ms
Required Headers.Has Authorization Bearer Header ✅ 510ms
Required Headers.Has Content Type Json ✅ 511ms
Required Headers.Has Posthog Sdk Info Format ✅ 511ms
Required Headers.Has Posthog Attempt Header ✅ 510ms
Required Headers.Has Posthog Request Id ✅ 510ms
Required Headers.Has Posthog Request Timestamp ✅ 510ms
Required Headers.Has User Agent ✅ 510ms
Body Format.Body Has Created At And Batch ✅ 510ms
Body Format.No Api Key In Body ✅ 511ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 516ms
Event Format.Distinct Id Is String ✅ 510ms
Event Format.Distinct Id At Root Not Properties ✅ 510ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 510ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 511ms
Event Format.Event Has Required Root Fields Batch ✅ 513ms
Event Format.Event Uuid Is Valid Batch ✅ 518ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 514ms
Event Format.Set Once Properties Preserved Batch ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 513ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1011ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 511ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 512ms
Deduplication.Preserves Uuid On Retry ✅ 6519ms
Deduplication.Preserves Timestamp On Retry ✅ 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6521ms
Deduplication.No Duplicate Events In Batch ✅ 519ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13520ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 514ms
Response Format Validation.Success No Retry After When All Ok ✅ 512ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 513ms
Response Format Validation.Response Echoes Request Id ✅ 510ms
Retry Behavior.Retries On 408 ✅ 6520ms
Retry Behavior.Retries On 500 ✅ 6515ms
Retry Behavior.Retries On 503 ✅ 8523ms
Retry Behavior.Retries On 504 ✅ 6516ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11524ms
Retry Behavior.Does Not Retry On 400 ✅ 2511ms
Retry Behavior.Does Not Retry On 401 ✅ 2514ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2513ms
Retry Behavior.Does Not Retry On 415 ✅ 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22532ms
Retry Behavior.Max Retries Respected ✅ 22535ms
Partial Batch Handling.Handles 200 Full Success ✅ 2514ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3517ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3514ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3513ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6522ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6521ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3520ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 510ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2513ms
Event Options.Cookieless Mode Override ✅ 510ms
Event Options.Disable Skew Correction Override ✅ 510ms
Event Options.Process Person Profile Override ✅ 510ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 511ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 510ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 511ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 510ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 510ms
Identity.Capture Ai Event Has Uuid ✅ 511ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 510ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 510ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 12ms
Request Payload.Flags Request Uses V2 Query Param ✅ 9ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 10ms
Request Payload.Flags Request Omits Authorization Header ✅ 9ms
Request Payload.Token In Flags Body Matches Init ✅ 9ms
Request Payload.Groups Round Trip ✅ 9ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 9ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 10ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 9ms
Retry Behavior.Retries Flags On 502 ✅ 313ms
Retry Behavior.Retries Flags On 504 ✅ 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 511ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 70ms
Versioned Boolean Matching.Matching Version 1 ✅ 68ms
Versioned Boolean Matching.Matching Version 2 ✅ 68ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 35ms

@greptile-apps

greptile-apps Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium impact] The PR appears safe to merge, with a non-blocking consent-scoping issue in the unknown-key fallback.

Reviews (2) · Last reviewed commit: "fix(django): only read this project's po..." · Reviewed by Greptile

Comment thread posthog/integrations/django.py Outdated
Comment thread posthog/integrations/django.py Outdated
Comment thread posthog/test/integrations/test_middleware.py Outdated
…pt-out

Read the cookie for the known project key only (trimmed, with the posthog-js character replacement), ignore it when the consent cookie opts out, compare timestamps with an absolute difference, update the public API snapshot, and cover the setting and the 24-hour cap in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
@DanielVisca
DanielVisca marked this pull request as ready for review October 9, 2026 18:49
@DanielVisca
DanielVisca requested a review from a team as a code owner October 9, 2026 18:49
Comment on lines +117 to +121
consent_values = [
value
for name, value in cookies.items()
if name.startswith(_POSTHOG_CONSENT_COOKIE_PREFIX)
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Unrelated opt-outs drop session links

When no middleware or module key is set, _read_posthog_cookie checks every project's consent cookie. A request with only ph_projectA_posthog and __ph_opt_in_out_projectB=0 therefore loses project A's distinct ID and session ID, even though the visitor opted out only of project B. This can drop browser-session links for apps that capture through an explicit client without setting POSTHOG_MW_CLIENT.

Keep the selected cookie's name and check consent only for that project.

Knowledge Base Used: Framework integrations

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/integrations/django.py
Line: 117-121

Comment:
**Unrelated opt-outs drop session links**

When no middleware or module key is set, `_read_posthog_cookie` checks every project's consent cookie. A request with only `ph_projectA_posthog` and `__ph_opt_in_out_projectB=0` therefore loses project A's distinct ID and session ID, even though the visitor opted out only of project B. This can drop browser-session links for apps that capture through an explicit client without setting `POSTHOG_MW_CLIENT`.

Keep the selected cookie's name and check consent only for that project.

**Knowledge Base Used:** [Framework integrations](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/framework-integrations.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@DanielVisca DanielVisca added the stamphog Request stamphog review label Oct 9, 2026 — with PostHog
@stamphog stamphog Bot removed the stamphog Request stamphog review label Oct 9, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approved — this change needs a human reviewer.

Re-adding the stamphog label gives the same result unless the changed files change.

stamphog can't approve this pull request, because two policy gates refused it. The deny-list gate matched public_api: the change adds a new read_posthog_cookie attribute to PosthogContextMiddleware, which shows up in references/public_api_snapshot.txt. The tier gate classified it as T2-never (260 lines across 4 files, cross-cutting, a feat change), a category that always needs a human reviewer. The size gate passed, so splitting the PR won't clear the refusal. Please ask a human maintainer to review it, ideally someone who owns the Django integration and the public API surface.

  • 👍 on the PR from greptile-apps[bot].
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: public_api
size ✓ 125L, 1F substantive, 260L/4F incl. docs/generated/snapshots — within ceiling
tier ✗ classified as T2-never: T2-never (260L, 4F, cross-cutting, feat)
stamphog 2.4.1 .stamphog/policy.yml @ unknown · reviewed head 4efbf1a

Comment thread posthog/integrations/django.py Outdated
@veria-ai

veria-ai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

…safe

POSTHOG_MW_READ_POSTHOG_COOKIE is now off by default, because the server cannot see an opt-out that posthog-js keeps in localStorage. Read the cookie only when neither tracing header is present, take the distinct ID only for identified users so anonymous visitors stay personless, and accept the older two-item $sesid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
@DanielVisca DanielVisca changed the title feat(django): read the posthog-js cookie when tracing headers are missing feat(django): optionally read the posthog-js cookie when tracing headers are missing Oct 9, 2026
@DanielVisca DanielVisca changed the title feat(django): optionally read the posthog-js cookie when tracing headers are missing feat(django): opt-in posthog-js cookie fallback for request context Oct 9, 2026
…back

Add POSTHOG_MW_COOKIE_SESSION_IDLE_TIMEOUT_SECONDS for projects with a custom posthog-js session_idle_timeout_seconds, and list the unsupported posthog-js configurations in the middleware docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
Clamp POSTHOG_MW_COOKIE_SESSION_IDLE_TIMEOUT_SECONDS to 60 seconds through 10 hours, the bounds posthog-js applies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
Add POSTHOG_MW_COOKIE_OPT_OUT_BY_DEFAULT, so a visitor without a consent cookie counts as opted out, like posthog-js with opt_out_capturing_by_default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2
POSTHOG_MW_COOKIE_SESSION_IDLE_TIMEOUT_SECONDS = 0 now falls back to 30 minutes, like posthog-js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 80f44d9e-704d-4f9c-93d2-bd37d55ab1c2

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant