Welcome to your first Supabase Function! Supabase Functions (powered by Deno) allow you to run server-side code without managing infrastructure. Think of them as the serverless backend for your applications. For this 'Hello World' example, we'll create a simple function that returns a greeting.
Before we write any code, let's understand the basic structure. Supabase Functions are typically JavaScript or TypeScript files. They export an async function that will be executed when the function is triggered.
Navigate to your Supabase project dashboard. On the left-hand sidebar, you'll find a section for 'Functions'. Click on it, and then click the 'New Function' button.
You'll be presented with a code editor. Let's start by creating a simple function that returns 'Hello World!'. Replace any existing boilerplate code with the following:
export async function onRequest(request) {
return new Response('Hello World!');
}Let's break down this code:
export async function onRequest(request): This is the entry point for your function. Supabase expects a function namedonRequest(or a name you configure) that accepts aRequestobject. Theasynckeyword is important as most operations within a function will be asynchronous.request: This object contains information about the incoming HTTP request, such as headers, method, and body. For this simple example, we won't be using it.return new Response('Hello World!'): This is how you send a response back to the client. We're creating a newResponseobject with the string 'Hello World!' as its body. By default, this will be a 200 OK status with a plain text content type.
Once you've entered the code, give your function a name. Let's call it hello-world. Then, click the 'Deploy' button. Supabase will now build and deploy your function.
After deployment, you'll see your function listed in the 'Functions' section. Next to your function's name, you'll find a URL. This is the endpoint for your 'Hello World' function.