# Next.js Integration

Spyglasses integrates seamlessly with Next.js applications through our official package. Follow these steps to set up Spyglasses in your Next.js project.

## Installation

1. **Install the package**:
   ```bash
   npm install @spyglasses/next
   ```

   with yarn:
   ```
   yarn add @spyglasses/next
   ```

   with pnpm:
   ```
   pnpm add @spyglasses/next
   ```

2. **Add your API key**:
   Create or update your `.env.local` file with your Spyglasses API key:
   ```env
   SPYGLASSES_API_KEY=your_api_key_here
   ```

## Configuration

Create or update your `middleware.ts` file in the root of your project:

```typescript

  apiKey: process.env.SPYGLASSES_API_KEY,
  // Optional: override collector endpoint
  collectorEndpoint: process.env.SPYGLASSES_COLLECTOR_ENDPOINT,
  // Optional: enable debug logging
  debug: process.env.NODE_ENV === 'development'
});

// Configure matchers for the middleware

  matcher: [
    // Spyglasses matchers
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}
```

## Docker

If you deploy with Docker, set your API key in your Dockerfile or docker-compose:

**Dockerfile:**
```dockerfile
ENV SPYGLASSES_API_KEY=your_api_key_here
```

**docker-compose:**
```yaml
services:
  web:
    environment:
      - SPYGLASSES_API_KEY=your_api_key_here
```

## Environment Variables at Runtime

For platforms that inject environment variables at runtime, you can reference them directly in your middleware:

```typescript:middleware.ts

  apiKey: process.env.SPYGLASSES_API_KEY,
  collectorEndpoint: process.env.SPYGLASSES_COLLECTOR_ENDPOINT,
  debug: process.env.NODE_ENV === 'development'
});
```

## Wrapping Existing Middleware

If you have existing middleware, you can compose it with Spyglasses in two ways:

### 1. Middleware Chaining (Recommended)

```typescript

const spyglassesMiddleware = createSpyglassesMiddleware({
  apiKey: process.env.SPYGLASSES_API_KEY,
})

async function existingMiddleware(request: NextRequest) {
  // Your custom logic here
  return NextResponse.next()
}

  // Run Spyglasses middleware first
  await spyglassesMiddleware(request);
  // Then run your middleware
  return existingMiddleware(request)
}

  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
    '/protected/:path*',
  ],
}
```

### 2. Middleware Composition (Advanced)

```typescript

const spyglassesMiddleware = createSpyglassesMiddleware({
  apiKey: process.env.SPYGLASSES_API_KEY,
})

async function existingMiddleware(request: NextRequest) {
  // Your custom logic here
  return NextResponse.next()
}

  // Run both middlewares in sequence
  const [spyglassesResponse, existingResponse] = await Promise.all([
    spyglassesMiddleware(request),
    existingMiddleware(request),
  ])

  if (spyglassesResponse?.status === 403) {
    return spyglassesResponse // Block bot traffic
  }
  if (existingResponse?.status === 401) {
    return existingResponse // Handle unauthorized access
  }
  return NextResponse.next()
}

  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
    '/protected/:path*',
  ],
}
```

> **Tip:** Use chaining unless you know you need composition.

## Deployment

When deploying your Next.js application, make sure to add your Spyglasses API key to your environment variables:

### Vercel
- Go to Project Settings > Environment Variables
- Add `SPYGLASSES_API_KEY`
- Deploy to apply changes

### Netlify
- Go to Site Settings > Build & Deploy > Environment
- Add `SPYGLASSES_API_KEY`
- Trigger a new deploy

### AWS Amplify
- Go to App Settings > Environment Variables
- Add `SPYGLASSES_API_KEY`
- Redeploy your application

## Verifying Installation

After deploying your application with Spyglasses, you can verify the installation by checking your Spyglasses dashboard. If everything is set up correctly, you should start seeing data from your Next.js application.

## Troubleshooting

### API Key Not Found
- Verify environment variable is set
- Check for typos in variable name
- Ensure deployment includes environment variables

### Middleware Not Running
- Confirm `middleware.ts` is in the correct location
- Check matcher configuration
- Verify Next.js version (13.0.0 or higher required)

### Performance Issues
- Enable debug mode to check for errors
- Verify matcher configuration isn't too broad
- Check network latency to collector endpoint

If you're not seeing data in your Spyglasses dashboard:
1. Verify your API key is correct
2. Check that the middleware is properly configured
3. Ensure your deployment includes the environment variables
4. Check your browser console for any errors

Need help? Contact support@spyglasses.io
