@unidir/unidir-nextjs
v1.0.12
Published
The official UniDir SDK for Next.js applications. This SDK provides secure, server-side OpenID Connect (OIDC) authentication using encrypted `httpOnly` cookies.
Readme
@unidir/unidir-nextjs
The official UniDir SDK for Next.js applications. This SDK provides secure, server-side OpenID Connect (OIDC) authentication using encrypted httpOnly cookies.
🚀 Key Features
- Zero-Flicker Auth: Validate sessions in Server Components before the page is sent to the browser.
- Encrypted Sessions: Uses JWE (JSON Web Encryption) to ensure session data is unreadable and tamper-proof.
- App Router Optimized: Built for Next.js 13, 14, and 15, including full support for Middleware and Server Actions.
- Secure by Default: Tokens are exchanged on the server-side, keeping your
clientSecrethidden from the browser.
⚙️ Installation
Install the SDK and its core peer dependencies:
npm install @unidir/unidir-nextjs jose cookie
🛠️ Setup Guide
1. Environment Variables
Create a .env.local file in your project root.
Note:
UNIDIR_SECRETmust be a random string of at least 32 characters.
UNIDIR_DOMAIN=[https://your-tenant.unidir.io](https://your-tenant.unidir.io)
UNIDIR_CLIENT_ID=your_client_id
UNIDIR_CLIENT_SECRET=your_client_secret
UNIDIR_REDIRECT_URI=http://localhost:3000/api/auth/callback
UNIDIR_SECRET='your_32_character_session_secret'2. Initialize the SDK
Create a shared library file to export your UniDir instance. This singleton will be used across your application.
lib/unidir.ts
import { initUniDir } from '@unidir/unidir-nextjs';
export const unidir = initUniDir({
domain: process.env.UNIDIR_DOMAIN!,
clientId: process.env.UNIDIR_CLIENT_ID!,
clientSecret: process.env.UNIDIR_CLIENT_SECRET!,
secret: process.env.UNIDIR_SECRET!,
redirectUri: process.env.UNIDIR_REDIRECT_URI!,
});
### 3. API Route Handler
Create a catch-all route to handle the authentication flow (login, logout, and callback).
**app/api/auth/[unidir]/route.ts**
```typescript
import { unidir } from '@/lib/unidir';
export const GET = unidir.handleAuth();📖 Usage Gallery
Protecting Server Components (HOC)
Use withPageAuthRequired to wrap pages that require authentication. It handles the redirect logic automatically.
app/dashboard/page.tsx
import { unidir } from "@/lib/unidir";
async function Dashboard({ user }: { user: any }) {
return (
<div>
<h1>Protected Dashboard</h1>
<p>Welcome back, {user.name}!</p>
</div>
);
}
export default unidir.withPageAuthRequired(Dashboard);Accessing Auth State on the Client
Wrap your root layout with the UserProvider and use the useUser hook in client components.
app/layout.tsx
import { UserProvider } from "@unidir/unidir-nextjs";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<UserProvider>{children}</UserProvider>
</body>
</html>
);
}components/UserMenu.tsx
"use client";
import { useUser } from "@unidir/unidir-nextjs";
export default function UserMenu() {
const { user, isLoading } = useUser();
if (isLoading) return <span>Loading...</span>;
return user ? (
<a href="/api/auth/logout">Logout</a>
) : (
<a href="/api/auth/login">Login</a>
);
}🔒 Security Architecture httpOnly Cookies: Session tokens are stored in cookies that cannot be accessed via JavaScript (document.cookie), which prevents XSS-based token theft.
Server-Side Exchange: The client_secret is used only on the server to exchange authorization codes for tokens.
Tamper-Proof: Every session is signed and encrypted. If the UNIDIR_SECRET is compromised or the cookie is modified, the session becomes invalid.
📄 API Reference
| Method | Environment | Description |
| :--------------------------- | :--------------- | :---------------------------------------------------- |
| handleAuth() | Server (API) | Main router for /login, /logout, and /callback. |
| getSession(req) | Server (SSR/API) | Returns the decrypted user session. |
| withPageAuthRequired(Comp) | Server (Page) | HOC that redirects unauthenticated users. |
| UserProvider | Client (Layout) | Context provider for client-side state. |
| useUser() | Client (Hook) | Access { user, isLoading, error } in components. |
License
MIT © UniDir
