Optare v1.0 is now available. Get started →
SDKs
Next.js

Next.js SDK Quick Start

Full-featured authentication for Next.js with App Router, Server Components, and Edge Runtime support.

Installation

npm install @optare/optareid-nextjs

Setup

1. Environment Variables

# .env.local
OPTARE_CLIENT_ID=your-client-id
OPTARE_CLIENT_SECRET=your-client-secret
AUTH_SECRET=your-32-character-secret

2. Create Auth Route Handler

// app/api/auth/[...optare]/route.ts
import { createHandlers } from '@optare/optareid-nextjs';
 
export const { GET, POST } = createHandlers({
  clientId: process.env.OPTARE_CLIENT_ID!,
  clientSecret: process.env.OPTARE_CLIENT_SECRET!,
  secret: process.env.AUTH_SECRET!,
});

3. Add Session Provider

// app/layout.tsx
import { OptareProvider } from '@optare/optareid-nextjs';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <OptareProvider>{children}</OptareProvider>
      </body>
    </html>
  );
}

4. Add Middleware (Optional)

// middleware.ts
import { createMiddleware } from '@optare/optareid-nextjs/middleware';
 
export default createMiddleware({
  secret: process.env.AUTH_SECRET!,
  protectedRoutes: ['/dashboard/*', '/settings/*'],
  publicRoutes: ['/', '/login', '/api/auth/*'],
});
 
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

Server Components

// app/dashboard/page.tsx
import { getSession, hasLicense } from '@optare/optareid-nextjs/server';
import { redirect } from 'next/navigation';
 
export default async function Dashboard() {
  const session = await getSession();
  
  if (!session?.user) {
    redirect('/api/auth/signin');
  }
  
  const hasPremium = await hasLicense('premium-plan');
  
  return (
    <div>
      <h1>Welcome, {session.user.name}</h1>
      {hasPremium && <PremiumFeatures />}
    </div>
  );
}

Client Components

'use client';
import { useOptare, SignInButton, SignOutButton, Authenticated } from '@optare/optareid-nextjs';
 
export function UserNav() {
  const { user, isLoading } = useOptare();
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <nav>
      <Authenticated fallback={<SignInButton>Sign In</SignInButton>}>
        <span>{user?.name}</span>
        <SignOutButton />
      </Authenticated>
    </nav>
  );
}

Available Hooks & Components

Hooks

HookDescription
useOptare()Full session state with signIn/signOut methods
useUser()Just the user object

Components

ComponentDescription
OptareProviderSession context provider
SignInButtonPre-styled sign in button
SignOutButtonPre-styled sign out button
AuthenticatedRenders children only when authenticated
UnauthenticatedRenders children only when NOT authenticated

Server Functions

FunctionDescription
getSession()Get current session
getUser()Get current user
getAccessToken()Get access token for API calls
hasLicense(slug)Check if user has product license
hasEntitlement(name)Check if user has entitlement
hasRole(role)Check if user has role

API Routes

The SDK creates these routes automatically:

RouteMethodDescription
/api/auth/signinGETInitiates OAuth flow
/api/auth/callbackGETHandles OAuth callback
/api/auth/signoutPOSTEnds session
/api/auth/sessionGETReturns current session

Next Steps