> ## Documentation Index
> Fetch the complete documentation index at: https://docs.limitly.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js SDK Authentication

> Learn how to authenticate with the Limitly API using the Next.js SDK

The Limitly Next.js SDK uses API key authentication to interact with the Limitly API.

## API Key Setup

To use the SDK, you need a Limitly API key. You can get one from your [Limitly Dashboard](https://app.limitly.com).

## Basic Authentication

Initialize the SDK with your API key:

```typescript theme={null}
import { Limitly } from '@limitly/limitly-nextjs';

const limitly = new Limitly({
  apiKey: 'lk_1234567890abcdef'
});
```

## Environment Variables

For security, store your API key in environment variables:

```bash theme={null}
# .env.local
LIMITLY_API_KEY=lk_1234567890abcdef
```

Then use it in your application:

```typescript theme={null}
import { Limitly } from '@limitly/limitly-nextjs';

const limitly = new Limitly({
  apiKey: process.env.LIMITLY_API_KEY!
});
```

## API Route Example

Here's how to use authentication in a Next.js API route:

```typescript theme={null}
// app/api/users/route.ts
import { Limitly } from '@limitly/limitly-nextjs';

const limitly = new Limitly({
  apiKey: process.env.LIMITLY_API_KEY!
});

export async function GET(request: Request) {
  const apiKey = request.headers.get('authorization')?.replace('Bearer ', '');
  
  if (!apiKey) {
    return Response.json({ error: 'API Key required' }, { status: 401 });
  }

  const result = await limitly.validation.validate(
    apiKey,
    '/api/users',
    'GET'
  );

  if (!result.success) {
    return Response.json({ error: 'Rate limit exceeded' }, { status: 429 });
  }

  return Response.json({ message: 'Request allowed' });
}
```

## Error Handling

The SDK provides comprehensive error handling:

```typescript theme={null}
import { Limitly } from '@limitly/limitly-nextjs';

const limitly = new Limitly({
  apiKey: process.env.LIMITLY_API_KEY!
});

try {
  const result = await limitly.validation.validate(
    'user_api_key',
    '/api/users',
    'GET'
  );
  
  if (result.success) {
    console.log('Request allowed');
  } else {
    console.log('Request denied:', result.error);
  }
} catch (error) {
  console.error('Authentication error:', error);
}
```

## Next Steps

* [Request Validation](/sdk/nextjs/validation) - Validate user requests
* [Middleware](/sdk/nextjs/middleware) - Use built-in middleware for API routes
* [API Key Management](/sdk/nextjs/api-keys) - Manage API keys for your users
