Elixir
This library provides an Elixir HTTP client for PostHog. See the repository for more information.
Install with the wizard
Run this command in your project directory to add PostHog to your Elixir project. The wizard detects your framework, installs the SDK, and sets up your first events.
Or set it up manually by following the rest of this guide.
Installation
This library was built by the community but it's being maintained by the PostHog core team since v1.0.0. Thank you to Nick Kezhaya for building it originally. Thank you to Alex Martsinovich for contributing v2.0.0.
The package can be installed by adding posthog to your list of dependencies in mix.exs:
Configuration
You can see all the available configuration options in the PostHog.Config module.
Optionally, you might want to enable the Plug integration to attach request metadata and tracing context in Plug-based applications including Phoenix. You still need to capture events explicitly with PostHog.capture/2 or PostHog.capture/3.
Development/Test mode
For a test environment, you can pass in test_mode: true value to the config. This causes events to be dropped instead of sent to PostHog.
Identifying users
Identifying users is required. Backend events need a
distinct_idthat matches the ID your frontend uses when callingposthog.identify(). Without this, backend events are orphaned — they can't be linked to frontend event captures, session replays, LLM traces, or error tracking.See our guide on identifying users for how to set this up.
Capturing events
To capture an event, use PostHog.capture/2:
Tip: We recommend using a
[object] [verb]format for your event names, where[object]is the entity that the behavior relates to, and[verb]is the behavior itself. For example,project created,user signed up, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
Context
Carrying distinct_id around all the time might not be the most convenient approach, so PostHog lets you store it and other properties in a context.
The context is stored in the Logger metadata and PostHog automatically attaches these properties to any events you capture with PostHog.capture/2, as long as they happen in the same process.
You can also scope the context to a specific event name:
Batching events
Events are automatically batched and sent to PostHog via a background job.
Special events
PostHog.capture/2 is very powerful and enables you to send events that have special meaning.
In other libraries you'll usually find helpers for these special events, but they must be explicitly sent in Elixir.
For example:
Create alias
Group analytics
Request context
For Phoenix or Plug apps, add PostHog.Integrations.Plug before your router to attach request metadata and PostHog tracing headers to events captured during the request.
For plain Plug routers, add it before :match and :dispatch:
The plug adds request metadata such as $current_url, $host, $pathname, $request_method, $user_agent, and $ip. It also reads X-PostHog-Distinct-Id and X-PostHog-Session-Id as analytics context so backend events and errors can be linked to frontend users and sessions.
If you're using PostHog JS on the frontend, configure tracing_headers for your Phoenix or Plug backend hostname so browser requests include these headers.
Tracing headers are client-controlled analytics context, not authentication or authorization. Pass an authenticated distinct_id explicitly for security-sensitive server-side decisions.
Trace context
To link application spans to people and sessions, install the optional opentelemetry dependency and add this entry before the export processors in your existing OpenTelemetry :processors list:
Use your named PostHog supervisor in place of PostHog if needed. Keep your existing provider, exporter, and sampler. The processor supports OpenTelemetry SDK 1.7.0 or later. It adds missing sessionId and posthogDistinctId attributes from the current process's PostHog context when spans start. Existing canonical attributes take precedence.
The PostHog plug sets context for child spans. Phoenix with Cowboy starts its request span before the endpoint plugs run. To also link that earlier span, change your existing Cowboy instrumentation setup to capture only the two PostHog headers:
Configure instrumentation once, before the endpoint starts. Keep other existing options in the same configuration. Do not capture all request headers. Configure tracing_headers in the browser SDK so it sends these headers to your selected backend hostname.
Cowboy supplies the captured headers as initial span attributes. The processor sanitizes them and uses them only when no process identity or explicit canonical span attribute is present. Without header capture, an earlier request span stays unchanged. Missing IDs stay absent.
This request path was tested with Phoenix 1.8.15, opentelemetry_phoenix 2.0.1, and opentelemetry_cowboy 1.0.0. The same setup has not been verified with Bandit. HTTP request context does not transfer into LiveView processes automatically.
Context is process-local and ends when the request process exits. Clear it before you reuse the same process for unrelated work. Tasks and other processes need their own explicit context. Spans keep the IDs captured when they start. No trace provider, exporter, session, or recording is created by this bridge.
Feature flags
PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.
There are two steps to implement feature flags in Elixir:
Step 1: Evaluate flags once
Call PostHog.FeatureFlags.evaluate_flags/1 once for the user, then read values from the returned snapshot.
Boolean feature flags
Multivariate feature flags
PostHog.FeatureFlags.Evaluations.get_flag/2 returns the variant string for multivariate flags, true for enabled boolean flags, false for disabled flags, and nil when the flag wasn't returned by the evaluation.
Note:
PostHog.FeatureFlags.check/2,PostHog.FeatureFlags.check!/2,PostHog.FeatureFlags.get_feature_flag_result/2, andPostHog.FeatureFlags.get_feature_flag_result!/2still work during the migration period, but they're deprecated. Preferevaluate_flags/1for new code.
Step 2: Include feature flag information when capturing events
If you want use your feature flag to breakdown or filter events in your insights, you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event.
Note: This step is only required for events captured using our server-side SDKs or API.
There are two methods you can use to include feature flag information in your events:
Method 1: Put the evaluated flags snapshot in context
Put the same snapshot object that you used for branching into context. Subsequent captures from the same process attach the exact flag values from that evaluation and don't make another /flags request.
By default, this attaches every flag in the snapshot using $feature/<flag-key> properties and $active_feature_flags.
To reduce event property bloat, put a filtered snapshot in context:
only_accessed/1 is order-dependent. If you call it before accessing any flags with enabled?/2 or get_flag/2, no feature flag properties are attached.
Method 2: Include the $feature/feature_flag_name property manually
In the event properties, include $feature/feature_flag_name: variant_key:
Evaluating only specific flags
By default, evaluate_flags/1 evaluates every flag for the user. If you only need a few flags, pass flag_keys to request only those flags:
Sending $feature_flag_called events
Capturing $feature_flag_called events enables PostHog to know when a flag was accessed by a user and provide analytics and insights on the flag. With evaluate_flags/1, the SDK sends this event when you call PostHog.FeatureFlags.Evaluations.enabled?/2 or PostHog.FeatureFlags.Evaluations.get_flag/2 for a flag.
PostHog.FeatureFlags.Evaluations.get_flag_payload/2 doesn't send $feature_flag_called events.
Local feature flag evaluation
Local evaluation is available in version 2.15.0 and later. Follow the server-side local evaluation guide to find your secure key and see how to pass the person properties, groups, and group properties that your flag conditions require.
Store the secure key in a server-side environment variable. Don't expose it to client-side applications:
When secret_key is set, the SDK fetches definitions when it starts and polls for updates every 30 seconds. PostHog.FeatureFlags.evaluate_flags/1 evaluates each flag locally first. If a flag can't be evaluated locally, the SDK makes one /flags request to resolve the remaining flags. Set only_evaluate_locally: true in the evaluation map to prevent this remote fallback. The SDK then omits unresolved flags from the snapshot.
Use these configuration options to control local evaluation:
| Option | Default | Purpose |
|---|---|---|
enable_local_evaluation | true | Starts local evaluation when secret_key is set. |
feature_flags_poll_interval_ms | 30_000 | Sets the interval between definition refreshes. |
flag_definition_request_timeout_ms | 10_000 | Sets the timeout for each definition request. |
flag_definition_cache_provider_timeout_ms | 5_000 | Sets the timeout for each shared cache provider callback. |
For multiple server instances, you can implement PostHog.FeatureFlags.FlagDefinitionCacheProvider and set flag_definition_cache_provider: {module, state}. This optional provider shares definitions and coordinates which instance polls PostHog. See local evaluation in distributed environments for the callback contract and configuration.
Error tracking
Error tracking is enabled by default. It will automatically captures exceptions thrown by the application.
As a matter of fact, since this is built on top of Elixir's Logger module, it automatically captures any Logger.error calls.
You can always disable it by setting enable_error_tracking to false:
Transactional emails
From version 2.20.0, PostHog.Emails sends transactional emails and reads their status. See send transactional emails with Elixir for setup and examples.
| Option | Default | Description |
|---|---|---|
secret_key | nil | A project secret API key (phs_). Sending needs the transactional_email:write scope. Reading a status needs transactional_email:read or transactional_email:write. The same key turns on local feature flag evaluation. |
app_host | nil | Your PostHog app URL, such as https://posthog.example.com. Without it, a PostHog Cloud api_host maps to its region's app host, https://us.posthog.com or https://eu.posthog.com. Set it when api_host is a reverse proxy or a self-hosted PostHog. Otherwise each call returns the code missing_app_host, so the secret key never reaches the proxy. |
email_request_timeout_ms | 15_000 | The timeout for each email request. |
email_request_max_retries | 2 | How many times the SDK retries an email request. Set it to 0 when a job runner already retries the send. Pass max_retries to one send/2 to change it for that send. |
migrated_from | nil | The email provider you moved from, such as "resend". The SDK sends it with every email request in the X-PostHog-Migrated-From header. |
See PostHog.Emails on HexDocs for the module docs.
PostHog.Emails
Sends one transactional email, from a template made in PostHog or from content that your code rendered, and reads its status.
Each call blocks the calling process until it finishes. The SDK keeps no email queue. Each request times out after email_request_timeout_ms. The SDK retries network errors, rate limits, an idempotency key that is still in flight, and a 503, with the same idempotency key. It waits about 1 second, then 2 seconds, or as long as the server's Retry-After asks. When Retry-After asks for more than 30 seconds, it returns the error at once with retry_after_ms set. It never retries quota_limited or upload_quota_exceeded. Attachment uploads also retry storage answers of 429, 500, 502, 503, and 504, and each upload gets the request timeout plus 10 seconds for each MB of the file.
From version 2.23.2, the SDK sends to /api/messaging/. A self-hosted PostHog from before 2026-11-18 answers those requests with a 404.
Functions:
| Name | Description |
|---|---|
send/2 | Queues one email, from a template made in PostHog or from content that your code rendered. |
get/2 | Reads the status of an email that send/2 queued. |
PostHog.Emails.send/2
Queues one email. Pass the options as a keyword list or a map. Pass template_id to send a template made in PostHog (the template form), or template_key to send content that your code rendered (the code form). Never pass both. An option of the other form returns invalid_form before any request.
An option set to nil counts as left out. An empty reply_to, cc, bcc, or attachments list also counts as left out. A PostHog version that does not accept a field yet refuses the send with an error whose field names it. The SDK never drops a field to send the rest.
Parameters:
| Name | Description |
|---|---|
name | PostHog.supervisor_name(). The PostHog instance to send through. Added in 2.20.0. Default: PostHog. |
to | String.t(). One recipient email address. Added in 2.20.0. Required. |
distinct_id | String.t(). The recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address. The SDK never takes it from PostHog.set_context/2. Added in 2.20.0. Default: nil. |
idempotency_key | String.t(). 1 to 255 visible ASCII characters, with no spaces. A key that PostHog already accepted queues nothing and returns the first send's result. Template and code sends share one set of keys, so a key used for a different email returns idempotency_key_reused. Added in 2.20.0. Default: a UUID for the call. |
max_retries | non_neg_integer(). The retries for this send. 0 turns retries off. Added in 2.20.0. Default: the config's email_request_max_retries. |
template_id | String.t(). Template form. The UUID of a template made transactional in PostHog. Added in 2.20.0. Required in the template form. |
template_data | map(). Template form. The values for the template's {{ variables.* }} placeholders. It must encode as JSON. Added in 2.20.0. Default: %{}. |
template_key | String.t(). Code form. Names the email, such as "password-reset", so its metrics, logs, and status group under it in PostHog. Letters, digits, -, and _, at most 400 characters. Added in 2.20.0. Required in the code form. |
subject | String.t(). Code form. The subject line. Added in 2.20.0. Required in the code form. |
html | String.t(). Code form. The HTML body. To send a React email, render it to HTML in your app first. The SDK does no rendering. Added in 2.20.0. Give html, text, or both. |
text | String.t(). Code form. The plain-text body. Without it, PostHog derives the text from html. Added in 2.20.0. Give html, text, or both. |
from | String.t(). Code form. A verified sender, such as "Acme <security@example.com>". Added in 2.20.0. Default: the project's default sender. |
reply_to | String.t() \| [String.t()]. Code form. One address or a list of addresses. Added in 2.20.0. Default: nil. |
cc | String.t() \| [String.t()]. Code form. One address or a list of at most 10 bare addresses, such as "finance@example.com", that get a visible copy. Added in 2.22.0. Default: nil. |
bcc | String.t() \| [String.t()]. Code form. One address or a list of at most 10 bare addresses that get a hidden copy. Added in 2.22.0. Default: nil. |
attachments | [PostHog.Emails.attachment()]. Code form. The files to attach. See PostHog.Emails.attachment(). Added in 2.22.0. Default: nil. |
sensitive | boolean(). Code form. Set it to true when the email carries login links, reset tokens, or codes. A sensitive email keeps its links unchanged unless tracking turns clicks on, leaves its subject off engagement events, and keeps its content out of logs. The SDK sends it only when you set it. Added in 2.21.0. Default: the setting of the template made in PostHog whose key matches template_key, or true when no template matches. |
tracking | PostHog.Emails.tracking(). Code form. What PostHog tracks for the email. See PostHog.Emails.tracking(). The SDK sends it only when you set it. Added in 2.21.0. Default: nil. |
capture_engagement | boolean(). Code form. Deprecated from 2.21.0: use tracking: %{engagement: false}. Whether PostHog captures the email's engagement events. A send cannot set both. Added in 2.20.0. Default: nil. |
Returns:
| Type | Description |
|---|---|
{:ok, PostHog.Emails.SendResult.t()} | PostHog queued the email. This does not mean that it was delivered. Read the delivery with get/2. |
{:error, PostHog.Emails.Error.t()} | PostHog did not queue the email, or the SDK could not tell whether it did. The function never raises. |
Examples:
PostHog.Emails.get/2
Reads the status of an email that send/2 queued, for 30 days after the send. A key with only transactional_email:read can read statuses. The SDK retries a status read in the same way as a send.
Parameters:
| Name | Description |
|---|---|
name | PostHog.supervisor_name(). The PostHog instance to read through. Added in 2.20.0. Default: PostHog. |
message_id | String.t(). The id of the SendResult that send/2 returned. It must be a UUID, or the call returns invalid_message_id. Added in 2.20.0. Required. |
Returns:
| Type | Description |
|---|---|
{:ok, PostHog.Emails.Status.t()} | The email's latest status. |
{:error, PostHog.Emails.Error.t()} | PostHog did not return a status. The code is not_found for an unknown ID, for an email older than 30 days, or for a few seconds after the send. |
Examples:
PostHog.Emails.attachment()
A file for the attachments option of send/2. Added in 2.22.0. The keys are atoms. A string key, or a key such as :path, returns invalid_attachment. PostHog cannot fetch a file from a path or a URL.
An email carries at most 10 files and 40 MB after Base64 encoding, about 29 MB of files. The SDK checks both limits before any request and returns too_many_attachments or message_too_large. Without text, PostHog derives the text from html and counts it too.
The SDK hashes each file with SHA-256 and uploads only the files that PostHog does not have yet. It uploads them straight to PostHog's file storage over HTTPS, without the secret key and without your api_client_module. Your app must reach the storage host directly, because an upload ignores proxies and Req.default_options. When an upload fails, the SDK sends no email.
Attributes:
| Name | Type | Description |
|---|---|---|
filename | String.t() | The file name. It cannot be blank. Required. |
content | binary() | The file's raw bytes, such as File.read!/1 returns. Do not pass Base64. It cannot be empty. Required. |
content_type | String.t() | The MIME type, such as "application/pdf". Default: nil. |
content_id | String.t() | Shows the file inline. With content_id: "logo", reference it in html as <img src="cid:logo">. Default: nil. |
Examples:
PostHog.Emails.tracking()
What PostHog tracks for an email sent with template_key. Added in 2.21.0. When you leave tracking out, PostHog counts opens and captures engagement events, and tracks clicks only when the email is not sensitive. true turns on opens, clicks, and engagement events, even for a sensitive email. false turns them all off: the email has no open pixel and no rewritten links, and PostHog captures no engagement events. A map sets each one:
Attributes:
| Name | Type | Description |
|---|---|---|
opens | boolean() | Counts opens with an open pixel. Default: true. |
clicks | boolean() | Tracks clicks by rewriting links. Click tracking needs open tracking. Turn it on for a sensitive email only when its links are safe to rewrite. Default: true unless the email is sensitive. |
engagement | boolean() | Captures the email's engagement events. A project whose admin turned engagement capture off captures nothing. Default: true. |
Examples:
PostHog.Emails.SendResult
The queued email. A result means that PostHog queued the email, not that it was delivered.
Attributes:
| Name | Type | Description |
|---|---|---|
id | String.t() | The queued email's message ID. Pass it to get/2. |
replayed | boolean() | true when PostHog already accepted this idempotency key and returned the first send's result. Default: false. |
warnings | [PostHog.Emails.Warning.t()] | The warnings that PostHog returned with the email. send/2 also logs each one. Default: []. |
PostHog.Emails.Warning
A warning that PostHog returned with a queued email.
Attributes:
| Name | Type | Description |
|---|---|---|
code | String.t() | The warning code. |
message | String.t() | What PostHog warns about. |
fix | String.t() \| nil | How to fix it, when PostHog said. |
PostHog.Emails.Status
What happened to an email that send/2 queued.
Attributes:
| Name | Type | Description |
|---|---|---|
id | String.t() | The message ID that send/2 returned. |
status | String.t() | "queued" (the email waits to go out), "sent" (PostHog gave it to the email provider), "failed" (it was not sent, and reason says why), "delivered" (the recipient's mail server accepted it), "bounced", or "complained" (the recipient's mail provider reported it after delivery). A later PostHog version can return a value that this list does not have yet. |
created_at | DateTime.t() | When PostHog queued the email. |
status_at | DateTime.t() | When the email reached its current status. |
reason | String.t() \| nil | Why a failed email was not sent, such as "provider_error" or "recipient_suppressed", or the bounce type of a bounced email: "hard", "soft", or "unknown". nil otherwise. |
PostHog.Emails.Error
PostHog did not queue the email or return its status, or the SDK could not tell whether it did. Every failure of send/2 and get/2 returns {:error, %PostHog.Emails.Error{}}. Branch on code, or on name for a coarse category. The message never contains the secret key or the request body.
Attributes:
| Name | Type | Description |
|---|---|---|
name | name() | A coarse category of the failure. See the names below. |
code | String.t() | PostHog's stable error code, or one of the SDK codes below. |
message | String.t() | A human-readable message. |
status_code | pos_integer() \| nil | The HTTP status when PostHog answered. For attachment_upload_failed, the storage's status. |
why | String.t() \| nil | Why PostHog refused the request, when it said. |
fix | String.t() \| nil | How to fix it, when PostHog or the SDK said. |
docs_url | String.t() \| nil | A link to the docs for the error, when PostHog sent one. |
field | String.t() \| nil | The option that the error is about, such as "to". |
retry_after_ms | non_neg_integer() \| nil | How long PostHog, or the storage, asked the client to wait before it sends again. |
The name comes from the HTTP status and, for some statuses, the code:
| Name | When |
|---|---|
:validation_error | A 400, a 422 other than idempotency_key_reused, a 409 with template_outdated, an invalid_* code, too_many_attachments, or message_too_large. |
:missing_api_key | A 401, or missing_secret_key. |
:invalid_permission | A 403. |
:not_found | A 404. |
:concurrent_idempotent_requests | A 409 other than template_outdated. |
:invalid_idempotent_request | A 422 with idempotency_key_reused. |
:rate_limit_exceeded | A 429 other than quota_limited. |
:monthly_quota_exceeded | A 429 with quota_limited. |
:service_unavailable | A 503, or network_error. |
:application_error | Anything else, and always attachment_upload_failed. |
The SDK returns these codes itself:
| Code | When |
|---|---|
missing_secret_key | The config has no secret_key. No request is made. |
missing_app_host | api_host is not PostHog Cloud and the config has no app_host. No request is made. |
client_disabled | The PostHog instance is not running or has no api_key. No request is made. |
client_closed | The PostHog instance stopped during the call. The call made no further request, and a send sent no email. |
network_error | A request failed or timed out without an answer. |
api_error | PostHog answered without an error code, answered a send without a message ID or a status read without a status, or named an upload URL that is not HTTPS. |
unexpected_error | The SDK failed in an unexpected way. |
too_many_attachments | More than 10 files. No request is made. |
message_too_large | More than 40 MB after Base64 encoding. No request is made. |
attachment_upload_failed | An upload to PostHog's file storage failed, so no email was sent. message has the storage's answer. |
invalid_form | The options are not a keyword list or a map, the send has both or neither of template_id and template_key, a code send has no subject or no body, an option belongs to the other form, or an option has the wrong type. |
invalid_recipient | to is not one nonblank string. |
invalid_distinct_id | distinct_id is not a nonempty string. |
invalid_template_id | template_id is not a UUID. |
invalid_template_data | template_data is not a map, or does not encode as JSON. |
invalid_template_key | template_key has a character other than letters, digits, -, and _, or more than 400 characters. |
invalid_idempotency_key | idempotency_key is not 1 to 255 visible ASCII characters. |
invalid_max_retries | max_retries is not a nonnegative integer. |
invalid_attachment | An attachment has a missing, empty, or unknown key, or a value of the wrong type. |
invalid_message_id | The message_id of get/2 is not a UUID. |
Every invalid_* code returns before any request, and field names the option. For the codes that PostHog returns, such as quota_limited, recipient_suppressed, and idempotency_key_reused, and for which ones to retry, see what to retry.
Advanced configuration
By default, PostHog starts its own supervision tree and attaches a logger handler.
In certain cases, you might want to run this supervision tree yourself. You can do this by disabling the default supervisor and adding PostHog.Supervisor to your application tree with its own configuration:
Multiple instances
In even more advanced cases, you might want to interact with more than one PostHog project. In this case, you can run multiple PostHog supervision trees, one of which can be the default one:
Then, each function in the PostHog module accepts an optional first argument with the name of the PostHog supervisor tree that will process the capture:
Thanks
The library is maintained by the PostHog team since February 2025. Thanks to nkezhaya for contributing v0.1.0. Thanks to martosaur for contributing v2.0.0.





