Skip to content

perf(storefront/middleware): dedupe Shop.findByDomain, parallelize locale resolution, fix LOCALE_SLASH_TEST flag #1986

Description

@filiphsps

What to build

apps/storefront/src/middleware/storefront.ts runs on every request and has three hot-path issues:

  1. Duplicate Shop.findByDomain per request — line 64 (getHostname()) calls Shop.findByDomain(hostname, { sensitiveData: true }) unconditionally. Line 213 calls it again for cookie-less (first-time) visitors. That's two MongoDB round-trips for every new-user request that should be deduped (e.g. memoize within the request scope via react.cache() or pass the resolved shop down).

  2. Sequential locale resolution — line 213-215 chains Shop.findByDomain → ShopifyApiClient → LocalesApi sequentially. The shop lookup gates the rest, but LocalesApi doesn't strictly depend on the Shopify client construction step. Parallelize where the dependency graph allows.

  3. LOCALE_SLASH_TEST regex flag — line 139 declares the RegExp with the g flag immediately after a comment block (lines 132-137) that explicitly warns "Don't add the g flag here." Current .match() usage is incidentally safe, but the flag contradicts the documented invariant and is a latent footgun if anyone later switches to .test().

Acceptance criteria

  • Cookie-less request path issues one Shop.findByDomain call per request, not two (verify with a middleware test that asserts the call count)
  • Locale-resolution branch parallelizes the work that doesn't depend on Shop.findByDomain
  • LOCALE_SLASH_TEST no longer has the g flag, matching its surrounding documentation
  • Middleware tests in storefront.test.ts still pass and gain coverage for the dedup
  • Measure middleware latency on a representative cookie-less request before/after — should drop

Blocked by

None — can start immediately.

References

  • apps/storefront/src/middleware/storefront.ts:64,139,213-215

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugSomething isn't workingOptimizationPerformance or bundle optimizations.ready-for-agentFully specified, ready for an AFK agent

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions