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

# Authentication

> API authentication methods and security

# API Authentication

All GigaReels API requests require authentication using API keys. This guide covers authentication methods, security best practices, and troubleshooting.

## Authentication Methods

> [card] Bearer Token
>
> Standard HTTP Bearer authentication (recommended)

> [card] CLI Authentication
>
> Automatic credential management for development

## Bearer Token Authentication

### Request Format

Include your API key in the `Authorization` header:

```bash theme={null}
curl -X POST "https://gigareels.com/api/render" \
  -H "Authorization: Bearer your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "educational-brainrot",
    "prompt": "Explain quantum physics",
    "characterPack": "rick-and-morty",
    "backgroundVideoPack": "minecraft-parkour"
  }'
```

### SDK Implementation

The SDK handles authentication automatically:

```javascript theme={null}
import { GigaReels } from "@gigareels/sdk";

// Manual API key
const client = new GigaReels({
	apiKey: "your-api-key-here",
});

// Environment variable
const client = new GigaReels({
	apiKey: process.env.GIGAREELS_API_KEY,
});

// CLI credentials (automatic)
const client = new GigaReels(); // Uses stored credentials
```

## API Key Management

### Getting Your API Key

1. **Log in** to your [GigaReels Dashboard](https://gigareels.com/dashboard)
2. Navigate to **Settings** → **API Keys**
3. Click **Generate New API Key**
4. Copy and securely store your API key

> [!WARNING]
>
> **Security**: API keys provide full access to your account. Never share them publicly or commit
> them to version control.

### Key Properties

**apiKey** `string` *required*

Your unique API key from the dashboard

**format** `string`

Always starts with `giga_` followed by 32 alphanumeric characters

**scope** `string`

Full access to all API endpoints and features

**expiration** `string`

API keys do not expire but can be revoked from the dashboard

## CLI Authentication

### Login Process

```bash theme={null}
# Authenticate via browser
npx @gigareels/sdk login

# For local development
npx @gigareels/sdk login --local
```

The CLI authentication flow:

**1. Browser Authentication**

CLI opens your browser to the GigaReels authentication page

**2. Account Verification**

Log in with your existing account or sign up for a new one

**3. API Key Generation**

System automatically generates an API key for CLI use

**4. Local Storage**

Credentials are stored in `~/.gigareels/credentials.json`

### Checking Authentication Status

```javascript theme={null}
import { GigaReels } from "@gigareels/sdk";

// Check if CLI authentication exists
const isLoggedIn = await GigaReels.isLoggedIn();
console.log("Authenticated:", isLoggedIn);
```

### Logout

```bash theme={null}
# Clear stored credentials
npx @gigareels/sdk logout
```

## Authentication Errors

### Common Error Responses

> [accordion] 401 Unauthorized
>
> **Cause**: Invalid or missing API key
>
> ```json theme={null}
> {
>   "error": "Invalid API key"
> }
> ```
>
> **Solutions**:
>
> * Verify your API key is correct
> * Check the Authorization header format
> * Regenerate your API key if compromised

> [accordion] 403 Forbidden
>
> **Cause**: Valid API key but insufficient permissions
>
> ```json theme={null}
> {
>   "error": "Insufficient permissions for this operation"
> }
> ```
>
> **Solutions**:
>
> * Check your account subscription level
> * Verify the endpoint requires the permissions you have
> * Contact support if you believe this is an error

> [accordion] 429 Too Many Requests
>
> **Cause**: Rate limit exceeded
>
> ```json theme={null}
> {
>   "error": "Rate limit exceeded. Try again in 60 seconds."
> }
> ```
>
> **Solutions**:
>
> * Implement exponential backoff in your requests
> * Check your rate limits in the dashboard
> * Consider upgrading your plan for higher limits

## Security Best Practices

### API Key Security

> [card] 🔒 Storage
>
> * Store in environment variables - Use secure secret management systems - Never commit to
>   version control - Rotate keys regularly

> [card] 🌐 Network Security
>
> * Always use HTTPS - Validate SSL certificates - Use proper CORS settings - Implement request
>   timeouts

> [card] 🚨 Monitoring
>
> * Monitor for unusual usage patterns - Log authentication failures - Set up alerts for
>   suspicious activity - Track API key usage in dashboard

> [card] 🔄 Rotation
>
> * Rotate keys every 90 days - Generate new keys before travel - Revoke unused or compromised
>   keys - Use separate keys per environment

### Environment Variables

Set up secure environment variable management:

> [tab] Development (.env)
>
> ```bash theme={null}
> # .env (never commit this file)
> GIGAREELS_API_KEY=giga_your_development_key_here
> GIGAREELS_BASE_URL=https://gigareels.com
> ```

&#x20;

> [tab] Production (Docker)
>
> ````dockerfile # Dockerfile ENV GIGAREELS_API_KEY="" # docker run command docker run -e theme={null}
> GIGAREELS_API_KEY=giga_your_prod_key_here myapp ```
> </Tab>
>
> <Tab title="Production (Cloud)">
> ```bash
> # AWS Lambda
> aws lambda update-function-configuration \
>   --function-name my-function \
>   --environment Variables='{GIGAREELS_API_KEY=giga_your_key_here}'
>
> # Vercel
> vercel env add GIGAREELS_API_KEY
>
> # Heroku
> heroku config:set GIGAREELS_API_KEY=giga_your_key_here
> ````

### Request Security

Implement secure request patterns:

```javascript theme={null}
import { GigaReels } from "@gigareels/sdk";

class SecureGigaReelsClient {
	constructor() {
		// Validate API key format
		const apiKey = process.env.GIGAREELS_API_KEY;
		if (!apiKey || !apiKey.startsWith("giga_")) {
			throw new Error("Invalid API key format");
		}

		this.client = new GigaReels({
			apiKey,
			baseUrl: process.env.GIGAREELS_BASE_URL || "https://gigareels.com",
		});
	}

	async generateVideo(params) {
		try {
			// Add request timeout
			const timeout = new Promise((_, reject) =>
				setTimeout(() => reject(new Error("Request timeout")), 30000)
			);

			const request = this.client.templates.brainrot.educational(params);

			return await Promise.race([request, timeout]);
		} catch (error) {
			// Log error without exposing sensitive data
			console.error("Video generation failed:", {
				error: error.message,
				timestamp: new Date().toISOString(),
				// Don't log the full request or API key
			});
			throw error;
		}
	}
}
```

## Rate Limits

### Default Limits

| Endpoint | Requests per Minute | Requests per Hour | Requests per Day |
| - | - | - | - |
| `/api/render` | 10 | 100 | 1000 |
| `/api/render/status/*` | 60 | 1000 | 10000 |
| `/api/social-media/*` | 30 | 300 | 3000 |

### Rate Limit Headers

API responses include rate limit information:

```http theme={null}
HTTP/1.1 200 OK
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1640995200
```

### Handling Rate Limits

```javascript theme={null}
async function makeRequestWithRetry(requestFn, maxRetries = 3) {
	for (let attempt = 1; attempt <= maxRetries; attempt++) {
		try {
			return await requestFn();
		} catch (error) {
			if (error.message.includes("429") && attempt < maxRetries) {
				// Exponential backoff
				const delay = Math.pow(2, attempt) * 1000;
				console.log(`Rate limited. Retrying in ${delay}ms...`);
				await new Promise(resolve => setTimeout(resolve, delay));
				continue;
			}
			throw error;
		}
	}
}

// Usage
const result = await makeRequestWithRetry(() => client.templates.brainrot.educational(params));
```

## Testing Authentication

### Test Script

```javascript theme={null}
import { GigaReels } from "@gigareels/sdk";

async function testAuthentication() {
	try {
		const client = new GigaReels({
			apiKey: process.env.GIGAREELS_API_KEY,
		});

		// Test with a simple status check
		const task = await client.getTaskStatus("test_task_id");
		console.log("✅ Authentication successful");
	} catch (error) {
		if (error.message.includes("401")) {
			console.log("❌ Invalid API key");
		} else if (error.message.includes("404")) {
			console.log("✅ Authentication successful (task not found is expected)");
		} else {
			console.log("❌ Unexpected error:", error.message);
		}
	}
}

testAuthentication();
```

### CLI Testing

```bash theme={null}
# Test CLI authentication
npx @gigareels/sdk login

# Verify stored credentials
cat ~/.gigareels/credentials.json
```

## Migration Guide

### From v1 to v2 Authentication

If you're upgrading from an older version:

> [tab] Old Format
>
> ```javascript theme={null}
> // ❌ Old authentication method
> const client = new GigaReels({
>   token: "your-token-here"
> });
> ```

> [tab] New Format
>
> ```javascript theme={null}
> // ✅ New authentication method
> const client = new GigaReels({
>   apiKey: "giga_your_api_key_here"
> });
> ```

### Credential Migration

```bash theme={null}
# Check if you need to migrate
npx @gigareels/sdk logout
npx @gigareels/sdk login

# This will create new v2 format credentials
```

## Troubleshooting

> [accordion] API Key Not Working
>
> 1. Verify the key format starts with `giga_`
> 2. Check for extra spaces or characters
> 3. Ensure you're using the correct environment
> 4. Try generating a new API key

&#x20;

> [accordion] CLI Authentication Failed
>
> 1. Clear existing credentials: `npx @gigareels/sdk logout` 2. Try logging in again: `npx
>    	@gigareels/sdk login` 3. Check your internet connection 4. Try using `--local` flag for
>    development

> [accordion] Network Errors
>
> 1. Verify you can reach `https://gigareels.com`
> 2. Check firewall and proxy settings
> 3. Ensure SSL certificates are valid
> 4. Try a different network connection

## Next Steps

**1. Get Your API Key**

Generate an API key from the GigaReels dashboard

**2. Set Up Environment**

Configure environment variables for secure key storage

**3. Test Authentication**

Verify your setup with a simple API call

**4. Implement Security**

Add proper error handling and security measures

> [card] Ready to Make API Calls?
>
> Continue to the [Render API Reference](https://gigareels.mintlify.site/api-reference/render) to start generating content.

&#x20;


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.