Loading...

Anon key vs Secret key -- which one to use in Supabase Storage and when?

question supabase storage
Ram Patra Published on November 14, 2024

When working with Supabase Storage, deciding whether to use the anon key or the secret key depends on your application’s context and security requirements. Here’s a detailed breakdown to help you decide:


1. Supabase Keys Overview

  • Anon Key:
    • Public API key used for client-side operations.
    • Tied to the public role in your Supabase database.
    • Permissions are limited to what is explicitly allowed for public access.
  • Secret Key:
    • Private API key meant for server-side use only.
    • Has elevated permissions tied to the service_role, which bypasses all RLS (Row-Level Security) policies.
    • Should never be exposed in client-side code.

Client-Side Applications

  • Use the anon key for operations like:
    • Uploading files.
    • Downloading files.
    • Accessing storage buckets where public permissions or RLS policies are enforced.

Server-Side Applications

  • Use the secret key for operations like:
    • Managing storage (e.g., creating/deleting buckets).
    • Performing admin-level actions, such as overriding RLS policies.
    • Sensitive operations that require unrestricted access.

3. Security Best Practices

  • Anon Key:
    • Safe for embedding in your frontend code because its permissions are limited.
    • Make sure to configure Bucket Policies properly to restrict access to sensitive files.
  • Secret Key:
    • Must always be kept private and only used in secure, server-side environments (e.g., API servers, cloud functions).
    • Never expose the secret key in client-side code or frontend applications.

4. When to Use Which Key

| Scenario | Key to Use | Reason | |——————————————|———————–|—————————————————————————————————| | Allow users to upload files (frontend) | Anon Key | Public-facing; relies on RLS and bucket policies for access control. | | Allow users to download public files | Anon Key | Safe as long as public read access is enabled in bucket policies. | | Manage buckets and files (admin tasks) | Secret Key | Requires elevated permissions for operations like creating/deleting buckets. | | Perform background jobs (e.g., cleanup) | Secret Key | Secure, server-side environment ensures private access. | | Authenticate user-specific file access | Anon Key (frontend) + RLS | Combine anon key with database-driven RLS policies for fine-grained access control. |


Example Use Case

Frontend File Upload

Use the anon key with a properly configured bucket policy:

  1. Set up RLS policies to restrict uploads based on user sessions.
  2. Use Supabase’s client SDK:
    import { createClient } from "@supabase/supabase-js";
    
    const supabase = createClient("https://your-project.supabase.co", "your-anon-key");
    
    async function uploadFile(file: File) {
      const { data, error } = await supabase.storage
        .from("my-bucket")
        .upload(`folder/${file.name}`, file);
         
      if (error) {
        console.error("Error uploading file:", error);
        return;
      }
      console.log("File uploaded:", data);
    }
    

Server-Side File Management

Use the secret key for unrestricted access:

import { createClient } from "@supabase/supabase-js";

const supabase = createClient("https://your-project.supabase.co", "your-secret-key");

async function deleteFile(path: string) {
  const { data, error } = await supabase.storage
    .from("my-bucket")
    .remove([path]);

  if (error) {
    console.error("Error deleting file:", error);
    return;
  }
  console.log("File deleted:", data);
}

Conclusion

  • Use the anon key for client-side operations with limited, secure permissions.
  • Use the secret key for server-side operations with elevated privileges.
  • Always configure Bucket Policies and RLS to ensure secure and appropriate access control.
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on November 14, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question nextjs front-end November 12, 2024 How to define schemas, foreign keys, relations, and query data by performing joins in a Nextjs app using Supabase and Drizzle?

Drizzle is an ORM that makes it easy to work with db, data migrations, etc. Here’s how you can define foreign keys, relations, and perform table joins using Drizzle ORM in a Next.js app with Supabase: