Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
bfc6625
feat!: make beforeSend callbacks synchronous
turnipdabeets Oct 29, 2026
c3e4a07
Merge chore/v6-posthog-ios-4 into feat/v6-sync-before-send
turnipdabeets Oct 30, 2026
41ea6b0
fix: keep the call queue on iOS, macOS and Android
turnipdabeets Oct 30, 2026
fe0a6ff
test(android): restore the screenshot scale expectation lost in the m…
turnipdabeets Oct 30, 2026
3157fc1
fix(web): hand feature events to posthog-js before yielding
turnipdabeets Oct 30, 2026
776713d
Merge remote-tracking branch 'origin/chore/v6-posthog-ios-4' into pha…
turnipdabeets Oct 31, 2026
26380a1
docs: fold #686 release notes into the 6.0 docs
turnipdabeets Oct 31, 2026
cc8701f
Merge chore/v6-posthog-ios-4 into feat/v6-sync-before-send
turnipdabeets Nov 2, 2026
193b92e
fix: run a renaming beforeSend once and keep its user properties
turnipdabeets Oct 30, 2026
f22f4d8
Merge feat/v6-desktop-capture-v1 into feat/v6-sync-before-send
turnipdabeets Nov 2, 2026
fa11659
Merge feat/v6-sync-before-send into fix/v6-before-send-rename-once
turnipdabeets Nov 2, 2026
28f8761
fix: keep events when beforeSend resets on desktop or sets user prope…
turnipdabeets Nov 3, 2026
025cf37
fix(web): keep an event on its user when beforeSend changes the user
turnipdabeets Nov 3, 2026
9a09d06
fix(desktop): keep the prepared user's person and session state when …
turnipdabeets Nov 3, 2026
5f627ef
fix(web): don't restore the distinct id across a beforeSend consent c…
turnipdabeets Nov 3, 2026
9dde196
fix(web): drop user properties when beforeSend resets the user
turnipdabeets Nov 3, 2026
a48d07c
docs: note what a web beforeSend calling reset() keeps
turnipdabeets Nov 3, 2026
a339b60
Merge remote-tracking branch 'origin/feat/v6-desktop-capture-v1' into…
turnipdabeets Nov 3, 2026
9e34e68
Merge remote-tracking branch 'origin/feat/v6-sync-before-send' into f…
turnipdabeets Nov 3, 2026
f400ed3
Merge feat/v6-desktop-capture-v1 into fix/v6-before-send-rename-once
turnipdabeets Nov 3, 2026
c0374cb
fix: add exception steps before beforeSend on Windows and Linux
turnipdabeets Nov 3, 2026
37fb1ea
Merge feat/v6-before-send-parity into fix/v6-before-send-rename-once
turnipdabeets Nov 3, 2026
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
5 changes: 4 additions & 1 deletion .changeset/v6-major-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
- **Breaking:** remove the `PostHogSessionReplayConfig.debouncerDelay` setter — use `throttleDelay`
- **Breaking:** remove `PostHogDataMode.cellular` — use `PostHogDataMode.any`
- **Breaking:** make `beforeSend` and `logsConfig.beforeSend` callbacks synchronous — load what they need ahead of time instead of using `await`
- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` from applying to that event first, and stop dropping that event on Windows and Linux
- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()`, `captureException()`, `captureFeatureView()` or `captureFeatureInteraction()` from applying to that event first, and stop dropping that event on Windows and Linux
- Run a `beforeSend` callback that renames a screen or exception event once, and keep its `userProperties`
- Keep `userProperties` and `userPropertiesSetOnce` that a `beforeSend` callback sets on a screen or exception event on web
- Send an event as its original user when a `beforeSend` callback calls `reset()` or `identify()` on Windows and Linux, instead of dropping it, and on web, instead of sending it as the new user
- **Breaking:** remove `toMap()` from the config classes and `PostHogFeatureFlagResult.fromMap()` from the public API
- **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb`
- **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26
Expand Down
2 changes: 1 addition & 1 deletion posthog_flutter/MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ They serialized the internal platform-channel format and have no replacement. `t

### `beforeSend` callbacks are synchronous

`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback is a compile error. Load what it needs ahead of time and read it synchronously.
`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback, or one declared to return `FutureOr<PostHogEvent?>`, is a compile error. Load what it needs ahead of time and read it synchronously.

```dart
// Before
Expand Down
88 changes: 69 additions & 19 deletions posthog_flutter/lib/posthog_flutter_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
Map<String, Object>? userPropertiesSetOnce,
Map<String, Object?>? options,
}) {
return applyBeforeSend(
final distinctId =
_beforeSendCallbacks.isEmpty ? null : currentWebDistinctId();
final wasIdentified = distinctId != null && currentWebUserIdentified();
final processed = applyBeforeSend(
_beforeSendCallbacks,
PostHogEvent(
event: eventName,
Expand All @@ -58,6 +61,35 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
options: options == null ? null : {...options},
),
);
if (processed == null ||
distinctId == null ||
distinctId == currentWebDistinctId()) {
return processed;
}
// posthog-js stores an event's `$set` as the current user's person
// properties for flags, so after a reset() they would reach the next user.
// identify() of an anonymous user links the two, so they stay.
if (wasIdentified || !currentWebUserIdentified()) {
processed
..userProperties = null
..userPropertiesSetOnce = null
..properties = {...?processed.properties}
..properties!.remove(r'$set')
..properties!.remove(r'$set_once');
}
// posthog-js builds the event only after the callbacks, so one calling
// reset() or identify() would otherwise move the event to the new user.
// Event properties win over the stored distinct id. A callback changing
// consent under cookieless_mode swaps the id on purpose: neither the user
// who opted out nor the shared cookieless id may come back.
if (distinctId != r'$posthog_cookieless' &&
!(posthog?.has_opted_out_capturing() ?? true)) {
processed.properties = {
'distinct_id': distinctId,
...?processed.properties,
};
Comment thread
turnipdabeets marked this conversation as resolved.
Resolved
}
return processed;
}

/// posthog-js sends these calls' events without event properties, so
Expand Down Expand Up @@ -216,6 +248,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
return;
}

return _sendCapture(processedEvent);
}

Future<void> _sendCapture(PostHogEvent processedEvent) {
final extracted = CaptureUtils.extractUserProperties(
properties: processedEvent.properties,
userProperties: processedEvent.userProperties,
Expand Down Expand Up @@ -329,11 +365,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
}

if (processedEvent.event != PostHogEventName.screen) {
await capture(
eventName: processedEvent.event,
properties: processedEvent.properties?.cast<String, Object>(),
options: processedEvent.options,
);
await _sendCapture(processedEvent);
return;
}

Expand All @@ -342,16 +374,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
screenName;
_currentScreen = finalScreenName;
processedEvent.properties?.remove(PostHogPropertyName.screenName);
final extracted = CaptureUtils.extractUserProperties(
properties: processedEvent.properties,
userProperties: processedEvent.userProperties,
userPropertiesSetOnce: processedEvent.userPropertiesSetOnce,
);
final remaining = _withOptionProperties(
processedEvent.properties,
extracted.properties,
processedEvent.options,
PostHogEventName.screen,
);
final userProperties = extracted.userProperties;
final userPropertiesSetOnce = extracted.userPropertiesSetOnce;

return handleWebMethodCall(
MethodCall('screen', {
'screenName': finalScreenName,
if (remaining != null && remaining.isNotEmpty) 'properties': remaining,
if (userProperties != null)
'userProperties': PropertyNormalizer.normalize(userProperties),
Comment thread
turnipdabeets marked this conversation as resolved.
Resolved
if (userPropertiesSetOnce != null)
'userPropertiesSetOnce':
PropertyNormalizer.normalize(userPropertiesSetOnce),
}),
);
}
Expand Down Expand Up @@ -645,22 +689,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
}

if (processedEvent.event != PostHogEventName.exception) {
await capture(
eventName: processedEvent.event,
properties: processedEvent.properties?.cast<String, Object>(),
options: processedEvent.options,
);
await _sendCapture(processedEvent);
return;
}

final normalizedData = PropertyNormalizer.normalize(
_withOptionProperties(
processedEvent.properties?.cast<String, Object>(),
processedEvent.options,
PostHogEventName.exception,
) ??
<String, Object>{},
final extracted = CaptureUtils.extractUserProperties(
properties: processedEvent.properties?.cast<String, Object>(),
userProperties: processedEvent.userProperties,
userPropertiesSetOnce: processedEvent.userPropertiesSetOnce,
);
final userProperties = extracted.userProperties;
final userPropertiesSetOnce = extracted.userPropertiesSetOnce;
// posthog-js's captureException takes no capture options, but capture
// merges `$set` and `$set_once` from the event's properties.
final normalizedData = PropertyNormalizer.normalize({
...?_withOptionProperties(
extracted.properties,
processedEvent.options,
PostHogEventName.exception,
),
if (userProperties != null) r'$set': userProperties,
if (userPropertiesSetOnce != null) r'$set_once': userPropertiesSetOnce,
});

return await handleWebMethodCall(
MethodCall('captureException', {'properties': normalizedData}),
Expand Down
12 changes: 10 additions & 2 deletions posthog_flutter/lib/src/posthog_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -456,8 +456,16 @@ class PostHogConfig {
/// rest later.
///
/// **Note:**
/// - Callbacks are synchronous. Load anything they need (such as remote
/// config) ahead of time.
/// - Callbacks are synchronous and run on the calling isolate, so a slow one
/// blocks the UI. Load anything they need (such as remote config or feature
/// flags) ahead of time; a change made after the callback returns is not
/// sent.
/// - A callback that captures an event must not do so for that event too, or
/// it never finishes.
/// - On web, an event whose callback calls `reset()` stays on its user but
/// joins the next user's session and person processing, and its user
/// properties are dropped, because posthog-js builds the event after the
/// callbacks.
/// - If a callback throws, the event is dropped and later callbacks are not
/// called.
/// - If any callback returns `null`, the event is dropped and subsequent
Expand Down
33 changes: 12 additions & 21 deletions posthog_flutter/lib/src/posthog_flutter_desktop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -88,18 +88,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
return client;
}

DesktopPostHog? _clientForContinuation(
String op,
_ClientScope scope,
String distinctId,
) {
DesktopPostHog? _clientForContinuation(String op, _ClientScope scope) {
final client = _clientFor(op);
if (client == null) return null;
if (_clientScope != scope ||
client.optedOut ||
client.getDistinctId() != distinctId) {
printIfDebug('[PostHog] $op dropped: the project, the user or the '
'consent changed while beforeSend was running.');
if (_clientScope != scope || client.optedOut) {
printIfDebug('[PostHog] $op dropped: the project or the consent changed '
'while beforeSend was running.');
return null;
}
return client;
Expand Down Expand Up @@ -260,7 +254,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
if (!_hasName(eventName)) return;
final scope = _clientScope;
if (scope == null) return;
final distinctId = client.getDistinctId();

final prepared = _prepare(
client,
Expand All @@ -277,7 +270,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
return;
}

final current = _clientForContinuation('capture', scope, distinctId);
final current = _clientForContinuation('capture', scope);
if (current == null) return;
await _captureProcessed(current, processed, prepared);
});
Expand All @@ -300,7 +293,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
if (!_hasName(eventName)) return null;
final scope = _clientScope;
if (scope == null) return null;
final distinctId = client.getDistinctId();

final prepared = _prepare(
client,
Expand All @@ -317,7 +309,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
return null;
}

final current = _clientForContinuation('captureAi', scope, distinctId);
final current = _clientForContinuation('captureAi', scope);
if (current == null) return null;
return _captureProcessed(current, processed, prepared, ai: true);
});
Expand All @@ -334,7 +326,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
if (client.optedOut) return;
final scope = _clientScope;
if (scope == null) return;
final distinctId = client.getDistinctId();

final prepared = _prepare(
client,
Expand All @@ -346,14 +337,15 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
options: options,
);
if (prepared == null) return;
final sessionId = client.getSessionId();
final processed = _runBeforeSend(prepared.event);
if (processed == null) {
printIfDebug(
'[PostHog] Screen event dropped by beforeSend: $screenName');
return;
}

final current = _clientForContinuation('screen', scope, distinctId);
final current = _clientForContinuation('screen', scope);
if (current == null) return;
Comment thread
turnipdabeets marked this conversation as resolved.
Resolved

// A renamed event is no longer a screen view.
Expand All @@ -369,8 +361,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
return;
}

// Later events that set no `$screen_name` of their own carry this one.
if (finalScreenName is String) {
// Later events that set no `$screen_name` of their own carry this one,
// unless a callback's reset() started a session for the next user.
if (finalScreenName is String && current.getSessionId() == sessionId) {
current.registerForSession(
{PostHogPropertyName.screenName: finalScreenName});
}
Expand Down Expand Up @@ -604,7 +597,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
if (client.optedOut) return;
final scope = _clientScope;
if (scope == null) return;
final distinctId = client.getDistinctId();

final exceptionProps = DartExceptionProcessor.processException(
error: error,
Expand All @@ -630,8 +622,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
return;
}

final current =
_clientForContinuation('captureException', scope, distinctId);
final current = _clientForContinuation('captureException', scope);
if (current == null) return;
await _captureProcessed(current, processed, prepared);
});
Expand Down
45 changes: 30 additions & 15 deletions posthog_flutter/lib/src/posthog_flutter_web_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ extension PostHogExtension on PostHog {
external void unregister(JSAny key);
// ignore: non_constant_identifier_names
external JSAny? get_session_id();
// ignore: non_constant_identifier_names
external JSAny? get_property(JSAny name);
external JSFunction onFeatureFlags(JSFunction callback);
external void startSessionRecording();
external void stopSessionRecording();
Expand Down Expand Up @@ -296,6 +298,27 @@ Future<Map<String, Object?>> _reloadFeatureFlags(PostHog? ph) async {
}
}

/// The user posthog-js would send an event as right now.
String? currentWebDistinctId() =>
posthog?.get_distinct_id()?.dartify() as String?;

/// Whether posthog-js's current user is identified.
bool currentWebUserIdentified() =>
posthog?.get_property(r'$user_state'.toJS)?.dartify() == 'identified';

/// posthog-js capture options carrying `$set` and `$set_once`.
/// See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts
Map<String, Object> _personCaptureOptions(Map args) {
final userProperties = safeMapConversion(args['userProperties']);
final userPropertiesSetOnce = safeMapConversion(
args['userPropertiesSetOnce'],
);
return {
if (userProperties.isNotEmpty) '\$set': userProperties,
if (userPropertiesSetOnce.isNotEmpty) '\$set_once': userPropertiesSetOnce,
};
}

Future<dynamic> handleWebMethodCall(MethodCall call) async {
_maybeOverrideSDKInfo();

Expand Down Expand Up @@ -338,20 +361,7 @@ Future<dynamic> handleWebMethodCall(MethodCall call) async {
final properties = safeMapConversion(args['properties']);
properties.addAll(_getLocationProperties());
_addAppVersionProperties(properties);
final userProperties = safeMapConversion(args['userProperties']);
final userPropertiesSetOnce = safeMapConversion(
args['userPropertiesSetOnce'],
);

// Build options object for posthog-js capture with $set and $set_once
// See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts
final options = <String, Object>{};
if (userProperties.isNotEmpty) {
options['\$set'] = userProperties;
}
if (userPropertiesSetOnce.isNotEmpty) {
options['\$set_once'] = userPropertiesSetOnce;
}
final options = _personCaptureOptions(args);

posthog?.capture(
stringToJSAny(eventName),
Expand All @@ -366,7 +376,12 @@ Future<dynamic> handleWebMethodCall(MethodCall call) async {
properties.addAll(_getLocationProperties());
_addAppVersionProperties(properties);

posthog?.capture(stringToJSAny('\$screen'), mapToJSAny(properties), null);
final options = _personCaptureOptions(args);
posthog?.capture(
stringToJSAny('\$screen'),
mapToJSAny(properties),
options.isNotEmpty ? mapToJSAny(options) : null,
);
break;
case 'captureLog':
final body = args['body'] as String;
Expand Down
7 changes: 3 additions & 4 deletions posthog_flutter/lib/src/utils/call_order.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ class CallOrder {

/// Runs [hook] once every earlier call has been handed over, so it sees
/// the state the app left before capturing, then hands its result to
/// [send]. Later calls wait for [send] to finish, so it may itself capture
/// (a beforeSend that renames a `$screen` does).
/// [send]. Later calls wait for [send] to finish.
Future<void> event<E>(
FutureOr<E> Function() hook,
Future<void> Function(E event) send,
Expand All @@ -62,8 +61,8 @@ class CallOrder {
Future<void> Function(E event) send,
) async {
final timer = Timer(maxWait, () {
printIfDebug('[PostHog] beforeSend took longer than '
'${maxWait.inSeconds}s; later calls no longer wait for it.');
printIfDebug('[PostHog] An event took longer than '
'${maxWait.inSeconds}s to hand over; later calls no longer wait for it.');
turn.ahead.then((_) => turn.end());
});
try {
Expand Down
Loading
Loading