Ben Senescu ad3b732f60 hosted: add product analytics (#83)
* track core product analytics flows

Track auth, search, export, audit, and credit-consumption events with canonical route IDs so PostHog funnels and usage dashboards stay low-noise and privacy-safe.

* fix: keep auth actions usable after session loss

* refactor: simplify analytics and auth helpers

- Replace isRecord/getActiveOrganizationId type guards with simple cast
- Refactor getAnalyticsRouteContext from if/return chain to route tables
- Replace toVerificationIssueType switch with zod enum
- Merge duplicate credits_consume events into single event per API call
- Merge two PostHogBootstrap useEffects into one

* refactor: add projectId to middleware context to reduce boilerplate

The requireProjectContext middleware now includes projectId directly,
eliminating repeated manual construction of BillingCustomerContext
objects across all server function handlers.

* remove unused BILLING_* env var fallbacks from cost profile script

* remove before_send event enrichment to preserve native PostHog URL tracking

The before_send hook was stripping $pathname, $current_url, $referrer and
other URL properties, which breaks PostHog web analytics dashboards, paths
analysis, session replay, and attribution. The route_id/route_group injection
it provided is unnecessary since PostHog already captures $pathname natively.

* remove route mapping layer, pass raw redirect paths to analytics events

The route ID registry (STATIC_ROUTES, PROJECT_ROUTES, getAnalyticsRouteContext,
getRedirectRouteId) duplicated what PostHog already captures via $pathname.
Replace redirect_route_id with redirect_to containing the raw path, and remove
~80 lines of route mapping infrastructure.

* clean up analytics events: drop redundant submit events and derived properties

- Remove search_submit events for keywords, domain overview, and backlinks
  (the search_complete events capture the meaningful outcome data)
- Remove target_type from backlinks events (derived 1:1 from search_scope)
- Remove result_limit from keyword research (requested limit, not useful
  alongside actual result_count)
- Remove export_format from data:export events (always "csv")

* refactor: inline wrappers, colocate helpers, deduplicate getActiveOrganizationId

- Inline toVerificationIssueType into verify-email.tsx (single-use wrapper)
- Move mapDataforseoPathToCreditFeature into dataforseoClient.ts (only consumer)
- Extract shared getActiveOrganizationId into lib/auth-session.ts (was
  duplicated in __root.tsx and middleware/ensure-user/hosted.ts)
- Rename shared/analytics.ts → shared/internal-user.ts (only email helpers
  remain after removing route mapping, verification, and dataforseo helpers)

* remove internal user tracking and email domain properties

Drop is_internal_user super property, email_domain person property, and all
supporting code (shared/internal-user.ts, getEmailDomain, isInternalUserEmail).
Simplifies initPostHog and identifyAnalyticsUser signatures.

* remove backlinks:search_complete effect-based tracking

The reactive useEffect + useRef dedup pattern added ~30 lines of plumbing
inside a data hook for a single analytics event. Not worth the complexity.

* simplify: replace manual type guards with zod, deduplicate posthog and sign-out helpers

- Replace hand-rolled typeof checks in getActiveOrganizationId and
  isAuthenticatedServerFunctionContext with zod safeParse
- Extract withPostHogClient helper to deduplicate client posthog wrapper
- Move apiKey guard into getServerPostHogClient factory
- Extract signOutAndRedirect to avoid duplicated sign-out logic
- Drop derivable has_results from analytics events
- Remove unnecessary path normalization in mapDataforseoPathToCreditFeature

* fix: strip email from pageview URLs, restore sign-out guard, harden server posthog, fix path mapper

- Sanitize $current_url on pageviews to remove email query param (PII)
- Restore onSuccess for sign-out redirect to avoid bounce-back on failure
- Swallow shutdown() errors so PostHog outages can't fail billed work
- Rewrite mapDataforseoPathToCreditFeature to match real API path structure
  (path[1] = module, path[3] = endpoint) instead of scanning all segments

* simplify: remove redundant refs in verify-email, infer middleware context type

- Remove unnecessary useRef guards in verify-email effects (deps already prevent re-firing)
- Use z.ZodType<EnsuredUserContext> annotation to infer return type instead of casting
- Add comment explaining one-shot PostHog client on Workers

* fix: reset PostHog identity on sign-out before redirect

* fix: require POSTHOG_HOST env var instead of defaulting to us.i.posthog.com

* fix: annotate url as unknown to satisfy no-unsafe-assignment

* format
2026-04-08 14:09:02 -04:00
2026-02-27 14:09:33 -05:00
2026-04-08 14:09:01 -04:00
2026-03-30 14:11:01 -04:00
2026-04-08 14:09:02 -04:00
2026-03-19 19:24:34 -04:00
2026-03-11 23:23:47 -04:00
2026-03-19 19:24:34 -04:00
2026-02-27 14:09:33 -05:00
2026-02-27 14:09:33 -05:00
2026-03-19 19:24:34 -04:00
2026-02-27 14:14:23 -05:00
2026-03-11 23:23:47 -04:00

OpenSEO

OpenSEO is an SEO tool for the people. If tools like Semrush or Ahrefs are too expensive or bloated, OpenSEO is a pay-as-you-go alternative that you actually control.

OpenSEO demo (placeholder)

Table of Contents

Why Use This

  • Open source and self-hostable.
  • No subscriptions.
  • Focused workflows instead of a giant, complex SEO suite.
  • AI-native: use your own tools like Claude Code / Cowork for more powerful AI features than other platforms provide.

Main SEO Workflows

  • Keyword research
    • Find topics worth targeting, estimate demand, and prioritize what to write next.
  • Domain insights
    • Understand where your domain is gaining or losing visibility so you can focus on the pages that move revenue.
  • Backlinks
    • See who links to your site, which pages attract links, and where links are newly won or lost.
  • Site Audits
    • Catch technical issues early so your site is easier for search engines to crawl and rank.

Roadmap

Top priorities:

  • Rank tracking
  • AI content workflows

If something important is missing, please join the Discord or email me at ben@everyapp.dev and request it.

Community

Email me: ben@everyapp.dev Join Discord to chat: Discord

Follow along for updates:

Pricing / Costs

OpenSEO is totally free to use. It works by using DataForSEO's APIs, which is a paid third-party service unaffiliated with OpenSEO.

There are two separate things:

  1. OpenSEO app cost: $0, you host it yourself.
  2. DataForSEO API: pay-as-you-go based on usage.

For cost estimates, see DataForSEO API Cost Reference.

DataForSEO API Key Setup

OpenSEO uses DataForSEO to fetch SEO data. You need an API key to connect OpenSEO to the service.

Backlinks requires one more step beyond the API key: you also need DataForSEO Backlinks enabled on your account (trial or paid subscription), then confirm access from the Backlinks page in OpenSEO.

  1. Go to DataForSEO API Access.
  2. Request API credentials by email (API key by email or API password by email).
  3. Use your DataForSEO login + API password, then base64 encode login:password:
printf '%s' 'YOUR_LOGIN:YOUR_PASSWORD' | base64
  1. Set this as DATAFORSEO_API_KEY in your environment file:
  • Docker self-hosting: .env
  • Cloudflare: Set it in the workers UI
  • Local development: .env.local

Self-hosting

OpenSEO supports two self-hosting paths:

  • Docker for your homelab or local use (Recommended).
  • Cloudflare for use across multiple devices or for your team.

Docker

Docker is recommended for getting started. It's super easy to get up and running once you install Docker.

Cloudflare

If you love OpenSEO and want to use it across multiple devices or with your team, you can host it on Cloudflare which we'll be a SaaS-like experience. Also, this will have automatic database backups and other nice convenience features. It's just a bit more effort to get started if you're unfamiliar with Cloudflare.

Docker Self Hosting

Prerequisites:

Quickstart:

  1. cp .env.example .env
  2. Set DATAFORSEO_API_KEY in .env
  3. docker compose up -d
  4. Open http://localhost:<PORT> (default 3001)

By default, compose.yaml pulls the published image from GHCR:

  • ghcr.io/every-app/open-seo:latest

To update to the newest published image, pull first and then restart:

docker compose pull
docker compose up -d

Or use a single command:

docker compose up -d --pull always

Use a pinned version tag in .env if preferred:

OPEN_SEO_IMAGE=ghcr.io/every-app/open-seo:v1.2.3

For more info, see docs/SELF_HOSTING_DOCKER.md.

Cloudflare Self-Hosting

Deploy the Worker

Clicking this button opens a page to deploy OpenSEO in your Cloudflare account. If you do not have an account yet, it will take you to account creation first (OpenSEO works great on the free plan).

Reference these docs while deploying since the Cloudflare UI doesn't indicate what steps you need to take: docs/SELF_HOSTING_CLOUDFLARE.md.

Deploy to Cloudflare

Local Development

Prerequisites

  • Node.js 20+
  • pnpm
  • A DataForSEO account/API credentials

Local Development Workflow

pnpm install

# Run once per fresh local DB
pnpm run db:migrate:local

Configure .env.local:

  1. cp .env.example .env.local

  2. Add DATAFORSEO_API_KEY as a base64-encoded login:password value:

    printf '%s' 'YOUR_LOGIN:YOUR_PASSWORD' | base64

Run Locally:

# Option 1
pnpm run dev

# Option 2 (Recommended)
# This log file makes it easier for your coding agent to debug.
mkdir .logs
touch .logs/dev-server.log

# This command uses portless, which is great for worktrees. It also pipes logs to that fixed file, which is helpful for agent debugging output.
pnpm dev:agents

pnpm dev:agents runs through portless at http://open-seo.localhost:1355 by default.

When using a git worktree, portless prefixes the branch name, for example http://feature-name.open-seo.localhost:1355.

Database Commands

Generate migration:

pnpm run db:generate

Migrate local DB:

pnpm run db:migrate:local

Auth modes

  • AUTH_MODE=cloudflare_access (default): validates Cloudflare Access JWTs (cf-access-jwt-assertion) using TEAM_DOMAIN + POLICY_AUD.
  • AUTH_MODE=local_noauth: local trusted mode, no auth check, injects admin@localhost.
  • AUTH_MODE=hosted: Better Auth-backed email/password mode. Requires Better Auth schema generation plus BETTER_AUTH_SECRET and BETTER_AUTH_URL.

Local scripts (pnpm dev and pnpm dev:agents) set AUTH_MODE=local_noauth automatically. Use AUTH_MODE=cloudflare_access pnpm dev when you specifically want to test Access validation locally.

For Cloudflare deployments, ensure Cloudflare Access is enabled on your Worker route/domain and provide TEAM_DOMAIN + POLICY_AUD in environment variables.

Contributing

Contributions are very welcome.

  • Open an issue for bugs, UX friction, or feature requests.
  • Open a PR if you want to implement a feature directly.
  • Community-driven improvements are prioritized, and high-quality PRs are encouraged.

If you want to contribute but are unsure where to start, open an issue and describe what you want to build.

SEO API Cost Reference

Use this section to estimate DataForSEO spend per request type. OpenSEO itself remains free; these are API usage costs only.

As of February 26, 2026, DataForSEOs public docs/pricing pages say:

  • New accounts include $1 free credit to test the API.
  • The minimum top-up/payment is $50.

That means you can try OpenSEO for free with the starter credit, then decide if/when to top up.

Pricing sources

1) Site audit

  • No paid API calls in the current implementation.
  • Current billed cost pattern (from account usage logs):
    • 0.02 + (0.0001 x returned_keywords) USD
  • Default app setting: 150 results per search ($0.035 each).
  • Available result tiers:
    • 150 results = $0.035
    • 300 results = $0.05
    • 500 results = $0.07

3) Domain overview

  • Standard domain overview request (with top 200 ranked keywords): $0.0401 per domain.
  • General formula if needed:
    • 0.0201 + (0.0001 x ranked_keywords_returned) USD
  • Backlinks search costs about $0.06 for a domain or $0.04 for a page.
  • Opening extra tabs like Referring Domains or Top Pages adds about +$0.02 each.
  • Exact cost can vary slightly based on returned rows and DataForSEO pricing.

Planning examples

  • 100 keyword research requests at the default 150 results: $3.50
  • 100 keyword research requests at 500 results each: $7.00
  • 100 domain overviews (200 ranked keywords each): $4.01
  • 100 backlinks domain searches at current defaults before opening extra tabs: about $6.34
  • 100 backlinks page searches at current defaults before opening extra tabs: about $4.30
  • 100 fully explored backlinks domain searches: about $10.94
  • 100 fully explored backlinks page searches: about $8.61
Description
No description provided
Readme MIT 24 MiB
Languages
TypeScript 95.9%
MDX 2.4%
CSS 0.8%
JavaScript 0.5%
HTML 0.2%
Other 0.2%