saas-factory-auth
v0.1.0
Published
Authentication and session management for Next.js applications
Maintainers
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/authQuick 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-secretGenerate secrets:
openssl rand -base64 322. 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)
- User submits credentials
- Server validates and creates session
- Session stored in httpOnly cookie
- Cookie sent on every request
- Server validates cookie on each request
OAuth Flow
- User clicks "Sign in with Google/GitHub"
- Redirected to OAuth provider
- User authorizes
- Provider redirects back with auth code
- Server exchanges code for tokens
- 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_SECRETto 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_SECRETis 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
maxAttemptsandwindowMsin 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
