npm package: @personql/nextjs
Description: PersonQL SDK optimized for Next.js applications
Author: PersonQL
Latest version: 1.0.7

# PersonQL Next.js SDK

A comprehensive Next.js SDK for PersonQL authentication, user management, and Customer Data Platform (CDP) with automatic digital fingerprinting.

## 🎯 Why a Dedicated Next.js SDK?

While Next.js **can** use our existing React SDK, this dedicated Next.js SDK provides:

### ✅ **Automatic SSR/Hydration Handling**

- No client/server state mismatches
- Seamless authentication state across server and client
- Prevents hydration errors

### ✅ **Built-in Route Protection**

- Middleware-based authentication
- Automatic redirects for protected routes
- Role-based access control

### ✅ **Server Components Support**

- Full Next.js 13+ App Router integration
- Server-side user data fetching
- Optimized performance

### ✅ **Advanced Session Management**

- Unified session across client/server
- Automatic token refresh
- Secure cookie handling

## 🚀 Quick Start

### Installation

```bash
npm install @personql/nextjs
```

### Basic Setup

```typescript
// app/layout.tsx
import { PersonQLProvider } from '@personql/nextjs';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PersonQLProvider
          apiKey={process.env.NEXT_PUBLIC_PERSONQL_API_KEY!}
        >
          {children}
        </PersonQLProvider>
      </body>
    </html>
  );
}
```

// All requests will use the gateway-worker URL automatically.

### Automatic Route Protection

```typescript
// middleware.ts
import { createAuthMiddleware } from '@personql/nextjs';

export const middleware = createAuthMiddleware({
  apiKey: process.env.PERSONQL_API_KEY!,
  publicRoutes: ['/', '/about', '/contact'],
  authRoutes: ['/login', '/signup'],
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
```

### Server Components

```typescript
// app/profile/page.tsx
import { getServerUser } from '@personql/nextjs';
import { redirect } from 'next/navigation';

export default async function ProfilePage() {
  const user = await getServerUser();

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

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

### Client Components

```typescript
// components/UserProfile.tsx
'use client';
import { usePersonQLNext } from '@personql/nextjs';

export function UserProfile() {
  const { user, isAuthenticated, isHydrated, trackEvent } = usePersonQLNext();

  if (!isHydrated) {
    return <div>Loading...</div>;
  }

  const handleProfileUpdate = async () => {
    await trackEvent('Profile Updated', { userId: user?.id });
  };

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <h2>Hello, {user?.name}</h2>
          <button onClick={handleProfileUpdate}>Update Profile</button>
        </div>
      ) : (
        <div>Please log in</div>
      )}
    </div>
  );
}
```

## 📚 Key Features

### 1. SSR-Safe Authentication

```typescript
import { usePersonQLNext } from '@personql/nextjs';

function MyComponent() {
  const { user, isAuthenticated, isHydrated } = usePersonQLNext();

  // Prevents hydration mismatches
  if (!isHydrated) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {isAuthenticated ? `Welcome ${user.name}` : 'Please log in'}
    </div>
  );
}
```

### 2. Automatic Route Protection

```typescript
// Protects routes automatically via middleware
// No need for manual auth checks in components
```

### 3. API Route Helpers

```typescript
// app/api/auth/[...personql]/route.ts
import { createAuthHandler } from '@personql/nextjs';

const handler = createAuthHandler({
  apiKey: process.env.PERSONQL_API_KEY!,
  baseUrl: process.env.PERSONQL_BASE_URL!,
});

export { handler as GET, handler as POST };
```

### 4. Protected API Routes

```typescript
// app/api/profile/route.ts
import { withAuth } from '@personql/nextjs';

export const GET = withAuth(async (request, { user }) => {
  // User is guaranteed to be authenticated
  const profile = await getUserProfile(user.id);
  return Response.json(profile);
});
```

### 5. Automatic Analytics

```typescript
'use client';
import { usePersonQLNext } from '@personql/nextjs';

export default function ProductPage({ product }) {
  const { trackEvent, trackPageView } = usePersonQLNext();

  useEffect(() => {
    // Automatic fingerprinting and page tracking
    trackPageView(`Product: ${product.name}`);
  }, [product]);

  return <div>Product details...</div>;
}
```

## 🔧 Configuration

### Environment Variables

```bash
# Public (client-side)
NEXT_PUBLIC_PERSONQL_API_KEY=your_api_key
NEXT_PUBLIC_PERSONQL_BASE_URL=https://gateway.personql.com

# Private (server-side)
PERSONQL_API_KEY=your_server_api_key
PERSONQL_BASE_URL=https://gateway.personql.com
```

### Advanced Configuration

```typescript
<PersonQLProvider
  apiKey={process.env.NEXT_PUBLIC_PERSONQL_API_KEY!}
  baseUrl={process.env.NEXT_PUBLIC_PERSONQL_BASE_URL!}
  config={{
    cdp: {
      enabled: true,
      database: 'nextjs_analytics',
      autoTracking: true,
      debug: process.env.NODE_ENV === 'development',
    },
    session: {
      cookieName: 'personql_session',
      maxAge: 60 * 60 * 24, // 24 hours
      secure: process.env.NODE_ENV === 'production',
    },
    auth: {
      redirectTo: '/login',
      afterAuthRedirect: '/dashboard',
      publicRoutes: ['/', '/about', '/contact'],
    },
  }}
>
```

## 🆚 Comparison with React SDK

| Feature           | React SDK | Next.js SDK   |
| ----------------- | --------- | ------------- |
| Basic Auth        | ✅        | ✅            |
| SSR Support       | ⚠️ Manual | ✅ Automatic  |
| Route Protection  | ❌ Manual | ✅ Middleware |
| Server Components | ❌        | ✅ Native     |
| Token Refresh     | ⚠️ Manual | ✅ Automatic  |
| Session Sync      | ❌        | ✅ Unified    |
| Edge Runtime      | ❌        | ✅ Supported  |

## 📖 Migration Guide

### From React SDK

1. **Install Next.js SDK**

   ```bash
   npm install @personql/nextjs
   npm uninstall @personql/react
   ```

2. **Update Imports**

   ```typescript
   // Before
   import { PersonQLProvider, useAuth } from '@personql/react';

   // After
   import { PersonQLProvider, usePersonQLNext } from '@personql/nextjs';
   ```

3. **Add Middleware** (Optional)

   ```typescript
   // middleware.ts - New capability!
   import { createAuthMiddleware } from '@personql/nextjs';

   export const middleware = createAuthMiddleware({
     apiKey: process.env.PERSONQL_API_KEY!,
     baseUrl: process.env.PERSONQL_BASE_URL!,
   });
   ```

4. **Update Hooks**

   ```typescript
   // Before - potential hydration issues
   const { isAuthenticated } = useAuth();

   // After - SSR-safe
   const { isAuthenticated, isHydrated } = usePersonQLNext();

   if (!isHydrated) return <div>Loading...</div>;
   ```

## 🚀 Deployment

Works seamlessly with all Next.js deployment platforms:

- ✅ **Vercel** - Full support with edge functions
- ✅ **Netlify** - Complete integration
- ✅ **Cloudflare Pages** - Optimized for Workers
- ✅ **AWS** - Lambda and edge support
- ✅ **Self-hosted** - Docker and traditional hosting

## 📄 License

MIT License - see LICENSE file for details.

---

**Need help?** Check out our [examples](../examples/nextjs-usage-examples.md) or [contact support](mailto:support@personql.dev).