# User Management for React Apps

**User management encompasses far more than login forms.** From password resets and session tokens to organization hierarchies and enterprise [SSO](https://clerk.com/glossary/single-sign-on-sso.md), the scope catches most development teams off guard — and building these features from scratch typically costs $250,000–600,000 over 6–12 months. Authentication vulnerabilities consistently rank among the top security risks, with broken authentication listed as #2 in OWASP's Top 10 ([OWASP Top 10, 2021](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)). Clerk, Auth0, AWS Cognito, and Firebase each address different segments, with Clerk offering the most complete React and Next.js integration for both B2C and B2B use cases. This guide examines what comprehensive user management actually requires, analyzes the build-vs-buy tradeoff with concrete data, and compares today's leading platforms.

> This article was updated March 11, 2026. The updates and changes reflect the major [Core 3](https://clerk.com/changelog/2026-03-03-core-3.md) release from March 3, 2026 and Clerk's [new pricing](https://clerk.com/changelog/2026-02-05-new-plans-more-value.md) launched February 5, 2026

| Topic                  | Finding                                                                                                                                                                                                                                                        | Impact                                                     |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| **Build time**         | Custom auth takes 5-6 weeks (basic) to 12+ months (production-grade) ([FusionAuth, 2024](https://fusionauth.io/buildvsbuy))                                                                                                                                    | Significant delay to core product development              |
| **Cost comparison**    | DIY: $700K–$1.95M vs Managed: $25K–$60K over 3 years                                                                                                                                                                                                           | 10-30x cost savings with managed solutions                 |
| **Credential attacks** | 22% of breaches start with credential abuse ([Verizon DBIR, 2025](https://www.verizon.com/business/resources/reports/dbir/))                                                                                                                                   | Authentication is the #1 attack vector                     |
| **MFA effectiveness**  | Blocks 99.9% of account compromises ([Microsoft, 2019](https://www.microsoft.com/en-us/security/blog/2019/08/20/one-simple-action-you-can-take-to-prevent-99-9-percent-of-account-attacks/))                                                                   | Essential security control, complex to implement correctly |
| **Enterprise SSO**     | 63% of organizations have implemented zero-trust strategies requiring SSO ([Gartner, 2024](https://www.gartner.com/en/newsroom/press-releases/2024-04-22-gartner-survey-reveals-63-percent-of-organizations-worldwide-have-implemented-a-zero-trust-strategy)) | Required for B2B enterprise sales                          |

## The true scope of user management

User management extends across at least ten distinct functional areas, each with its own security implications and edge cases. Developers frequently underestimate this scope, treating authentication as a weekend project rather than a core infrastructure decision.

**Authentication methods** alone span email/password, social [OAuth](https://clerk.com/glossary.md#oauth) (Google, GitHub, Facebook), [passwordless](https://clerk.com/glossary.md#passwordless-login) options ([magic links](https://clerk.com/glossary.md#magic-links), [passkeys](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options.md#passkeys), [WebAuthn](https://clerk.com/glossary.md#webauthn)), [multi-factor authentication](https://clerk.com/glossary.md#multi-factor-authentication-mfa) ([TOTP](https://clerk.com/glossary.md#authenticator-apps-totp), SMS, hardware keys), and enterprise [SSO](https://clerk.com/glossary/single-sign-on-sso.md) (SAML, OIDC). For B2B SaaS products, SSO support is often a prerequisite for enterprise deals and can significantly improve conversion rates for enterprise customers ([Clerk B2B SaaS, 2026](https://clerk.com/b2b-saas)).

[**Session management**](https://clerk.com/glossary.md#session-management) requires cryptographically random tokens, proper cookie security attributes, idle and absolute timeouts, multi-device handling, and secure session regeneration after privilege changes. The OWASP Session Management Cheat Sheet documents over twenty specific security requirements, from TLS implementation to [session fixation](https://clerk.com/glossary.md#session-fixation) prevention ([OWASP, 2024](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)).

**Password lifecycle** involves secure hashing—Argon2id is now OWASP's top recommendation ([OWASP Password Storage, 2024](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html))—breached password detection against databases like HaveIBeenPwned, reset flows with one-time tokens, [rate limiting](https://clerk.com/glossary.md#rate-limiting) by IP and account, and crucially, invalidating all existing sessions after password changes. Session invalidation failures remain a commonly exploitable vulnerability pattern ([Adhikari, 2024](https://medium.com/@ad.abhi0013/understanding-session-management-vulnerabilities-the-case-of-password-resets-0f5bb123f598)).

**User profiles and metadata** require handling custom fields, avatars, preferences, multiple email addresses, external IDs for migrations, and the distinction between public metadata (for client-readable RBAC data) and private metadata (server-only sensitive information).

For B2B applications, the complexity multiplies. **Organization management** demands [multi-tenant](https://clerk.com/glossary/multi-tenancy.md) data isolation, workspace hierarchies, organization-level settings and branding, domain verification for membership restrictions, and seamless context switching between organizations. **Role-based access control** requires permission modeling, predefined and custom roles, granular resource-level permissions, and role inheritance patterns ([Frontegg RBAC Guide, 2024](https://frontegg.com/guides/roles-and-permissions-handling-in-saas-applications)).

Enterprise customers expect **SSO integration**—63% of organizations have implemented [zero-trust](https://clerk.com/glossary.md#zero-trust-architecture) strategies that require identity verification—along with **[SCIM provisioning](https://clerk.com/glossary.md#directory-sync)** for automated user lifecycle management, comprehensive **[audit logs](https://clerk.com/glossary.md#audit-logs)** meeting [SOC 2](https://clerk.com/glossary.md#soc-2) requirements ([Frontegg, 2024](https://frontegg.com/blog/audit-logs-for-saas-enterprise-customers)), and **admin impersonation** capabilities for customer support.

Finally, **user lifecycle management** must handle account deletion (GDPR's "right to be forgotten"), data export (data portability requirements), consent management, and compliance with regulations including SOC 2, GDPR, [CCPA](https://clerk.com/glossary.md#california-consumer-privacy-act-ccpa), and potentially [HIPAA](https://clerk.com/glossary.md#health-insurance-portability-accountability-act-hipaa).

## Why building authentication is harder than it appears

Building production-grade authentication takes significantly longer than most teams anticipate:

| Feature                             | Development Time     | Estimated Cost           |
| ----------------------------------- | -------------------- | ------------------------ |
| Basic email/password + social login | 5-6 weeks            | $14,000-20,000           |
| TOTP-based MFA                      | 8-10 weeks MVP       | $50,000-150,000          |
| Enterprise SSO (SAML/OIDC)          | 3-6 developer-months | $250,000-500,000         |
| Full production system              | 12+ months           | $250,000-600,000 initial |

_Source: FusionAuth Build vs Buy Analysis, 2024_

The three-year total cost of ownership for custom authentication reaches $700,000 to $1.95 million when accounting for ongoing maintenance, security updates, and feature additions. By contrast, managed solutions cost approximately $25,000-60,000 over three years at 10,000 monthly active users.

### Hidden complexities that catch teams

**Password reset flows** require tracking unique one-time tokens, rate limiting by IP and account to prevent [brute force](https://clerk.com/glossary.md#brute-force-detection), and invalidating all existing sessions—a security requirement that developers frequently overlook.

**Session management edge cases** multiply quickly: handling [JWT](https://clerk.com/glossary.md#json-web-token) tokens across multiple browsers and devices, implementing [refresh token](https://clerk.com/glossary.md#refresh-token) rotation for compromised sessions, and ensuring proper session destruction server-side. Developers often forget session invalidation during password reset processes—a vulnerability that attackers actively exploit.

**Username comparison** presents unexpected pitfalls: identical-looking usernames may not compare equal due to Unicode normalization issues. Password hashing requires migration paths when algorithms change. Account merging flows for users who signed up with different methods demand careful data reconciliation.

### The security risk calculation

22% of breaches begin with credential abuse, and 88% of basic web application attacks involve stolen credentials. MFA can block over 99.9% of account compromise attacks—yet implementing MFA correctly requires expertise most application teams lack.

Common DIY vulnerabilities include passwords stored unhashed or improperly hashed, clear-text passwords in log files, password reset forms exploitable via social engineering, hardcoded JWT tokens in source code, and missing rate limiting.

## Comparing user management platforms

The market offers several mature options, each with distinct strengths and tradeoffs. The right choice depends on your tech stack, team size, budget constraints, and specific feature requirements.

### Platform feature comparison

| Feature                          | Clerk          | Auth0          | AWS Cognito | Firebase         | Supabase    |
| -------------------------------- | -------------- | -------------- | ----------- | ---------------- | ----------- |
| **Free tier (MRU/MAU)**          | **50,000 MRU** | **25,000**     | 10,000      | **50,000**       | **50,000**  |
| **MFA**                          | Yes            | Yes            | Yes         | Upgrade required | Yes         |
| **SSO/SAML**                     | Yes            | Yes            | Yes         | Upgrade required | Paid add-on |
| **Organization Management**      | Yes            | Yes            | No          | No               | Manual      |
| **RBAC**                         | Yes            | Yes            | Limited     | No               | Via RLS     |
| **React/Next.js SDK**            | Yes            | Yes            | Yes         | Limited          | Yes         |
| **Pre-built UI Components**      | Yes            | Basic          | Basic       | Basic            | Yes         |
| **Extensibility / Custom Logic** | Limited        | Yes            | Yes         | Limited          | Yes         |
| **Self-hosting Option**          | No             | No             | No          | No               | Yes         |
| **Vendor Lock-in Risk**          | **Low**        | Medium         | High (AWS)  | High (Google)    | **Low**     |
| **Documentation Quality**        | Excellent      | Good (complex) | Poor        | Good             | Excellent   |

_Sources: [Clerk, 2026](https://clerk.com/docs.md), [Auth0, 2025](https://auth0.com/docs), [AWS Cognito, 2025](https://docs.aws.amazon.com/cognito/), [Firebase, 2025](https://firebase.google.com/docs/auth), [Supabase, 2025](https://supabase.com/docs/guides/auth)_

### Platform deep dive: Clerk

Clerk has become a popular choice for React and Next.js developers, with over 700,000 weekly npm downloads for its React SDK ([NPM Trends, 2026](https://npmtrends.com/@clerk/clerk-react)). The platform manages authentication for thousands of applications, from early-stage startups to large-scale enterprises ([Clerk, 2026](https://clerk.com/user-authentication)).

Several architectural decisions differentiate Clerk from alternatives:

**Pre-built, customizable components** handle both frontend rendering and backend logic. Components like [`<SignIn />`](https://clerk.com/docs/reference/components/authentication/sign-in.md), [`<UserButton />`](https://clerk.com/docs/reference/components/user/user-button.md), and [`<OrganizationSwitcher />`](https://clerk.com/docs/reference/components/organization/organization-switcher.md) provide production-ready UI while remaining fully customizable. With the release of Core 3, Clerk introduced the unified `<Show>` component for conditional rendering based on auth state, and automatic light/dark theme detection. As Guillermo Rauch, Vercel's CEO and Next.js creator, noted: "Clerk is the Stripe Checkout of authentication and user management, except it's built for React." ([Clerk, 2023](https://clerk.com/blog/series-a.md))

**First-class Next.js integration** supports App Router, Pages Router, and React Server Components ([Clerk, 2026](https://clerk.com/blog/nextjs-authentication.md)). The [`clerkMiddleware()`](https://clerk.com/docs/reference/nextjs/clerk-middleware.md) function protects routes before they reach your application—configured via `proxy.ts` in Next.js 16, which runs on Node.js runtime (not Edge)—while the [`auth()`](https://clerk.com/docs/reference/nextjs/auth.md) helper provides server component authentication and [`useAuth()`](https://clerk.com/docs/reference/hooks/use-auth.md) handles client components.

**Native B2B capabilities** include Organizations with hierarchical team structures, [custom RBAC](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions.md) with up to 10 roles per application, verified domain restrictions for membership, and pre-built billing components ([Clerk, 2026](https://clerk.com/docs/guides/organizations/overview.md)). The free tier includes 100 monthly retained organizations (MROs) with up to 5 members each.

**Security certifications** cover SOC2 Type II, HIPAA, GDPR, and CCPA compliance ([Clerk, 2026](https://clerk.com/user-authentication)). Third-party penetration testing follows OWASP Testing Guide and NIST Technical Guide standards.

**Considerations:** Clerk is a fully managed service with no self-hosting option, which may not suit teams with strict data residency requirements. Its extensibility model is more opinionated than Auth0's Actions framework, trading flexibility for simplicity.

Implementation typically takes minutes rather than weeks. As Turso documented after their migration: "In terms of development speed, I'm not aware of another solution that has something similar to Clerk's Account Portal." ([Turso Blog, 2024](https://turso.tech/blog/why-we-transitioned-to-clerk-for-authentication))

### Platform deep dive: Auth0

Auth0 remains the most feature-complete enterprise solution, offering capabilities that justify its premium for organizations with complex requirements.

**Extensibility through Actions** provides a powerful framework for custom authentication logic. Teams can inject code at any point in the authentication pipeline—post-login, pre-registration, password reset, and more. For organizations with complex authorization rules or legacy system integrations, this flexibility is often decisive.

**Enterprise-grade features** include excellent [OIDC](https://clerk.com/glossary.md#openid-connect) compliance, comprehensive B2B multi-tenancy through Organizations, and mature integrations with enterprise [identity providers](https://clerk.com/glossary.md#identity-provider-sso-idp-sso). Auth0's long track record in the enterprise space means better support for edge cases and unusual configurations.

**Considerations:** Auth0's pricing has drawn criticism for what developers call the "growth penalty"—cost is frequently cited as a primary reason developers migrate away ([SSOJet, 2024](https://ssojet.com/blog/auth0-pricing-growth-penalty); [SuperTokens, 2024](https://supertokens.com/blog/auth0-vs-clerk)). The platform's breadth can also translate to complexity; teams report steeper learning curves compared to more opinionated alternatives.

### Platform deep dive: AWS Cognito

Cognito makes sense for teams deeply invested in the AWS ecosystem, offering native integration with Lambda, API Gateway, and other AWS services.

**Lambda triggers** enable sophisticated custom workflows at every authentication touchpoint—pre-signup validation, post-confirmation actions, token generation customization, and more. For teams already running on AWS, this integration can simplify architecture significantly.

**Cost efficiency at scale** becomes apparent for high-volume applications, as Cognito's pricing model favors large MAU counts more than some competitors.

**Considerations:** Developer experience has drawn consistent criticism. Common pain points include rigid user pools that cannot add attributes after creation, limited disaster recovery capabilities, and rate limits that cause throttling at scale. Documentation quality lags behind competitors, and the learning curve for proper IAM configuration is substantial.

### Platform deep dive: Supabase Auth

Supabase offers the strongest value proposition for budget-conscious teams and those prioritizing open-source flexibility.

**Generous free tier** of 50,000 MAU makes it accessible for side projects and early-stage startups. The open-source model means teams can self-host with full control over their data—a decisive factor for organizations with strict data residency or sovereignty requirements.

**PostgreSQL-native integration** through Row Level Security provides elegant authorization patterns for teams already using Postgres. Authentication and authorization logic lives alongside your data, simplifying the mental model.

**Excellent developer experience** with strong React integration, good documentation, and active community support. Edge Functions provide extensibility when needed.

**Considerations:** Native organization management requires manual implementation, and RBAC patterns are less turnkey than dedicated B2B platforms. Enterprise SSO is a paid add-on rather than built-in.

### Platform deep dive: Firebase Authentication

Firebase works well for mobile-first applications within the Google ecosystem, particularly for teams already using Firestore or other Firebase services.

**Strong mobile SDKs** and seamless integration with Google Cloud services make it a natural choice for Android/iOS applications with Google Cloud backends.

**Generous free tier** of 50,000 MAU and simple getting-started experience lower the barrier to entry.

**Considerations:** Enterprise features are limited without upgrading to Identity Platform. Built-in RBAC, audit logs, and organization management are absent, requiring either custom implementation or the significantly more expensive Identity Platform tier. Vendor lock-in to the Google ecosystem is substantial.

## Security and compliance requirements

Proper user management must satisfy both technical security standards and regulatory compliance requirements.

### OWASP authentication best practices

The OWASP Authentication Cheat Sheet establishes foundational requirements ([OWASP, 2024](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)):

**Multi-factor authentication** is "by far the best defense against the majority of password-related attacks" ([OWASP, 2024](https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html)). Require some form of MFA for all users, TOTP for user-enabled MFA, and mandatory MFA for administrators. Prefer possession-based factors ([hardware keys](https://clerk.com/glossary.md#hardware-keys)) or biometrics over SMS.

**Password policies** should require minimum 8 characters with MFA enabled or 15+ characters without, allow maximum lengths of at least 64 characters for passphrases, permit all characters including Unicode and whitespace, and avoid composition rules. Contrary to older guidance, **avoid periodic password changes**—encourage strong passwords plus MFA instead.

**Session security** demands unique session IDs that are cryptographically random, secure cookie flags, SameSite attributes to prevent [CSRF](https://clerk.com/glossary.md#cross-site-request-forgery-csrf), idle timeouts of 15-30 minutes for high-value applications, absolute timeouts of 2-24 hours, and session ID regeneration after authentication.

**Password storage** requires modern hashing algorithms: Use Argon2id with a minimum configuration of 19 MiB of memory, an iteration count of 2, and 1 degree of parallelism. If Argon2id is not available, use scrypt or bcrypt with a work factor of 10 or more. Never use MD5, SHA-1, or plain SHA-256.

### Regulatory compliance overview

**SOC 2** requires implementation of 64+ controls across five Trust Services Criteria: security, availability, processing integrity, confidentiality, and privacy. Key user management controls include MFA implementation, RBAC, user provisioning/deprovisioning workflows, access logging, and regular access reviews. Achieving SOC 2 compliance independently takes 18-24 months and costs $75,000-200,000+; with managed authentication platforms, the timeline shortens to 6-12 months at $20,000-60,000 ([AICPA, 2025](https://www.aicpa.org/)).

**GDPR** mandates user rights including access (users can request copies of personal data), rectification (correct inaccurate data), erasure (delete data when no longer necessary or upon withdrawal of consent), and portability (export in machine-readable format). Non-compliance penalties reach €20 million ($21 million USD) or 4% of global annual turnover ([European Commission, 2018](https://eur-lex.europa.eu/eli/reg/2016/679/oj)).

**CCPA/CPRA** applies to businesses with annual revenue exceeding $26.6 million (adjusted for inflation as of 2025), 50%+ revenue from selling personal information, or data from 100,000+ California consumers ([California Privacy Protection Agency, 2025](https://cppa.ca.gov/regulations/cpi_adjustment.html)). Required capabilities include "Do Not Sell My Personal Information" links, 45-day response windows for consumer requests, and identity verification before fulfilling requests.

## B2B SaaS user management architecture

B2B applications face additional complexity around multi-tenancy, organization structures, and enterprise sales requirements. [Understanding multi-tenancy](https://clerk.com/blog/what-is-multi-tenancy-and-why-it-matters-for-B2B-SaaS.md) is foundational—it's the architecture pattern that allows a single application instance to serve multiple customers while keeping their data, configurations, and workflows isolated. Without it, you'd face mounting technical debt from coordinating migrations across separate databases, fragmented monitoring, and impossible-to-scale infrastructure.

### Multi-tenancy implementation patterns

Three primary patterns exist for tenant data isolation:

**Shared database with tenant identifiers** adds an `organization_id` column to every table—simplest and most cost-effective but offers limited isolation. **Separate schemas per tenant** improves isolation while sharing database infrastructure. **Database-per-tenant** provides maximum isolation for strict compliance requirements but increases operational complexity significantly ([Daily.dev, 2024](https://daily.dev/blog/multi-tenant-database-design-patterns-2024)).

Modern authentication platforms abstract this complexity through Organizations as first-class entities. Each organization maintains isolated configurations, SSO connections, security policies, and member rosters while users can belong to multiple organizations with a single identity.

> Learn more about modeling your system for multi-tenancy in [this guide on our blog](https://clerk.com/blog/how-to-design-multitenant-saas-architecture.md).

### Essential B2B features checklist

Core requirements every B2B SaaS needs:

- [Multi-tenant](https://clerk.com/glossary/multi-tenancy.md) data isolation
- Organization/workspace support with user membership model
- Email-based invitation system with role pre-assignment
- Basic [RBAC](https://clerk.com/glossary.md#role-based-access-control-rbac) (admin, member roles minimum)
- Domain-based auto-join for enterprise customers

Standard features for growth-stage applications:

- [Custom roles](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions.md) and fine-grained permissions
- Organization settings and branding customization
- Pending invitation management and reminders
- User offboarding workflows with resource ownership transfer

Enterprise requirements for upmarket sales:

- [SAML/OIDC SSO](https://clerk.com/glossary/single-sign-on-sso.md)—required by enterprises implementing zero-trust strategies
- [SCIM provisioning](https://clerk.com/glossary.md#directory-sync) for automated user lifecycle management
- Comprehensive [audit logs](https://clerk.com/glossary.md#audit-logs) with SIEM integration
- Admin impersonation with mandatory justification and audit trails
- [Just-in-time provisioning](https://clerk.com/docs/guides/configure/auth-strategies/enterprise-connections/jit-provisioning.md) from IdP attributes
- Per-seat billing integration with Stripe, Chargebee, or similar

### The role-based access control foundation

Effective RBAC requires modeling four core components ([Stytch, 2024](https://stytch.com/docs/b2b/guides/rbac/overview)):

- **Resources**: The entities in your system that require access control—documents, projects, billing settings, team configurations, or any object users interact with. Define resources at the granularity that matches your authorization needs.

- **Actions**: The operations users can perform on resources, typically including create, read, update, and delete (CRUD), but often extending to domain-specific operations like "publish," "approve," or "transfer ownership."

- **Roles**: Named collections of permissions that bundle related actions across resources. Common roles include Admin (full access), Editor (create and modify), and Viewer (read-only), though B2B applications often require custom roles like "Billing Manager" or "Project Lead."

- **Role bindings**: The associations between users and roles, determining what each user can actually do. Bindings can be scoped globally, per-organization, or per-resource depending on your authorization model.

Most applications need both predefined roles (admin, editor, viewer) and custom role creation for enterprise customers ([EnterpriseReady, 2024](https://www.enterpriseready.io/features/role-based-access-control/)). Consider whether permissions apply at tenant level (all resources of a type), organization level (within organization scope), or individual resource level (most granular). Role inheritance—where Owner inherits Admin permissions, which inherits Member permissions—simplifies management for common use cases ([Stytch, 2024](https://stytch.com/blog/what-is-rbac/)).

## Implementation patterns for Next.js applications

[React Server Components](https://clerk.com/glossary.md#react-server-components) fundamentally change authentication architecture. Traditional client-side approaches render authentication UI, make API calls for session data, and re-render based on state—introducing loading flickers and exposing authentication logic.

With RSC, authentication can happen entirely server-side before any HTML reaches the client. Clerk's `auth()` helper retrieves session data in Server Components without round-trips:

filename: app/dashboard/page.tsx
```tsx
import { auth } from '@clerk/nextjs/server'
import { Dashboard } from '@/components/Dashboard'

export default async function DashboardPage() {
  const { isAuthenticated, redirectToSignIn, userId, orgId } = await auth()

  if (!isAuthenticated) {
    return redirectToSignIn()
  }

  // User is authenticated, orgId indicates active organization
  return <Dashboard organizationId={orgId} />
}
```

The `clerkMiddleware()` function protects routes in milliseconds before requests reach your application. In Next.js 16, this is configured via `proxy.ts` (replacing the previous `middleware.ts`). Unlike `middleware.ts`, which defaulted to Edge Runtime, `proxy.ts` runs exclusively on Node.js—giving auth libraries access to the full Node.js API. Setting `export const runtime = 'edge'` in `proxy.ts` is not supported:

filename: proxy.ts
```ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)'])

export default clerkMiddleware(async (auth, req) => {
  if (isProtectedRoute(req)) await auth.protect()
})

export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)',
  ],
}
```

For B2B applications, organization context flows through the entire request:

filename: app/team/settings/page.tsx
```tsx
import { auth } from '@clerk/nextjs/server'
import { AdminSettings } from '@/components/AdminSettings'
import { InsufficientPermissions } from '@/components/InsufficientPermissions'
import { NoOrganizationSelected } from '@/components/NoOrganizationSelected'

export default async function TeamSettings() {
  const { orgId, orgRole } = await auth()

  if (!orgId) {
    return <NoOrganizationSelected />
  }

  if (orgRole !== 'org:admin') {
    return <InsufficientPermissions />
  }

  return <AdminSettings />
}
```

## Making the build versus buy decision

The data strongly favors buying for most teams, but context matters.

**Build custom authentication only when** authentication is your core product differentiator, you have a dedicated security team with 3+ engineers, unique requirements exist that no platform addresses, and timeline flexibility of 12+ months is acceptable.

**Use a managed solution when** you need production-ready auth in under 3 months, your team should focus on core product development, compliance requirements (SOC 2, GDPR, HIPAA) apply, you want to avoid ongoing security maintenance, and you have fewer than 2 dedicated security engineers.

**Choosing the right platform** depends on your specific context:

- **React/Next.js teams prioritizing speed**: Clerk and Supabase both offer excellent developer experiences with strong framework integration
- **Enterprise requirements and complex authorization**: Auth0's extensibility and maturity may justify the premium
- **AWS-native architectures**: Cognito's Lambda integration provides capabilities others can't match
- **Budget constraints or data sovereignty needs**: Supabase's generous free tier and self-hosting option stand out
- **Mobile-first Google ecosystem**: Firebase remains a natural fit

## Conclusion

Comprehensive user management requires expertise across authentication protocols, session security, password handling, B2B organization structures, enterprise integrations, and regulatory compliance. The engineering effort to build and maintain this infrastructure properly far exceeds what most teams anticipate—while the security consequences of getting it wrong can be catastrophic.

Modern authentication platforms have reduced implementation time from months to hours while providing security certifications and compliance frameworks that would cost hundreds of thousands of dollars to achieve independently. For React and Next.js teams specifically, options like Clerk and Supabase offer particularly strong developer experiences, while Auth0 and Cognito serve teams with different priorities around extensibility or cloud ecosystem alignment.

The question isn't whether you can build authentication—technically capable teams certainly can. The question is whether authentication is where your limited engineering bandwidth creates the most value. For the vast majority of applications, it isn't.

## Frequently asked questions

## FAQ

### What are comprehensive user management solutions?

Comprehensive user management solutions are platforms that handle the full spectrum of identity and access management for applications—not just login forms, but the entire user lifecycle. This includes authentication methods (passwords, social login, SSO, MFA), session management, password resets, user profiles, organization structures for B2B applications, role-based access control, and compliance requirements like SOC 2 and GDPR. Modern platforms like Clerk, Auth0, Supabase, and AWS Cognito provide these capabilities as managed services, eliminating the need for teams to build and maintain this infrastructure themselves.

### How long does it take to build a comprehensive user management solution from scratch?

Building a production-grade comprehensive user management solution takes significantly longer than most teams anticipate. Basic email/password with social login requires 5-6 weeks of development. Adding TOTP-based MFA extends this to 8-10 weeks for an MVP. Enterprise SSO with SAML and OIDC support requires 3-6 developer-months. A full production system with all features typically takes 12+ months. This timeline doesn't include ongoing maintenance, security patches, and feature additions.

### What does a user management solution cost to build versus buy?

The three-year total cost of ownership for custom-built comprehensive user management solutions ranges from $700,000 to $1.95 million, including initial development, ongoing maintenance, security updates, and feature additions. By comparison, managed solutions cost approximately $25,000-60,000 over three years at 10,000 monthly active users—representing 10-30x cost savings. Teams should model their specific growth trajectory, as the optimal platform depends on MAU volume and feature requirements.

### What features should comprehensive user management solutions include?

Production-ready comprehensive user management solutions should include: **Authentication methods** (email/password, social OAuth, passwordless, MFA, and enterprise SSO), **Session management** (cryptographically random tokens, secure cookie attributes, timeouts, multi-device handling), **Password lifecycle** (secure hashing with Argon2id, breached password detection, reset flows with rate limiting), **User profiles** (custom fields, avatars, multiple emails, public and private metadata), **B2B capabilities** (organization management, role-based access control, domain verification, SCIM provisioning), and **Compliance features** (audit logs, data export, account deletion, consent management).

### Which comprehensive user management solution is best for React and Next.js applications?

For React and Next.js applications, both Clerk and Supabase offer excellent developer experiences with strong framework integration. Clerk provides extensive pre-built components and first-class Next.js support including App Router, Server Components, and middleware configured via proxy.ts (Node.js runtime) in Next.js 16. Supabase offers PostgreSQL-native integration and an open-source self-hosting option that appeals to teams with data sovereignty requirements. Auth0 may be preferable for teams needing complex authorization logic through its Actions framework. The best choice depends on your specific requirements around B2B features, extensibility needs, and budget constraints.

### How do comprehensive user management solutions compare on pricing?

Pricing varies significantly across platforms. Clerk offers 50,000 free MRU (Monthly Retained Users) with OAuth built-in, while MFA, passkeys, and enterprise SSO connections are available on Pro plans starting at $25/month. Auth0 provides 25,000 free MAU with enterprise SSO, suited for complex enterprise needs. AWS Cognito includes 10,000 free MAU with built-in SSO for AWS-native teams. Firebase offers 50,000 free MAU but requires upgrades for MFA and SSO. Supabase provides 50,000 free MAU with MFA included but SSO as a paid add-on. Teams should model their specific growth trajectory, as the 'best value' platform depends heavily on MAU volume, feature requirements, and whether self-hosting is important.

### What security standards should comprehensive user management solutions meet?

Comprehensive user management solutions should meet OWASP authentication best practices, including: **Multi-factor authentication** that blocks 99.9% of account compromise attacks, **Password storage** using Argon2id with minimum 19 MiB memory, or bcrypt with work factor 10+, **Session security** with cryptographically random IDs, HttpOnly/Secure cookies, SameSite attributes, and 15-30 minute idle timeouts, plus **Compliance certifications** including SOC 2 Type II, GDPR, CCPA, and potentially HIPAA depending on use case.

### Why is authentication the biggest security risk for web applications?

Authentication remains the leading attack vector because 22% of all data breaches begin with credential abuse, and 88% of basic web application attacks involve stolen credentials. Common vulnerabilities in DIY implementations include passwords stored improperly, clear-text passwords in logs, exploitable reset flows, hardcoded tokens, and missing rate limiting. Managed authentication platforms from established providers address these vulnerabilities by default through battle-tested implementations.

### What B2B features do comprehensive user management solutions need?

For B2B SaaS applications, comprehensive user management solutions require **core features** like multi-tenant data isolation, organization/workspace support with membership models, email-based invitation systems, and basic RBAC (admin, member roles). **Enterprise requirements** include SAML/OIDC SSO—required by 63% of organizations implementing zero-trust strategies, SCIM provisioning for automated user lifecycle, comprehensive audit logs, and admin impersonation with audit trails. Platforms like Clerk and Auth0 provide native organization management, while Supabase requires more manual implementation.

### When should teams build their own user management solution instead of buying?

Teams should consider building custom comprehensive user management solutions only when: authentication is their core product differentiator, they have a dedicated security team with 3+ engineers, unique requirements exist that no platform addresses, and timeline flexibility of 12+ months is acceptable. For the vast majority of applications, managed solutions offer faster time-to-market, better security, and significantly lower total cost of ownership.

### How do comprehensive user management solutions handle compliance requirements?

Leading comprehensive user management solutions handle compliance through: **SOC 2** with pre-built controls across security, availability, and privacy criteria—reducing compliance timeline from 18-24 months to 6-12 months, **GDPR** with built-in support for data access, rectification, erasure, and portability rights, **CCPA/CPRA** with identity verification workflows and 45-day response window support, and **HIPAA** with BAA availability and appropriate data handling controls. Most major platforms (Clerk, Auth0, AWS Cognito) maintain relevant compliance certifications, though specific certifications vary by platform and pricing tier.
