Logo

dev-resources.site

for different kinds of informations.

Unlocking User Data: Building a Secure Supabase Edge Function

Published at
11/26/2024
Categories
supabase
typescript
frontend
webdev
Author
thingengineer
Author
13 person written this
thingengineer
open
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/[email protected]/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.

supabase Article's
30 articles in total
Favicon
Building Production-Grade Web Applications with Supabase – Part 1
Favicon
Tracing and Metrics in supabase/storage
Favicon
Understanding Storage backends in supabase/storage
Favicon
Auth in Supabase storage
Favicon
Overview of supabase storage repository
Favicon
Harnessing the Power of Self-Hosted Supabase on Coolify: A Complete Guide to Server Setup and OAuth Providers Integration
Favicon
checa como se hace una conexión entre nextjs y la autenticación de supabase
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Custom schema specific Supabase Server Component clients in Grida Form workspace
Favicon
Custom schema specific Supabase Client Component clients in Grida Form workspace
Favicon
Introducing Supabase Client Playground: The Ultimate Tool for Streamlined Query Testing
Favicon
hCaptcha, a bot detection tool, usage in Supabase and Chatwoot
Favicon
Securing Client-Side Routes in Next.js with Supabase
Favicon
How to Transfer PostgreSQL Database from Local to Supabase on macOS
Favicon
Supabase | My Way of Designing & Managing DB
Favicon
What does Supabase use for its Authentication?
Favicon
É seguro guardar dados do usuário no localStorage?
Favicon
Supabase RLS Alternative
Favicon
Build Queue Worker using Supabase Cron, Queue and Edge Function
Favicon
Supabase Just Got More Powerful: Queue, Cron, and Background Tasks in Edge Functions
Favicon
Comparison of the middleware implementation between Supabase Auth documentation and the nextjs-stripe-supabase.
Favicon
How Supabase implemented micro-frontends using Multi Zones in Next.js
Favicon
Unlocking User Data: Building a Secure Supabase Edge Function
Favicon
Usecase: TumbleLog
Favicon
Supabase Edge Functions
Favicon
Setup Astro With Supabase and Prisma
Favicon
We launched SupaCharts! Visualize Beautiful Charts from your Supabase Data.
Favicon
A Free Minimalistic SaaS Starter Kit for Fast MVP Building
Favicon
supabase注册并创建项目和添加数据表
Favicon
Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide

Featured ones: