Skip to main content

Auth, Routing, and Middleware Feature Context

Source: .agents/references/features/auth-routing-and-middleware.md

Content

Auth, Routing, and Middleware Feature Context

Purpose

Auth, routing, and middleware protect route access, locale/country redirects, portal path redirects, Flutter/webview behavior, token refresh, login/logout/reset flows, and public/private page boundaries. This domain is high-impact because incorrect redirects can break SEO, checkout, community access, or authenticated creator/member workflows.

User-Facing Workflows

  • Visitors and members move through login, logout, OAuth, reset/forget password, email redirect, and account deletion flows.
  • Requests pass through middleware that may redirect based on country, locale, community page rules, portal path, product checkout path, authenticated user state, or Flutter/webview context.
  • Authenticated-only pages should redirect unauthenticated users without breaking public community pages.
  • Public routes must remain accessible unless a middleware explicitly gates them.

Key Entrypoints

  • Routes:
    • src/middleware.page.js
    • src/pages/auth/
    • src/pages/login/
    • src/pages/logout/
    • src/pages/oauth/
    • src/pages/forget-password/
    • src/pages/reset-password/
    • src/pages/email-redirect/
    • src/pages/account-deletion/
    • src/pages/reroute-user/
  • Middleware:
    • src/middlewares/withMiddlewares.ts
    • src/middlewares/authenticatedUserRedirectionMiddleware.ts
    • src/middlewares/communityPageRedirectionMiddleware.ts
    • src/middlewares/communityPageMemberRedirectionMiddleware.ts
    • src/middlewares/communityCookieRemovalMiddleware.ts
    • src/middlewares/commonLocaleRedirectionMiddleware.ts
    • src/middlewares/countryPricingRedirectionMiddleware.ts
    • src/middlewares/countryZerolinkRedirectionMiddleware.ts
    • src/middlewares/domainSwitchMiddleware.ts
    • src/middlewares/portalRedirectionMiddleware.ts
    • src/middlewares/portalSettingsPathMiddleware.ts
    • src/middlewares/portalMoneyPathMiddleware.ts
    • src/middlewares/appCheckoutRedirectionMiddleware.ts
    • src/middlewares/whiteLabelDomainRoutingMiddleware.ts
    • src/middlewares/flutterWebMiddleware/
  • Modules/hooks/utilities:
    • src/modules/Auth.js
    • src/hooks/router/useParametrizedPathname.ts
    • src/hooks/router/useShallowRouterReplace.ts
    • src/contexts/RouterContext/index.tsx
    • src/utility/crossHostAuthUrl.ts
    • src/utility/domainUrl.ts
    • src/utility/framerRoutes.ts
    • src/utility/jwtHelper.ts
    • src/utility/cookieService.ts
    • src/utility/loginConstants.js
    • src/utility/routesHelper.ts
    • src/utility/webview.js
    • src/utility/middleware/
  • Services:
    • src/services/userService.js
    • src/services/helpers/authorizedRequest.js
    • src/services/helpers/adminProtectedAxiosRequest.ts
    • src/services/helpers/staticServerProtectedAxiosRequest.js

Data Flow and Service Boundaries

  • Middleware ordering matters. Inspect withMiddlewares.ts and src/middleware.page.js before adding or changing a redirect rule.
  • Sensitive auth query cleanup must not run before the middleware chain has preserved existing route decisions. Token-bearing URLs should set cookies on the final response, then scrub accessToken and refreshToken from the outgoing redirect URL, or return a cleaned redirect only when the route would otherwise continue to the page.
  • Locale redirection must run before white-label custom-domain rewrites. Custom-domain rewrites return a response for public pages and stop the middleware chain, so placing locale handling after them breaks multi-language URL redirects on verified custom domains.
  • Redirect logic often depends on cookies, country/locale, community slugs, portal paths, and auth state. Preserve existing fallback behavior for missing or malformed values.
  • Auth token helpers and request helpers may run in server or browser contexts. Do not assume window or document is available.
  • Service helper changes can affect all API calls. Keep helper edits narrow and run broad verification when touching request/authorization utilities.
  • Route changes should consider Next.js page naming conventions: page files use .page.js or .page.tsx.

White-Label Cross-Domain Routing

Keep the policy centralized:

  • whiteLabelDomainRoutingMiddleware.ts decides which host should serve a request.
  • RouterContext normalizes client-side router.push and router.replace.
  • withMiddlewares.ts consumes valid cross-host token links and removes token params from the URL.
  • routesHelper.ts builds public/share URLs that users copy or see rendered.

Domain mapping:

  • Do not use Edge Config for white-label mapping.
  • Use community-landing-page?whiteLabelledDomain=host to resolve a custom domain to its community.
  • Use community-landing-page?communitySlug=/slug to check whether a NAS community route has a custom domain.

Expected URL behavior:

  • https://a.com/ stays https://a.com/ and internally rewrites to the community home page.
  • https://a.com/products stays https://a.com/products and internally rewrites to the community products page.
  • https://a.com/a/home redirects to https://a.com/; custom-domain public URLs should not expose the community slug.
  • https://nas.com/a/home redirects to https://a.com/ when community a has whiteLabelledDomain.
  • https://nas.com/a/courses/course-id redirects to https://a.com/courses/course-id when community a has whiteLabelledDomain.
  • https://a.com/user/account-profile redirects to the NAS domain because /user is NAS-only.
  • https://a.com/get-started redirects to the NAS domain because /get-started is NAS-owned.

Path ownership:

  • Custom-domain public paths use slugless URLs, such as /, /community, /products, and /courses/....
  • NAS-only paths are listed in NAS_ONLY_CUSTOM_DOMAIN_PATHS, including /user, /portal, /checkout-global, /payment-method, /payment-authentication, /subscribe-plan, /choose-a-plan, /get-started, /install, /reset-password, /forget-password, /email-redirect, and /account-deletion.
  • Custom-domain runtime paths are listed in CUSTOM_DOMAIN_RUNTIME_PATHS; currently /auth, /login, and /reroute-user.
  • Framer/marketing paths are NAS-owned. Do not append or consume auth tokens for Framer paths; only scrub token params if they appear in the URL.

Auth and locale rules:

  • Cross-host login continuity uses direct accessToken and refreshToken query params from crossHostAuthUrl.ts; do not route through /auth/pub or /auth/sub.
  • Only append token params when both tokens exist, the target host differs from the current host, and the target is trusted.
  • withMiddlewares.ts must remove accessToken and refreshToken from outgoing URLs after preserving the normal middleware redirect/rewrite decision.
  • Settings/user routes may include a sanitized returnUrl so the NAS settings back button can return to the original custom-domain page.
  • Locale redirects must run before custom-domain public-page rewrites so / can become /ja on custom domains when the stored locale requires it.

Conventions and Gotchas

  • Treat query params, slugs, cookies, and JWTs as untrusted. Validate and narrow before use.
  • For auth-token URL cleanup, tests must cover middleware-generated redirects, middleware pass-through, cookie setting before cleanup, invalid token scrubbing, and preservation of non-sensitive query params.
  • Do not store sensitive credentials in direct browser storage. Use existing cookie/request helpers.
  • Avoid direct window or document access outside guarded browser-only code.
  • Redirect bugs often show up as loops. Check both the source route and target route when changing middleware.
  • Preserve locale and country pricing behavior unless the task explicitly changes routing policy.
  • Middleware code may be TypeScript while some route/auth modules are JavaScript. Keep existing extension unless migrating is requested.
  • .agents/rules/web-security.mdc
  • .agents/rules/prefer-typescript-files.mdc
  • .agents/rules/clean-typescript.mdc
  • .agents/rules/bun-first.mdc
  • .agents/references/features/custom-domain-management.md
  • .agents/references/features/community-public-pages.md
  • .agents/references/features/checkout-and-payments.md

Useful Graph Queries and Fallback Searches

Use the terms below with search_graph/search_code, then run trace_path on central middleware, redirect, or auth symbols. Run these shell searches only as documented fallbacks.

rtk rg "redirect|middleware|cookie|jwt|authorizedRequest|login|logout|oauth|webview" src/middleware.page.js src/middlewares src/pages src/utility src/services
rtk find src/middlewares -maxdepth 3 -type f
rtk rg "router.replace|router.push|useShallowRouterReplace|useParametrizedPathname" src

Update Triggers

Update this reference when middleware order, redirect policy, auth helper contracts, login/reset routes, or server/client request helper behavior changes.