React & Next.js

Next.js Integration

Official Next.js SDK (@authsetu/nextjs) for App Router authentication, route protection middleware, and server guards.


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:

bash
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.

tsx
// 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>
  );
}

Note

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.

typescript
// 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).*)",
  ],
};

Tip

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

typescript
// 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" };
}

---

4. Pre-built Next.js UI Pages

Add pre-built sign-in and sign-up pages using AuthSetu components:

tsx
// 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>
  );
}

tsx
// 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>
  );
}


Was this page helpful?