Tutorial

Next.js Integration

Integrate Idenplane into a Next.js App Router project with server components, middleware guards, and API route protection.

Installation

Install the dedicated Next.js SDK — it re-exports the core React SDK's AuthProvider/useAuth from its main entry point, plus server-only helpers under /middleware, /server, and /api sub-paths.

Terminal
npm install idenplane-nextjs

Client-Side Provider

Wrap your app in AuthProvider — the same provider used by the React SDK — inside a client component.

app/providers.tsx
'use client';

import { AuthProvider } from 'idenplane-nextjs';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider
      url="https://auth.example.com"
      realm="my-realm"
      clientId="nextjs-app"
      redirectUri=
    >
      {children}
    </AuthProvider>
  );
}

Middleware — Route Protection

createAuthMiddleware checks a cookie or Bearer token and redirects unauthenticated visitors, but only decodes the JWT locally — it does not verify the signature. Treat it as a first-pass redirect guard, not the authoritative check.

middleware.ts
import { NextResponse } from 'next/server';
import { createAuthMiddleware } from 'idenplane-nextjs/middleware';

const authMiddleware = createAuthMiddleware({
  serverUrl: 'https://auth.example.com',
  realm: 'my-realm',
  clientId: 'nextjs-app',
  protectedPaths: ['/dashboard', '/api/protected'],
  loginPath: '/login',
});

export default function middleware(request) {
  return authMiddleware(request, NextResponse);
}

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

Server Component Auth

getServerUser reads the access-token cookie in a Server Component with no client-side round-trip. It also only decodes the JWT locally — for real authorization decisions (role checks, data access), verify the token first with verifyToken from idenplane-sdk/server.

app/dashboard/page.tsx
import { cookies } from 'next/headers';
import { getServerUser } from 'idenplane-nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const user = await getServerUser(await cookies(), {
    serverUrl: 'https://auth.example.com',
    realm: 'my-realm',
  });

  if (!user) redirect('/login');

  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
}

API Route Protection

withAuthHandler (App Router) validates the Bearer token's signature via JWKS before your handler runs — unlike the middleware and Server Component helpers above, this one is safe to use for authorization decisions on its own.

app/api/protected/data/route.ts
import { withAuthHandler } from 'idenplane-nextjs/api';

export const GET = withAuthHandler(
  {
    serverUrl: 'https://auth.example.com',
    realm: 'my-realm',
    requiredRoles: ['user'],
  },
  (req, user) => Response.json({ message: 'Protected data', user }),
);