DEV Community

John Builds
John Builds

Posted on

How to persist landing page attribution across OAuth redirects (30 lines of middleware)

Landing page attribution breaks the moment a user hits an OAuth flow.

Here's the scenario: you're running ads to multiple landing pages — one angle about speed, one about voice matching, one generic. All getting clicks. But by the time a visitor completes signup through Google OAuth or Twitter OAuth, the original URL params are gone. You see a new user in your database. You have no idea which LP or which copy variant sent them.

The fix: cookie before redirect

The solution is straightforward once you see it:

  1. On first page load, write the landing page path + A/B variant to a cookie — before any auth redirect happens
  2. On account creation (server-side), read that cookie back and persist both fields on the user record
  3. The cookie survives OAuth round-trips regardless of which auth method they use
// middleware.ts — runs on first page load
if (request.nextUrl.pathname.startsWith('/lp/')) {
  response.cookies.set('signup_landing_page', request.nextUrl.pathname, { maxAge: 3600 })
  response.cookies.set('ab_variant', getVariantFromCookie(request), { maxAge: 3600 })
}
Enter fullscreen mode Exit fullscreen mode
# users_controller.rb — on account creation
user.signup_landing_page = cookies[:signup_landing_page]
user.ab_variant = cookies[:ab_variant]
Enter fullscreen mode Exit fullscreen mode

Why not just use GA4?

GA4 session attribution and database-level user attribution tell different stories when auth redirects are involved. GA4 may correctly attribute the session to the landing page — but if you want to segment your actual converted users by which LP they came from (to measure LTV, churn rate, or feature adoption by cohort), you need it on the user record.

Now every new signup in XreplyAI carries signup_landing_page and ab_variant. First week of data is already changing where ad spend goes.

About 30 lines of middleware total. Worth the afternoon.


Built for XreplyAI — AI social media tool for solo founders.

Top comments (0)