After installing the KeyHippo extension in your Supabase database, the next step is to set up the KeyHippo client in your application. This guide will walk you through the process of integrating KeyHippo into your client-side code.

Prerequisites

Before setting up the KeyHippo client, ensure you have:

  1. Installed the KeyHippo extension in your Supabase database
  2. A Supabase project with a client application
  3. Node.js and npm (or yarn) installed in your development environment

Installation

First, install the KeyHippo client package in your project:

npm install keyhippo
# or if you're using yarn
yarn add keyhippo

Basic Setup

1. Import KeyHippo

In your application code, import the KeyHippo class:

import { KeyHippo } from 'keyhippo';

2. Initialize KeyHippo

Create an instance of KeyHippo, passing your Supabase client:

import { createClient } from '@supabase/supabase-js';
import { KeyHippo } from 'keyhippo';

const supabase = createClient('YOUR_SUPABASE_URL', 'YOUR_SUPABASE_ANON_KEY');
const keyHippo = new KeyHippo(supabase);

Replace ‘YOUR_SUPABASE_URL’ and ‘YOUR_SUPABASE_ANON_KEY’ with your actual Supabase project details.

Basic Usage

Once you’ve set up the KeyHippo client, you can start using its features:

Creating an API Key

async function createNewApiKey(userId: string, description: string) {
  try {
    const result = await keyHippo.createApiKey(userId, description);
    console.log('New API Key:', result.apiKey);
    return result;
  } catch (error) {
    console.error('Error creating API key:', error);
  }
}

Revoking an API Key

async function revokeApiKey(userId: string, keyId: string) {
  try {
    await keyHippo.revokeApiKey(userId, keyId);
    console.log('API Key revoked successfully');
  } catch (error) {
    console.error('Error revoking API key:', error);
  }
}

Fetching API Key Information

async function getApiKeyInfo(userId: string) {
  try {
    const keyInfos = await keyHippo.loadApiKeyInfo(userId);
    console.log('API Key Information:', keyInfos);
    return keyInfos;
  } catch (error) {
    console.error('Error fetching API key info:', error);
  }
}

Advanced Configuration

Custom Logger

KeyHippo allows you to pass a custom logger for more granular control over logging:

const customLogger = {
  info: (message: string) => console.log(`[INFO] ${message}`),
  warn: (message: string) => console.warn(`[WARN] ${message}`),
  error: (message: string) => console.error(`[ERROR] ${message}`),
  debug: (message: string) => console.debug(`[DEBUG] ${message}`),
};

const keyHippo = new KeyHippo(supabase, customLogger);

Error Handling

KeyHippo uses the Effect library for error handling. Wrap your KeyHippo operations in try-catch blocks to handle potential errors:

import { AppError } from 'keyhippo';

try {
  const result = await keyHippo.createApiKey(userId, 'New Key');
  // Handle successful key creation
} catch (error) {
  if (error instanceof AppError) {
    switch (error._tag) {
      case 'DatabaseError':
        // Handle database errors
        break;
      case 'UnauthorizedError':
        // Handle unauthorized access
        break;
      case 'ValidationError':
        // Handle validation errors
        break;
      case 'NetworkError':
        // Handle network issues
        break;
    }
  } else {
    // Handle other types of errors
  }
}

Best Practices

  1. Secure Storage: Never store API keys in client-side code or version control systems.
  2. Error Handling: Implement error handling for all KeyHippo operations.
  3. Logging: Use appropriate logging levels and ensure sensitive information is not logged.
  4. Key Rotation: Implement regular key rotation to enhance security.
  5. Access Control: Limit API key creation and management to authorized users only.

Troubleshooting

If you encounter issues:

  1. Connection Problems: Ensure your Supabase client is correctly initialized.
  2. Permission Errors: Verify that the authenticated user has the necessary permissions in your RLS policies.
  3. Version Mismatch: Make sure your client package version is compatible with your installed KeyHippo extension.

Next Steps

With the KeyHippo client set up, you can now:

  1. Implement API key authentication in your application
  2. Create and manage API keys for your users
  3. Enhance your Row Level Security policies with KeyHippo functions

Create Policies

Learn how to create RLS policies that leverage KeyHippo for API key authentication.