Managing Tokens

This guide will help you manage your API tokens effectively and securely.

Token Best Practices

1. Use Different Tokens for Different Environments

Create separate tokens for development, staging, and production:

// Development environment
const devToken = 'scr_dev_1234567890';

// Staging environment
const stagingToken = 'scr_staging_1234567890';

// Production environment
const prodToken = 'scr_prod_1234567890';

2. Store Tokens Securely

Never hardcode tokens in your code. Use environment variables or secure configuration management:

// .env file
SCREENSHOTLY_API_TOKEN=your_token_here

// Code
const apiToken = process.env.SCREENSHOTLY_API_TOKEN;
if (!apiToken) {
  throw new Error('API token not configured');
}

3. Rotate Tokens Regularly

Generate new tokens periodically and phase out old ones:

async function rotateToken() {
  // Generate new token
  const response = await fetch('https://api.screenshotly.app/api/keys/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${currentToken}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: 'Production Token',
      expiresIn: 30, // 30 days
    }),
  });

  const { apiKey } = await response.json();

  // Update your configuration with the new token
  // Then phase out the old token after ensuring the new one works
}

4. Monitor Token Usage

Regularly check token usage and watch for unusual patterns:

async function checkTokenUsage() {
  const response = await fetch('https://api.screenshotly.app/api/keys', {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
    },
  });

  const { keys } = await response.json();
  const token = keys[0];

  console.log('Token Usage:', {
    requests: token.usageCount,
    lastUsed: token.lastUsedAt,
    status: token.status,
  });
}

Token Management Through Dashboard

Creating Tokens

  1. Navigate to the API Tokens page
  2. Click “Generate New Token”
  3. Enter a descriptive name
  4. Set an expiration date
  5. Copy and securely store the token

Revoking Tokens

If a token is compromised:

  1. Navigate to API Tokens
  2. Find the compromised token
  3. Click the “Revoke” button
  4. Generate a new token to replace it

Token Management Through API

Generating Tokens

async function generateToken() {
  const response = await fetch('https://api.screenshotly.app/api/keys/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: 'API Token',
      expiresIn: 30, // Days until expiration
    }),
  });

  const { apiKey, expiresAt } = await response.json();
  return { apiKey, expiresAt };
}

Listing Tokens

async function listTokens() {
  const response = await fetch('https://api.screenshotly.app/api/keys', {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
    },
  });

  const { keys } = await response.json();
  return keys;
}

Revoking Tokens

async function revokeToken(tokenId: string) {
  const response = await fetch(`https://api.screenshotly.app/api/keys?id=${tokenId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${apiToken}`,
    },
  });

  if (!response.ok) {
    throw new Error('Failed to revoke token');
  }
}

Error Handling

Implement proper error handling for token management:

async function handleTokenOperations() {
  try {
    // Try to use the token
    const response = await fetch('https://api.screenshotly.app/screenshot', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        url: 'https://example.com',
      }),
    });

    if (response.status === 401) {
      // Token is invalid or expired
      await handleTokenRefresh();
    } else if (response.status === 429) {
      // Rate limit exceeded
      await handleRateLimitExceeded();
    }
  } catch (error) {
    console.error('Token operation failed:', error);
  }
}

async function handleTokenRefresh() {
  // Generate a new token
  const { apiKey } = await generateToken();
  
  // Update your configuration
  await updateTokenConfiguration(apiKey);
}

async function handleRateLimitExceeded() {
  // Wait for rate limit reset or use a different token
  const response = await fetch('https://api.screenshotly.app/api/keys', {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
    },
  });

  const { keys } = await response.json();
  const resetTime = new Date(keys[0].rateLimit.reset);
  
  console.log(`Rate limit will reset at: ${resetTime}`);
}

Security Checklist

✅ Use environment variables for token storage
✅ Rotate tokens regularly (every 30-90 days)
✅ Monitor token usage for suspicious activity
✅ Use different tokens for different environments
✅ Implement proper error handling
✅ Have a token rotation strategy
✅ Keep tokens out of version control
✅ Revoke compromised tokens immediately

Next Steps