Skip to content

Identity & Attribution

B2B SaaSMobile apps

Stitch Amazon Cognito users to ad clicks and revenue

Wire Amazon Cognito PostConfirmation and PostAuthentication Lambda triggers to Apex using the immutable Cognito sub with a 1.5-second cap so logins never hit Cognito's 5-second limit.

Two Node.js 18+ Lambda triggers that never block sign-in.

6 min read15 min setupUpdated
Backend infrastructure engineer explaining a user-pool identity flow to a colleague using wooden building blocks on a sunlit studio bench.
Use Cognito's immutable sub across PostConfirmation and PostAuthentication triggers while staying safely under the 5-second timeout.

Cognito Lambda latency & trigger lab

Simulate Cognito's 5-second deadline and passive reconciliation

Switch between PostConfirmation and PostAuthentication, inject API latency, and verify how the 1.5-second abort keeps user sign-ins green.

Illustrative SaaS · Amazon Cognito User Pool (Node.js 18+)
$80,000
ApexApex · Live Playbook Simulator

Verified monthly revenue

$80,000

100% reconciled to commerce / CRM

Discovery channel credit

$46,400

+$33,600 vs last-click

Branded search / direct credit

$12,000

15% of closed revenue

Revenue credit by funnel role

Touchpoint roleLast-clickSelected modelDifference
First discovery (ads, posts, QR)$12,800$46,400+$33,600
Mid-funnel nurture (email, retargeting)$19,200$21,600+$2,400
Final branded search / direct$48,000$12,000-$36,000

Credit restored to discovery touches

$46,400

Full multi-touch path kept on one stitched customer timeline

  • Switch attribution models in one click without re-tagging links or re-importing orders.
  • Compare first-touch, linear, time-decay, and last-touch on the exact same revenue.

Stitched buyer journey

  1. Day 1Discovery touch capturedFirst touch

    Apex stores first-touch source on the visitor ID.

  2. Day 11Email click + identity stitchStitched

    Visitor signs up; anonymous session merges onto the customer record.

  3. Day 19Direct checkout closesVerified

    Revenue credits cleanly across the chosen attribution model.

The complete playbook

Step-by-step setup, worked math, and real limits.

Steps, technical details, and live pricing.

How it works without Apex

Attach two lightweight Node.js 18+ Lambda triggers to your Amazon Cognito User Pool: PostConfirmation sends user_signed_up with eventId keyed by the user's immutable Cognito sub, and PostAuthentication sends user_identified so existing pre-Apex users reconcile automatically on their next login. Both handlers await fetch with a 1.5-second timeout and catch all errors so Cognito's hard 5-second trigger limit never fails a sign-in.

How Apex does it for you

Apex maps Cognito's sub to internal_user_id, deduplicates repeated PostConfirmation retries via eventId, reconciles dormant users passively as they sign back in, and isolates staging user pools via x-apex-environment.

How to set this up in 5 steps

  1. Create a workspace server key and set Lambda env vars

    Generate an apex_sk_ key under Settings, then API keys in Apex. Store it as APEX_API_KEY on both Lambda functions, and set APEX_ENVIRONMENT to beta or dev on non-production user pools.

  2. Deploy the PostConfirmation Lambda for new sign-ups

    Read sub, email, name, and picture from event.request.userAttributes and POST user_signed_up with eventId set to signup- plus sub, awaiting fetch with AbortSignal.timeout(1500) and a catch fallback.

  3. Deploy the PostAuthentication Lambda for passive backfill

    On every sign-in, POST user_identified with email and userId set to sub using the same 1.5-second timeout and silent catch so pre-Apex users reconcile automatically on their next login.

  4. Keep await on fetch and return event cleanly

    Always await the fetch before returning event because Lambda freezes execution the moment the handler resolves, which would drop an unawaited request.

  5. Attach both triggers in your Cognito User Pool

    Under User pool properties, Lambda triggers, attach Post confirmation and Post authentication, then confirm a test account and verify the profile appears under Customers.

Two triggers and why both matter

Amazon Cognito assigns every user an immutable UUID called sub. Even if a customer later updates their email address or signs in through a federated provider, sub never changes, making it the cleanest possible internal_user_id for Apex.

Instead of trying to capture identity inside fragile browser callbacks after Cognito Hosted UI redirects, wire two small Node.js 18+ Lambda triggers documented in Connect Cognito:

  1. PostConfirmation fires when a brand-new user confirms their account and records user_signed_up with eventId: "signup-" + sub.
  2. PostAuthentication fires on every subsequent sign-in and sends user_identified so every existing customer created before you installed Apex reconciles automatically the next time they log in.
Two engineers discussing a wooden clipboard beside coiled braided cables on a sunlit timber workbench in a brick-and-glass workshop.
Keeping await on fetch with a strict 1.5-second AbortSignal guarantees events leave Lambda without risking Cognito's 5-second ceiling.

PostConfirmation and PostAuthentication code

Both functions use Node.js 18+ built-in fetch and AbortSignal.timeout with zero third-party npm packages to bundle:

// cognito-post-confirmation.js
export const handler = async (event) => {
  const { sub, email, name, picture } = event.request.userAttributes;
  await fetch("https://app.apex.inc/api/v1/events", {
    method: "POST",
    signal: AbortSignal.timeout(1500),
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.APEX_API_KEY,
      "x-apex-environment": process.env.APEX_ENVIRONMENT ?? "production",
    },
    body: JSON.stringify({
      events: [
        {
          type: "user_signed_up",
          eventId: `signup-${sub}`,
          email,
          data: { userId: sub, name, avatar_url: picture },
        },
      ],
    }),
  }).catch(() => {});
  return event;
};

For returning logins, attach a second trigger to Post authentication sending type: "user_identified" with email and data: { userId: sub } using the exact same timeout and error handler.

Two SaaS founders reviewing onboarding cohorts with printed index cards laid out on a sunlit maple table.
Passive PostAuthentication sync stitches legacy Cognito accounts automatically on their very next login with zero manual CSV work.

Protecting Cognito's 5-second limit

Cognito enforces a hard 5-second deadline on synchronous Lambda triggers, and any unhandled exception fails the user's sign-up or sign-in outright. Four habits make this integration bulletproof in production:

RuleWhat happens if you skip it
Cap fetch at 1,500 msA slow upstream socket can push Lambda past Cognito's 5-second wall and reject the login
Keep `await` on `fetch`Returning event early lets Lambda freeze the container before the HTTP request leaves
Swallow errors with `.catch(() => {})`A transient network failure turns into a broken login screen instead of a harmless skipped ping
Pass `APEX_ENVIRONMENT` on non-prod poolsQA sign-ups from staging user pools leak into production customer lists and ad conversions
Note on regional consent: Cognito does not pass visitor country or tracking consent automatically. If you store either as custom attributes (such as custom:country or custom:consent), pass them on the event payload. Otherwise, see Server Events consent rules for how missing-country sign-ups are handled. If you also need dormant users imported immediately, follow Backfill existing users.

What this costs on Apex

Live Apex pricing · Pay-as-you-go

Estimated Apex cost for SaaS product on Amazon Cognito with 3,000 monthly sign-ups and 22,000 sign-ins

$0 / month

Covered by monthly free allowances.

Apex meter / scheduleScenario volumeFree allowance / basisRateApex cost
Events
Cognito PostConfirmation and PostAuthentication server events (3,000 confirmed sign-ups plus 22,000 returning authentications per month)
25,000 / mo1M / month$5 per 100K events$0

Every Cognito user reconciles cleanly against your existing marketing snippet visits and Stripe invoices. History: 13 months no card, 3 years with card, 7 years once you've paid an invoice. Live pricing.

Third-party and campaign costs (not paid to Apex)

ExpenseTypical rangeNotes
AWS Lambda trigger invocationsUnder $1/month25,000 short Node.js invocations fit inside the standard AWS Lambda free tier

Your Cognito User Pool triggers invoke tiny Node.js handlers that stay near zero on AWS billing, and Apex meters only the delivered server events under standard Web Measurement.

Verify with your AI agent

Inspect incoming Cognito sign-ups and environment isolation via MCP

After attaching both Cognito Lambda triggers, ask your coding agent to confirm sign-up deduplication and verify your staging pool writes to beta.

1Add Apex to your editor

Install in Grok Build

Opens Grok Build and adds Apex. Nothing to configure.

2Tell your agent

Prompt for your AI editor

In my Apex workspace, call apex_recent_events to verify user_signed_up events carry eventId starting with signup- and userId matching Cognito sub, then call list_workspace_environments to check staging isolation.

The first time your agent calls Apex, it gives you a link to approve in the browser. There is no key to paste. In Grok Build you can also run /setup-apex.

See how editor setup works step by step

cognito-triggers · Grok BuildWaiting for approval
Agent
You

Set up Apex in this repo.

Set up Apex · 0 of 4
  • Signed in
  • Workspace named
  • Events arriving
  • Conversion picked
  • Stripe

Your move

Reconcile every Cognito sign-up without risking the 5-second trigger limit.

Use sub as your permanent customer key, backfill existing users passively on login, and keep staging pools out of live metrics.