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.jssrc/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.tssrc/middlewares/authenticatedUserRedirectionMiddleware.tssrc/middlewares/communityPageRedirectionMiddleware.tssrc/middlewares/communityPageMemberRedirectionMiddleware.tssrc/middlewares/communityCookieRemovalMiddleware.tssrc/middlewares/commonLocaleRedirectionMiddleware.tssrc/middlewares/countryPricingRedirectionMiddleware.tssrc/middlewares/countryZerolinkRedirectionMiddleware.tssrc/middlewares/domainSwitchMiddleware.tssrc/middlewares/portalRedirectionMiddleware.tssrc/middlewares/portalSettingsPathMiddleware.tssrc/middlewares/portalMoneyPathMiddleware.tssrc/middlewares/appCheckoutRedirectionMiddleware.tssrc/middlewares/whiteLabelDomainRoutingMiddleware.tssrc/middlewares/flutterWebMiddleware/
- Modules/hooks/utilities:
src/modules/Auth.jssrc/hooks/router/useParametrizedPathname.tssrc/hooks/router/useShallowRouterReplace.tssrc/contexts/RouterContext/index.tsxsrc/utility/crossHostAuthUrl.tssrc/utility/domainUrl.tssrc/utility/framerRoutes.tssrc/utility/jwtHelper.tssrc/utility/cookieService.tssrc/utility/loginConstants.jssrc/utility/routesHelper.tssrc/utility/webview.jssrc/utility/middleware/
- Services:
src/services/userService.jssrc/services/helpers/authorizedRequest.jssrc/services/helpers/adminProtectedAxiosRequest.tssrc/services/helpers/staticServerProtectedAxiosRequest.js
Data Flow and Service Boundaries
- Middleware ordering matters. Inspect
withMiddlewares.tsandsrc/middleware.page.jsbefore 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
accessTokenandrefreshTokenfrom 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
windowordocumentis 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.jsor.page.tsx.
White-Label Cross-Domain Routing
Keep the policy centralized:
whiteLabelDomainRoutingMiddleware.tsdecides which host should serve a request.RouterContextnormalizes client-siderouter.pushandrouter.replace.withMiddlewares.tsconsumes valid cross-host token links and removes token params from the URL.routesHelper.tsbuilds 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=hostto resolve a custom domain to its community. - Use
community-landing-page?communitySlug=/slugto check whether a NAS community route has a custom domain.
Expected URL behavior:
https://a.com/stayshttps://a.com/and internally rewrites to the community home page.https://a.com/productsstayshttps://a.com/productsand internally rewrites to the community products page.https://a.com/a/homeredirects tohttps://a.com/; custom-domain public URLs should not expose the community slug.https://nas.com/a/homeredirects tohttps://a.com/when communityahaswhiteLabelledDomain.https://nas.com/a/courses/course-idredirects tohttps://a.com/courses/course-idwhen communityahaswhiteLabelledDomain.https://a.com/user/account-profileredirects to the NAS domain because/useris NAS-only.https://a.com/get-startedredirects to the NAS domain because/get-startedis 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
accessTokenandrefreshTokenquery params fromcrossHostAuthUrl.ts; do not route through/auth/pubor/auth/sub. - Only append token params when both tokens exist, the target host differs from the current host, and the target is trusted.
withMiddlewares.tsmust removeaccessTokenandrefreshTokenfrom outgoing URLs after preserving the normal middleware redirect/rewrite decision.- Settings/user routes may include a sanitized
returnUrlso 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/jaon 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
windowordocumentaccess 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.
Related Standards
.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.