---
title: "Next.js Integration"
description: "Comprehensive guide to integrating AuthSetu with Next.js App Router, edge middleware, and server actions."
order: 2
category: "Getting Started"
updated: "2026-10-13"
---

# Next.js Integration

AuthSetu provides first-class support for the Next.js App Router (versions 14, 15, and 16+), including edge middleware protection, server components, and authenticated server actions.

## Installation

```bash
pnpm add @authsetu/nextjs @authsetu/react
```

## Edge Route Protection via Middleware

Protect your dashboard and private routes using `authMiddleware`:

```typescript
// middleware.ts
import { authMiddleware } from '@authsetu/nextjs/server';

export default authMiddleware({
  publicRoutes: [
    '/',
    '/pricing',
    '/features',
    '/sign-in',
    '/sign-up',
    '/api/revalidate',
  ],
  loginUrl: '/sign-in',
});

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
```

## Accessing Current User in Server Components

Use `currentUser()` or `auth()` in React Server Components:

```tsx
// app/dashboard/page.tsx
import { currentUser } from '@authsetu/nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const user = await currentUser();

  if (!user) {
    redirect('/sign-in');
  }

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold">Welcome, {user.name}!</h1>
      <p className="text-muted-foreground">{user.email}</p>
    </div>
  );
}
```

## Client-Side Authentication State

In Client Components, use the `useAuth()` hook:

```tsx
'use client';

import { useAuth } from '@authsetu/react';

export function UserGreeting() {
  const { user, isLoaded, isSignedIn, signOut } = useAuth();

  if (!isLoaded) return <div>Loading session...</div>;
  if (!isSignedIn) return <a href="/sign-in">Sign In</a>;

  return (
    <div className="flex items-center gap-4">
      <span>Hello, {user.email}</span>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}
```
