npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@talltydev/auth

v0.1.1

Published

Authentication and authorization package for Better Auth with React components and configuration factories

Downloads

12

Readme

@talltydev/auth

A comprehensive authentication and authorization package built on Better Auth, featuring React components, configuration factories, and ZenStack integration.

Features

  • 🔐 Better Auth Integration - Pre-configured Better Auth server and client factories
  • ⚛️ React Components - Ready-to-use authentication UI components
  • 🏢 Multi-Organization Support - Built-in organization and role management
  • 📱 Multi-Factor Authentication - Email/password + SMS OTP support
  • 🛡️ Route Protection - AuthGuard component with role-based access control
  • 🔧 ZenStack Integration - Auth context for row-level security
  • 🎨 Customizable - shadcn/ui based components with Tailwind CSS
  • 📦 Dual Distribution - NPM package + CLI copy-components pattern

Installation

NPM Package (Recommended)

npm install @talltydev/auth
# or
pnpm add @talltydev/auth

Copy Components (For customization)

# Install Tallty CLI globally
npm install -g @talltydev/cli

# Copy individual components
tallty add auth-login
tallty add auth-signup
tallty add auth-provider
tallty add auth-guard

Quick Start

1. Server Setup (Next.js API Routes)

// lib/auth.ts
import { createAuth } from '@talltydev/auth/server'
import { prisma } from './prisma'

export const auth = createAuth({
  database: { client: prisma },
  emailProvider: {
    apiKey: process.env.EMAIL_API_KEY!,
    fromEmail: '[email protected]',
    service: 'resend'
  },
  smsProvider: {
    apiUrl: process.env.SMS_API_URL!,
    apiKey: process.env.SMS_API_KEY!
  },
  sessionConfig: {
    expiresIn: 7 * 24 * 60 * 60, // 7 days
    cookieName: 'auth-session'
  },
  trustedOrigins: [process.env.NEXTAUTH_URL!]
})
// app/api/auth/[...all]/route.ts
import { auth } from '@/lib/auth'

export const { GET, POST } = auth.handler

2. Client Setup

// lib/auth-client.ts
import { createAuthClient } from '@talltydev/auth/client'

export const authClient = createAuthClient()

3. Generate Auth Components

Use the Tallty CLI to scaffold auth components into your project:

# Generate auth components and templates
npx @talltydev/cli create my-app --auth

# Or add to existing project
npx @talltydev/cli add auth

This will generate:

  • src/components/auth/ - Authentication components (LoginForm, SignUpForm, etc.)
  • src/hooks/ - Auth hooks (useAuth, useOrganizationManagement)
  • src/client/ - Auth client configuration
  • src/types/ - TypeScript type definitions
  • src/lib/auth.config.ts - Better Auth configuration
  • Auth pages in src/app/auth/

4. Using Generated Components

// app/auth/page.tsx
import { LoginForm } from '@/components/auth/login-form'

export default function AuthPage() {
  return (
    <div className="max-w-md mx-auto mt-8">
      <LoginForm
        enablePhoneLogin={true}
        onSuccess={(response) => {
          console.log('Logged in:', response.user)
          // Redirect to dashboard
        }}
        onError={(error) => {
          console.error('Login failed:', error)
        }}
      />
    </div>
  )
}

5. Route Protection

// app/dashboard/page.tsx
import { AuthGuard } from '@/components/auth/auth-guard'

export default function DashboardPage() {
  return (
    <AuthGuard
      requireRoles={['teacher', 'admin']}
      requireOrganization={true}
    >
      <div>
        <h1>Dashboard</h1>
        <p>Only teachers and admins in an organization can see this!</p>
      </div>
    </AuthGuard>
  )
}

API Reference

Components

<AuthProvider>

React context provider for authentication state.

interface AuthProviderProps {
  children: React.ReactNode
  config?: AuthClientConfig
}

<LoginForm>

Email/password and phone number authentication form.

interface LoginFormProps {
  onSuccess?: (response: AuthResponse) => void
  onError?: (error: AuthError) => void
  enablePhoneLogin?: boolean
  className?: string
  children?: React.ReactNode
}

<SignUpForm>

User registration form with role selection.

interface SignUpFormProps {
  onSuccess?: (response: AuthResponse) => void
  onError?: (error: AuthError) => void
  enablePhoneSignup?: boolean
  className?: string
  children?: React.ReactNode
}

<AuthGuard>

Route protection component with role-based access control.

interface AuthGuardProps {
  children: React.ReactNode
  fallback?: React.ReactNode
  requireRoles?: UserRole[]
  requireOrganization?: boolean
}

<OrganizationSwitcher>

Dropdown for switching between user organizations.

interface OrganizationSwitcherProps {
  className?: string
  onOrganizationChange?: (organization: Organization) => void
}

Hooks

useAuth()

Primary authentication hook with sign in/out methods.

const {
  user,
  session,
  isAuthenticated,
  signIn,
  signUp,
  signOut,
  verifyOtp,
  isSigningIn,
  error
} = useAuth()

useEnhancedSession()

Enhanced session management with auto-refresh.

const {
  user,
  session,
  refresh,
  isRefreshing
} = useEnhancedSession()

useOrganizationManagement()

Organization and role management utilities.

const {
  organizations,
  activeOrganization,
  setActiveOrganization,
  canManageOrganization,
  canAdminOrganization
} = useOrganizationManagement()

Configuration Factories

createAuth(config)

Creates Better Auth server instance with pre-configured plugins.

interface AuthConfig {
  database: DatabaseConfig
  emailProvider?: EmailProviderConfig
  smsProvider?: SmsProviderConfig
  sessionConfig?: SessionConfig
  roleConfig?: RoleConfig
  organizationConfig?: OrganizationConfig
  phoneNumberConfig?: PhoneNumberConfig
}

createAuthClient(baseUrl?, options?)

Creates Better Auth client instance for React applications.

interface AuthClientConfig {
  baseUrl?: string
  fetchOptions?: RequestInit
}

ZenStack Integration

The package provides utilities for integrating with ZenStack's access control system:

// lib/zenstack.ts
import { createAuthContext } from '@talltydev/auth/zenstack'
import { enhance } from '@zenstackhq/runtime'
import { prisma } from './prisma'

export function getEnhancedPrisma(user: User, activeOrganization: Organization) {
  const authContext = createAuthContext(user, null, activeOrganization)

  return enhance(prisma, {
    user: authContext
  })
}

Use in your ZenStack schema:

model Post {
  id String @id @default(cuid())
  title String
  content String
  authorId String
  organizationId String

  author User @relation(fields: [authorId], references: [id])
  organization Organization @relation(fields: [organizationId], references: [id])

  // Only organization members can read posts
  @@allow('read', auth().activeOrganization.id == organizationId)

  // Only teachers and above can create posts
  @@allow('create',
    auth().activeOrganization.id == organizationId &&
    auth().organizationRole in ['teacher', 'manage', 'admin']
  )

  // Authors and admins can update their posts
  @@allow('update', auth().id == authorId || auth().organizationRole == 'admin')
}

Environment Variables

# Required
BETTER_AUTH_SECRET=your-secret-key
DATABASE_URL=postgresql://user:pass@localhost:5432/db

# Optional
EMAIL_API_KEY=your-email-service-key
SMS_API_KEY=your-sms-service-key
SMS_API_URL=https://api.yourprovider.com/sms
REDIS_URL=redis://localhost:6379

Copy Components

When using the copy-components approach, components are installed into your project for full customization:

# Available components
tallty add auth-login          # LoginForm
tallty add auth-signup         # SignUpForm
tallty add auth-provider       # AuthProvider
tallty add auth-guard          # AuthGuard
tallty add org-switcher        # OrganizationSwitcher
tallty add password-reset      # PasswordResetForm
tallty add phone-verification  # PhoneVerificationForm
tallty add profile-form        # ProfileForm

Components are installed to src/components/auth/ by default and include:

  • TypeScript source code
  • Usage examples
  • Dependency documentation
  • Installation instructions

Framework Compatibility

The package is optimized for:

  • Next.js 14+ (App Router and Pages Router)
  • React 18+
  • TypeScript 5+
  • Tailwind CSS (required for styling)

Framework-specific features:

  • Automatic "use client" directives for Next.js
  • SSR-safe session handling
  • API route integration
  • Middleware support for route protection

Development

Local Development

# Install dependencies
pnpm install

# Build the package
pnpm build

# Run tests
pnpm test

# Development mode with watch
pnpm dev

# Link for local testing
pnpm yalc:publish

Testing with YALC

# In the auth package
pnpm yalc:publish

# In your project
yalc add @talltydev/auth

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if needed
  5. Submit a pull request

License

MIT License - see LICENSE for details.

Support