0
0
Supabasecloud~5 mins

Why Edge Functions handle server-side logic in Supabase

Choose your learning style9 modes available
Introduction

Edge Functions run code close to users to handle tasks securely and quickly on the server side.

When you want to keep sensitive data safe and not expose it to users.
When you need to process data or make decisions before sending results to the user.
When you want faster responses by running code near the user's location.
When you want to reduce load on your main servers by offloading tasks.
When you need to customize responses based on user location or device.
Syntax
Supabase
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

serve((request) => {
  // Your server-side logic here
  return new Response('Hello from Edge Function');
});
Edge Functions use simple JavaScript or TypeScript to run server-side code.
They respond to HTTP requests and can access secure resources.
Examples
A basic Edge Function that returns a simple greeting.
Supabase
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

serve((request) => {
  return new Response('Hello World');
});
This Edge Function fetches data from another API and returns it as JSON.
Supabase
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

serve(async (request) => {
  const data = await fetch('https://api.example.com/data');
  const json = await data.json();
  return new Response(JSON.stringify(json), { headers: { 'Content-Type': 'application/json' } });
});
Sample Program

This Edge Function simulates server-side logic by creating a user object and returning a personalized greeting.

Supabase
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

serve((request) => {
  const user = { id: 1, name: 'Alice' };
  // Simulate server-side logic like authentication or data fetching
  const message = `Hello, ${user.name}! This message is from the server.`;
  return new Response(message, { headers: { 'Content-Type': 'text/plain' } });
});
OutputSuccess
Important Notes

Edge Functions run outside the user's browser, so they keep secrets safe.

They help make apps faster by running code near the user.

Always keep your server-side logic in Edge Functions to protect data and improve performance.

Summary

Edge Functions run server-side code close to users for speed and security.

They handle tasks like data processing, authentication, and API calls.

Using Edge Functions helps keep sensitive logic safe and apps responsive.