@auth-ezz/nextjs
v1.1.0
Published
A secure, high-performance authentication SDK designed specifically for modern Next.js applications using the App Router. Built on HTTP-only cookies and server-side session validation for maximum security.
Readme
@ezz-auth/next
A secure, high-performance authentication SDK designed specifically for modern Next.js applications using the App Router. Built on HTTP-only cookies and server-side session validation for maximum security.
✨ Features
- 🔒 Zero Token Exposure - Authentication tokens never reach the client-side
- 🚀 Next.js Optimized - Deep integration with App Router, Server Components, and Middleware
- 🛡️ Session-Based - Robust session management without complex token handling
- ⚡ Edge Ready - Lightweight middleware for edge deployment
- 🎯 TypeScript First - Full TypeScript support with comprehensive type definitions
- 🧩 Framework Agnostic - Works with any React-based Next.js application
📦 Installation
npm install @ezz-auth/next🚀 Quick Start
1. Environment Setup
Add to your .env:
# Core Auth System URL
AUTH_BASE_URL=https://auth.your-domain.com
# Your Application Credentials
AUTH_APP_KEY=your_public_key
AUTH_APP_SECRET=your_secret_key2. Initialize Routes
npx auth-ezz initThis creates the necessary API routes for authentication callbacks.
3. Protect Your App
// app/layout.tsx
import { AuthProvider } from "@ezz-auth/next/client";
import { auth } from "@ezz-auth/next/server";
export default async function RootLayout({ children }) {
const { user } = await auth();
return (
<html>
<body>
<AuthProvider initialUser={user}>
{children}
</AuthProvider>
</body>
</html>
);
}// app/dashboard/page.tsx
import { auth } from "@ezz-auth/next/server";
import { redirect } from "next/navigation";
export default async function Dashboard() {
const { user } = await auth();
if (!user) {
redirect("/");
}
return <h1>Welcome, {user.name}!</h1>;
}📚 API Reference
Client-Side API
AuthProvider
Context provider that manages authentication state across your React application.
import { AuthProvider } from "@ezz-auth/next/client";
<AuthProvider initialUser={user}>
<App />
</AuthProvider>Props:
initialUser(optional): Initial user object from server-side authchildren: React components to render
useUser()
React hook to access the current authenticated user in client components.
import { useUser } from "@ezz-auth/next/client";
function Profile() {
const { user, isSignedIn, isLoaded } = useUser();
if (!isLoaded) return <div>Loading...</div>;
if (!isSignedIn) return <div>Please sign in</div>;
return <div>Hello, {user.name}!</div>;
}Returns:
user: Current user object ornullisSignedIn: Boolean indicating authentication statusisLoaded: Boolean indicating if auth state has been determined
SignInButton
Pre-built component that redirects users to the authentication flow.
import { SignInButton } from "@ezz-auth/next/client";
<SignInButton />Props: None (customizable via CSS classes)
UserButton
Component that displays user information and provides logout functionality.
import { UserButton } from "@ezz-auth/next/client";
<UserButton />Props: None (customizable via CSS classes)
signOut()
Function to sign out the current user and clear their session.
import { signOut } from "@ezz-auth/next/client";
function handleLogout() {
signOut();
// User will be redirected and session cleared
}Server-Side API
auth()
Primary server-side function to authenticate requests and get user data.
import { auth } from "@ezz-auth/next/server";
export default async function ProtectedPage() {
const { user, session } = await auth();
if (!user) {
redirect("/login");
}
return <div>User: {user.email}</div>;
}Returns:
user: User object ornullsession: Session object ornull
currentUser()
Simplified function that returns only the current user (alias for auth().user).
import { currentUser } from "@ezz-auth/next/server";
const user = await currentUser();Returns: User object or null
requireAuth()
Throws an error if user is not authenticated. Useful for protecting API routes.
import { requireAuth } from "@ezz-auth/next/server";
export async function GET() {
const { user } = await requireAuth();
// User is guaranteed to be authenticated here
return Response.json({ data: "protected content" });
}Options:
state(optional): Custom state to pass through auth flow
Returns: Object with user and session (throws if unauthenticated)
handleAuthCallback()
Route handler for processing OAuth callbacks after authentication.
// app/api/auth/callback/route.ts
import { handleAuthCallback } from "@ezz-auth/next/server";
export const GET = handleAuthCallback({
redirectTo: "/dashboard"
});Options:
redirectTo(optional): Where to redirect after successful authentication (default: "/")
handleLogout()
Route handler for processing logout requests.
// app/api/auth/logout/route.ts
import { handleLogout } from "@ezz-auth/next/server";
export const POST = handleLogout();Middleware API
authMiddleware()
Next.js middleware for protecting routes at the edge.
// middleware.ts
import { authMiddleware } from "@ezz-auth/next/middleware";
export default authMiddleware();
export const config = {
matcher: ["/dashboard/:path*"]
};Returns: Next.js middleware function
CLI API
ezz-auth init
Scaffolds the necessary authentication routes for your Next.js application.
npx ezz-auth initCreates:
app/api/auth/callback/route.ts- OAuth callback handlerapp/api/auth/logout/route.ts- Logout handler
🔧 Configuration
Environment Variables
| Variable | Description | Required |
|----------|-------------|----------|
| AUTH_BASE_URL | URL of your Ezz Auth core system | ✅ |
| AUTH_APP_KEY | Public application key from developer console | ✅ |
| AUTH_APP_SECRET | Secret application key for server-side operations | ✅ |
Advanced Configuration
The SDK automatically detects your Next.js app directory structure:
src/app/(ifsrcdirectory exists)app/(standard App Router location)
📝 Examples
Complete App Setup
// app/layout.tsx
import { AuthProvider } from "@ezz-auth/next/client";
import { auth } from "@ezz-auth/next/server";
export default async function Layout({ children }) {
const { user } = await auth();
return (
<html>
<body>
<AuthProvider initialUser={user}>
<Header />
{children}
</AuthProvider>
</body>
</html>
);
}
// app/components/Header.tsx
"use client";
import { SignInButton, UserButton, useUser } from "@ezz-auth/next/client";
export function Header() {
const { isSignedIn } = useUser();
return (
<header>
<nav>
<Link href="/">Home</Link>
{isSignedIn ? <UserButton /> : <SignInButton />}
</nav>
</header>
);
}API Route Protection
// app/api/user/profile/route.ts
import { auth } from "@ezz-auth/next/server";
export async function GET() {
const { user } = await auth();
if (!user) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
return Response.json({ profile: user });
}Middleware Protection
// middleware.ts
import { authMiddleware } from "@ezz-auth/next/middleware";
export default authMiddleware();
export const config = {
matcher: ["/dashboard/:path*", "/api/protected/:path*"]
};🔄 How It Works
- Authorization Request: User clicks sign-in, SDK redirects to Ezz Auth core with your
AUTH_APP_KEY - User Authentication: Core system handles login via configured providers (OAuth, email, etc.)
- Callback Processing: Core redirects back with authorization code
- Token Exchange: Your app exchanges code for session token using
AUTH_APP_SECRET - Session Storage: Session stored in HTTP-only, secure, SameSite=Lax cookie
- Request Validation: Each request validates cookie against core introspection endpoint
🛡️ Security Features
- No Token Exposure: Authentication tokens never reach client-side JavaScript
- HTTP-Only Cookies: Session cookies cannot be accessed via JavaScript
- Secure by Default: Automatic security headers and cookie configuration
- Server-Side Validation: All authentication checks happen server-side
- CSRF Protection: Built-in protection against cross-site request forgery
🐛 Troubleshooting
Common Issues
"No app directory found"
- Ensure you're using Next.js App Router (not Pages Router)
- Check that your app directory is at
app/orsrc/app/
"Authentication failed"
- Verify
AUTH_BASE_URLis correct and accessible - Check that
AUTH_APP_KEYandAUTH_APP_SECRETare valid - Ensure callback URL is configured in your auth provider
"Session not persisting"
- Check that cookies are enabled in the browser
- Verify your domain configuration matches the auth core
📄 License
MIT © [Your Organization]
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
