DEV Community

Cover image for Unlocking User Data: Building a Secure Supabase Edge Function
Josh Campbell
Josh Campbell

Posted on

Unlocking User Data: Building a Secure Supabase Edge Function

In this tutorial, we'll delve into the world of Supabase Edge Functions. We'll explore how to set up a local development environment and build a simple function to list all users within your Supabase project. This hands-on guide will empower you to leverage the full potential of Supabase Edge Functions for your next project.


Prerequisites

Assuming you have your local Supabase CLI setup and linked to your remote project.

Make sure Supabase is running with:

supabase start
Enter fullscreen mode Exit fullscreen mode

Creating a New Edge Function

Run this to create a new edge function named 'admin-list-all-users':

supabase functions new admin-list-all-users
Enter fullscreen mode Exit fullscreen mode

This creates a new folder under ./supabase named 'admin-list-all-users' and inside that folder is an index.ts file.

Running Functions Locally

To run functions locally using the CLI, execute this command. Note that this ties up a console window until it is stopped with control + c. While it is running, you can see information about the function calls, and even more if you run it with the --debug flag.

supabase functions serve
Enter fullscreen mode Exit fullscreen mode

Before you edit the function, it would be a good idea to run the demo "hello world" code to make sure the basics are working. This code should be in your newly created function already but here it is just in case.

Demo Code

// Setup type definitions for built-in Supabase Runtime APIs
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';

console.log('Hello from Functions!');

Deno.serve(async (req) => {
  const { name } = await req.json();
  const data = {
    message: `Hello ${name}!`
  };

  return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });
});
Enter fullscreen mode Exit fullscreen mode

Running Your Function Locally

There is also a curl command at the bottom of your index.ts file that looks like this:

curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/admin-list-all-users' \
    --header 'Authorization: Bearer SUPABASE_ANON_KEY_HERE' \
    --header 'Content-Type: application/json' \
    --data '{"name":"World"}'
Enter fullscreen mode Exit fullscreen mode

Your SUPABASE_ANON_KEY should be automatically populated with the correct key for your local setup. Copy and paste that to your terminal and run it.

You should see a response like this:

{"message":"Hello World!"}%
Enter fullscreen mode Exit fullscreen mode

The Fun Part

Now lets replace the demo code with this:

// Setup type definitions for built-in Supabase Runtime APIs
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';

// Import necessary modules with full URLs
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';

// Access environment variables for Supabase URL and Service Role Key
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;

// Initialize the Supabase client with the service role key
const supabase = createClient(supabaseUrl, serviceRoleKey);

serve(async (_req) => {
  try {
    // Fetch all users
    const { data, error } = await supabase.auth.admin.listUsers();

    if (error) throw error;

    // Return the list of users as JSON
    return new Response(JSON.stringify(data), {
      headers: { 'Content-Type': 'application/json' },
      status: 200
    });
  } catch (error: any) {
    // Handle errors and return a JSON response
    return new Response(JSON.stringify({ error: error.message }), {
      headers: { 'Content-Type': 'application/json' },
      status: 500
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

This will automatically pull your Supabase URL and service role key then return a JSON object containing all users.

Again, run the function locally like this. Notice that we do not need to pass any data to the function this time.

curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/admin-list-all-users' \
    --header 'Authorization: Bearer SUPABASE_ANON_KEY_HERE' \
    --header 'Content-Type: application/json'
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you've successfully created and tested a Supabase Edge Function locally that can securely access and pass user data to the client. This powerful ability enables you to extend your Supabase application's capabilities without the need for complex server setups.

Take the next steps and deploy your function to run on your linked (live) Supabase project. Explore the vast possibilities of Edge Functions and leverage them to create secure, innovative and efficient applications by reading the Supabase docs.

Supabase Edge Functions DOCS

Watch for part 2 where we lock the function down using Supabase Auth.

Top comments (0)