Next.js Integration Guide (@authsetu/nextjs)
The @authsetu/nextjs SDK provides seamless integration with Next.js App Router, enabling client-side context, middleware route protection, and server component guards.
Installation
Installing @authsetu/nextjs automatically includes @authsetu/react and @authsetu/sdk-core as internal dependencies and re-exports all components, hooks, and types out of the box. You only need to install the single package:
bun add @authsetu/nextjs
# or
npm install @authsetu/nextjs---
1. Provider Setup (app/layout.tsx)
Wrap your root layout in the AuthProvider component to supply authentication context throughout your application.
// app/layout.tsx
import { AuthProvider } from "@authsetu/nextjs";
import "./globals.css";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<AuthProvider
publishableKey={process.env.NEXT_PUBLIC_AUTHSETU_PUBLISHABLE_KEY!}
baseUrl={process.env.NEXT_PUBLIC_AUTHSETU_API_URL || "https://api.authsetu.com"}
>
{children}
</AuthProvider>
</body>
</html>
);
}AuthProvider automatically reads local storage & cookies to restore active user sessions across SSR and client navigation.
---
2. Middleware Route Protection (middleware.ts)
Protect routes automatically before requests reach Server Components using withAuth.
// middleware.ts
import { withAuth } from "@authsetu/nextjs/middleware";
export default withAuth({
publicRoutes: [
"/",
"/sign-in",
"/sign-in/(.*)",
"/sign-up",
"/sign-up/(.*)",
"/auth/forgot-password",
"/auth/reset-password",
],
loginPath: "/sign-in",
});
export const config = {
matcher: [
/*
* Match all request paths except static assets & API routes:
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};Requests to routes not listed in publicRoutes will automatically redirect unauthenticated users to /sign-in.
---
3. Server Components & Server Actions
Use server guards in Server Components or Server Actions to enforce authorization or subscription plan limits.
Assert Plan Feature in Server Action
// app/actions/ai-generate.ts
"use server";
import { assertPlanFeature } from "@authsetu/nextjs";
export async function generateAiReport(userPlan: string) {
// Throws PlanGuardError if the user's plan does not support advanced AI features
assertPlanFeature(userPlan, "aiAnalytics");
// Perform AI generation...
return { success: true, result: "Generated Report" };
}// app/sign-in/[[...sign-in]]/page.tsx
import { SignIn } from "@authsetu/nextjs";
export default function SignInPage() {
return (
<div className="flex min-h-screen items-center justify-center p-4">
<SignIn redirectUrl="/dashboard" />
</div>
);
}// app/sign-up/[[...sign-up]]/page.tsx
import { SignUp } from "@authsetu/nextjs";
export default function SignUpPage() {
return (
<div className="flex min-h-screen items-center justify-center p-4">
<SignUp redirectUrl="/dashboard" />
</div>
);
}