# Centinel Analytica Next.js Integration

Bot protection middleware for Next.js applications.

## Installation

```bash
npm install @centinel/nextjs
```

## Setup

### 1. Environment Variables

Add your Centinel keys to `.env`:

```
CENTINEL_SITE_KEY=your_site_key_here
CENTINEL_SECRET_KEY=your_secret_key_here
NEXT_PUBLIC_CENTINEL_SITE_KEY=your_site_key_here
```

**Note:** Use `CENTINEL_SITE_KEY` for server-side code (layouts, middleware). Use `NEXT_PUBLIC_CENTINEL_SITE_KEY` if using CentinelLayout in client-side pages.

### 2. Client Script

Add the CentinelLayout to your root layout:

```typescript
// app/layout.tsx (server-side)
import { CentinelLayout } from '@centinel/nextjs';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <CentinelLayout siteKey={process.env.CENTINEL_SITE_KEY!}>
          {children}
        </CentinelLayout>
      </body>
    </html>
  );
}
```

Or if using in a client-side page:

```typescript
// app/page.tsx (client-side)
'use client';
import { CentinelLayout } from '@centinel/nextjs';

export default function HomePage(): JSX.Element {
  return (
    <CentinelLayout siteKey={process.env.NEXT_PUBLIC_CENTINEL_SITE_KEY!}>
      {/* Your page content */}
    </CentinelLayout>
  );
}
```

### 3. Protection

Choose between automatic middleware or manual validation:

#### Option A: Middleware (Recommended)

Create `middleware.ts` in your project root:

```typescript
import { createCentinelMiddlewareFromEnv } from '@centinel/nextjs';

export default createCentinelMiddlewareFromEnv();

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

#### Option B: Manual Validation

Use in specific API routes when middleware isn't suitable:

```typescript
// app/api/login/route.ts
import { createRequestValidatorFromEnv } from '@centinel/nextjs';
import { NextRequest, NextResponse } from 'next/server';

const { isBot } = createRequestValidatorFromEnv();

export async function POST(request: NextRequest) {
  if (await isBot(request)) {
    return NextResponse.json({ error: 'Blocked' }, { status: 403 });
  }
  return handleLogin(request);
}
```

Or with custom configuration:

```typescript
// app/api/protected/route.ts
import { createRequestValidator } from '@centinel/nextjs';
import { NextRequest, NextResponse } from 'next/server';

const { isBot } = createRequestValidator({
  siteKey: 'your_site_key',
  secretKey: 'your_secret_key'
});

export async function POST(request: NextRequest) {
  if (await isBot(request)) {
    return NextResponse.json({ error: 'Access denied' }, { status: 403 });
  }
  
  // Your protected logic
}
```

## Advanced Configuration

### Custom Configuration

Pass config directly instead of using environment variables:

```typescript
import { createCentinelMiddleware } from '@centinel/nextjs';

export default createCentinelMiddleware({
  siteKey: 'your_site_key',
  secretKey: 'your_secret_key'
});
```

### Route Matching

Specify which routes to protect:

```typescript
export const config = {
  matcher: [
    '/api/:path*',        // All API routes
    '/dashboard/:path*',  // Dashboard pages
    '/admin/:path*'       // Admin area
  ]
};
```

## How It Works

Centinel validates each request before it reaches your application. Suspicious requests are blocked or redirected to a verification page. The client script helps distinguish legitimate users from bots.

**Note:** Blocked requests are redirected to `/block` by default. Create this page in your app or customize the redirect URL in your middleware configuration.