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 🙏

© 2026 – Pkg Stats / Ryan Hefner

saas-factory-auth

v0.1.0

Published

Authentication and session management for Next.js applications

Readme

@saas-factory/auth

Complete authentication and session management package for Next.js applications. Supports session-based authentication with cookies and OAuth integration (Google, GitHub, etc.).

Features

  • Dual Authentication: Session-based (cookies) + JWT token support
  • OAuth Integration: Google, GitHub, and extensible for other providers
  • Secure Sessions: httpOnly cookies with CSRF protection
  • API Route Handlers: Ready-to-use authentication endpoints
  • React Hooks: useAuth(), useUser() hooks for client components
  • Server-Side Auth: getSession() for API routes and server components
  • Role-Based Access Control (RBAC): Built-in role and permission system
  • Password Security: bcrypt hashing with salting
  • Rate Limiting: Brute force attack prevention on login
  • Type-Safe: Full TypeScript support with types included
  • Database Agnostic: Works with any database via adapters (Prisma, Mongoose, etc.)

Installation

npm install @saas-factory/auth
# or
pnpm add @saas-factory/auth

Quick Start

1. Environment Setup

Create .env.local:

# Auth secrets
AUTH_SECRET=your-random-secret-key-here
SESSION_SECRET=another-random-secret-key

# OAuth (optional)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret

Generate secrets:

openssl rand -base64 32

2. Set Up API Routes

Create app/api/auth/[...auth]/route.ts:

import { createAuthHandler } from '@saas-factory/auth';
import { NextRequest } from 'next/server';

export const { GET, POST } = createAuthHandler({
  secret: process.env.AUTH_SECRET,
  providers: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    },
    github: {
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    },
  },
});

3. Get Session in Server Components

import { getSession } from '@saas-factory/auth';

export default async function Dashboard() {
  const session = await getSession();
  
  if (!session) {
    redirect('/auth/signin');
  }
  
  return <div>Welcome, {session.user.name}!</div>;
}

4. Use Auth Hook in Client Components

'use client';

import { useAuth } from '@saas-factory/auth';

export function UserMenu() {
  const { user, isLoading, logout } = useAuth();
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      <p>Hello, {user?.name}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

5. Protect Routes with Middleware

Create middleware.ts in your root:

import { withAuth } from '@saas-factory/auth';

export const middleware = withAuth(async (req) => {
  // Your custom middleware logic here
});

export const config = {
  matcher: ['/dashboard/:path*', '/settings/:path*'],
};

API Reference

createAuthHandler(config)

Creates Next.js API route handlers for authentication.

Config Options:

{
  secret: string;                    // Auth secret key
  providers?: {
    google?: OAuthConfig;
    github?: OAuthConfig;
    [key: string]: OAuthConfig;
  };
  database?: DatabaseAdapter;        // Custom DB adapter
  sessionOptions?: SessionConfig;
  rateLimiting?: RateLimitConfig;
}

getSession()

Server-side function to get current session in API routes or server components.

const session = await getSession();
// Returns: { user: { id, email, name, role }, expiresAt }

useAuth()

Client-side hook for authentication state.

const { 
  user,           // Current user object
  isLoading,      // Loading state
  isAuthenticated,// Boolean
  login,          // Manual login function
  logout,         // Logout function
  error           // Error message if any
} = useAuth();

withAuth(middleware)

Higher-order function to protect routes.

export const middleware = withAuth(async (req) => {
  // req.auth contains session info
  console.log(req.auth.user);
});

Authentication Flows

Session-Based Flow (Default)

  1. User submits credentials
  2. Server validates and creates session
  3. Session stored in httpOnly cookie
  4. Cookie sent on every request
  5. Server validates cookie on each request

OAuth Flow

  1. User clicks "Sign in with Google/GitHub"
  2. Redirected to OAuth provider
  3. User authorizes
  4. Provider redirects back with auth code
  5. Server exchanges code for tokens
  6. Session created with user data

Advanced Usage

Custom Database Adapter

import { createAuthHandler } from '@saas-factory/auth';

const customAdapter = {
  async findUser(email: string) {
    // Your DB logic
  },
  async createUser(data: UserData) {
    // Your DB logic
  },
  async updateSession(userId: string, sessionData: any) {
    // Your DB logic
  },
};

export const { GET, POST } = createAuthHandler({
  secret: process.env.AUTH_SECRET,
  database: customAdapter,
});

Role-Based Access Control

import { withRoleAuth } from '@saas-factory/auth';

export const middleware = withRoleAuth(['admin', 'moderator'])(
  async (req) => {
    // Only admin and moderator roles can access
  }
);

Custom Sign In Page

// app/auth/signin/page.tsx
import { SignInForm } from '@saas-factory/auth/components';

export default function SignInPage() {
  return (
    <div>
      <h1>Welcome Back</h1>
      <SignInForm />
    </div>
  );
}

Password Hashing

import { hashPassword, verifyPassword } from '@saas-factory/auth/utils';

// Hash password
const hashed = await hashPassword('user-password');

// Verify password
const isValid = await verifyPassword('user-password', hashed);

Database Setup

With Prisma

model User {
  id        String    @id @default(cuid())
  email     String    @unique
  name      String?
  password  String?   // null if OAuth only
  role      String    @default("user")
  sessions  Session[]
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

model Session {
  id        String   @id @default(cuid())
  userId    String
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  token     String   @unique
  expiresAt DateTime
  createdAt DateTime @default(now())
}

Security Best Practices

  • Always use HTTPS in production
  • Set AUTH_SECRET to a strong random value
  • Use httpOnly cookies (enabled by default)
  • Implement rate limiting on login endpoints
  • Validate all user input
  • Keep session duration reasonable (default: 7 days)
  • Rotate session tokens on privilege escalation
  • Use CSRF protection for forms

Troubleshooting

Session not persisting?

  • Check if cookies are enabled
  • Verify AUTH_SECRET is set
  • Ensure middleware is configured correctly
  • Check browser's cookie settings in DevTools

OAuth not working?

  • Verify client ID and secret are correct
  • Check redirect URI matches provider settings
  • Ensure environment variables are loaded
  • Check browser console for errors

Rate limiting too strict?

  • Adjust maxAttempts and windowMs in config
  • Implement whitelist for specific IPs if needed

Examples

See the examples folder for complete working applications:

  • Example 1: Basic sign in/sign up
  • Example 2: OAuth with social login
  • Example 3: Protected dashboard with roles

Contributing

See CONTRIBUTING.md for development guidelines.

License

MIT - See LICENSE in root directory