Guides

Public API

This guide will walk you through implementing Public APIs in your SaaS using the built-in API Key infrastructure. This infrastructure allows users to securely expose their API endpoints, ensuring that only authenticated requests can access their organization's data.

API Key Infrastructure

The API Key infrastructure allows each organization to generate and manage its own API keys, which are used to authenticate requests. These keys are unique to each organization and must be included in the request headers for authorized access.

How It Works

To create an API key for organization, follow these steps:

  1. Generate API Keys: Each organization can generate API keys through the API Key section.
  2. Secure Access: API keys must be passed in the request headers to access public APIs.
  3. Key Validation: API keys are validated via the getOrganizationAPIKeyData function, ensuring that only authorized users can access the organization's data.

API Security

To protect your API endpoints from unauthorized access, you must validate the incoming API key before processing the request. Use the getOrganizationAPIKeyData function, which checks the x-api-key header, verifies its existence, and ensures the key is valid.

The getOrganizationAPIKeyData function fetches and verifies the API key from the headers, ensuring the key belongs to an active organization.

export async function getOrganizationAPIKeyData() {
  const apiKey = headers().get("x-api-key");
 
  if (!apiKey) {
    throw new Error("API key is missing from headers");
  }
 
  const supabase = createSupabaseServerAdminClient();
  const { data, error } = await supabase
    .from("organization_apikeys")
    .select("id, organization_id, created_by")
    .eq("id", apiKey)
    .maybeSingle();
 
  // Update the last_used timestamp for the API key when it is used
  await supabase.rpc("update_api_key_last_used");
 
  if (error) {
    throw new Error("Invalid API key");
  }
 
  if (!data) {
    throw new Error("API key not found");
  }
 
  return data;
}

How to Use It

To secure your API routes, simply add the getOrganizationAPIKeyData function at the top of your API handler. It checks the x-api-key header, retrieves the corresponding organization data, and ensures the key is valid.

Example of securing an API route:

import { getOrganizationAPIKeyData } from "@/utils/server";
 
export default async function handler(req, res) {
  try {
    await getOrganizationAPIKeyData();
    // Proceed with the business logic here
    res.status(200).json({ message: "Authorized access" });
  } catch (error) {
    res.status(401).json({ error: error.message });
  }
}

How the Function Works

The function retrieves the x-api-key from the request headers.

  • It validates the API key by checking its existence in the organization_apikeys table in Supabase.
  • If the key is valid, it returns the associated organization's data.
  • If the key is invalid or missing, an error is thrown, preventing unauthorized access.
  • The last usage timestamp is updated via the update_api_key_last_used Supabase function to track API key usage.

Conclusion

By integrating the getOrganizationAPIKeyData function, you can securely expose public APIs for your SaaS product using API keys. This ensures that only authorized users with valid API keys can access sensitive organizational data.

On this page