0Pricing
Supabase Backend as a Service · 강의

애플리케이션에 함수 통합하기

클라이언트 측 애플리케이션에서 배포한 Edge Functions를 호출하고 그 응답을 처리하는 방법을 배웁니다.

애플리케이션에 함수 통합하기은(는) CoddyKit의 무료 Supabase Backend as a Service 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Supabase Backend as a Service 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Calling Your Edge Functions

You've learned to deploy Edge Functions. Now, let's connect them to your client application! This is where your app truly becomes dynamic.

Integrating functions allows your app to trigger server-side logic, process data, or interact with external services without managing a dedicated backend server.

How Clients Talk to Functions

Supabase Edge Functions are essentially HTTP endpoints. Your client application communicates with them by making standard HTTP requests.

The Supabase client library simplifies this process, providing a clean way to invoke your deployed functions directly from your JavaScript, TypeScript, or other supported client environments.

The `invoke()` Method

The primary method for calling an Edge Function from your client is supabase.functions.invoke().

It takes two main arguments:

  • Function Name: The name of your deployed Edge Function.
  • Options Object (optional): An object to pass data (payload) or configure the request.

Basic Invocation Syntax

Let's look at the basic structure for invoking an Edge Function without sending any specific data. You'll often use async/await for cleaner asynchronous code.

Invoking a 'Hello' Function

Imagine you have a simple Edge Function named 'hello-world' that just returns a 'Hello!' message. Here's how you'd call it:

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'

const supabase = createClient(supabaseUrl, supabaseAnonKey)

async function callHelloWorld() {
  try {
    const { data, error } = await supabase.functions.invoke('hello-world')
    if (error) {
      console.error('Error:', error.message)
    } else {
      console.log('Response:', data)
    }
  } catch (err) {
    console.error('Network error:', err.message)
  }
}

// Call the function to see the output
callHelloWorld()

Passing Data to Functions

Most real-world functions need input data. You can send a JSON payload to your Edge Function using the body property within the options object.

The body will be accessible inside your Edge Function via the request object.

Invoking with a Payload

Let's say you have a function called 'greet-user' that expects a name. Here's how to send that data:

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'

const supabase = createClient(supabaseUrl, supabaseAnonKey)

async function callGreetUser(userName) {
  try {
    const { data, error } = await supabase.functions.invoke('greet-user', {
      body: { name: userName }
    })
    if (error) {
      console.error('Error:', error.message)
    } else {
      console.log('Greeting:', data)
    }
  } catch (err) {
    console.error('Network error:', err.message)
  }
}

// Try it with your name!
callGreetUser('Coddy')

Handling Function Responses

When you invoke an Edge Function, the supabase.functions.invoke() call returns an object containing data and error properties.

  • data: Contains the successful response from your function.
  • error: Contains details if an error occurred during invocation or within the function itself.

Processing the Response

It's crucial to check for errors and handle both success and failure states. Your client application should gracefully manage these scenarios.

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'

const supabase = createClient(supabaseUrl, supabaseAnonKey)

async function processResponseExample() {
  const payload = { item: 'book', quantity: 2 }
  try {
    const { data, error } = await supabase.functions.invoke('process-order', {
      body: payload
    })

    if (error) {
      console.error('Order processing failed:', error.message)
      // Display an error message to the user
    } else {
      console.log('Order processed successfully:', data)
      // Update UI with success message or results
    }
  } catch (networkError) {
    console.error('Network or unexpected error:', networkError.message)
    // Handle connectivity issues
  }
}

processResponseExample()

Error Handling & Best Practices

Always implement robust error handling. Supabase's invoke method catches network errors in the catch block, and function-specific errors in the returned error object.

  • Frontend Validation: Validate input before sending.
  • User Feedback: Show loading states, success messages, or clear error messages.
  • Logging: Log errors for debugging.

Function Invocation Quiz

You're calling an Edge Function named 'calculate-total' and passing a JSON object { price: 10, quantity: 3 }. Which of the following code snippets correctly invokes the function and handles a potential error?

Functions in Your App

Great job! You've learned how to integrate Supabase Edge Functions into your client-side applications.

  • Use supabase.functions.invoke() to call functions.
  • Pass data using the body property in the options object.
  • Always handle both successful data and potential error responses.

This knowledge empowers you to build dynamic, interactive features powered by serverless logic directly from your app!

자주 묻는 질문

“애플리케이션에 함수 통합하기” 강의는 무료인가요?

네 — “애플리케이션에 함수 통합하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Supabase Backend as a Service 강의 전체를 잠금 해제할 수 있습니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.

“애플리케이션에 함수 통합하기”에서 뭘 배우나요?

클라이언트 측 애플리케이션에서 배포한 Edge Functions를 호출하고 그 응답을 처리하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Supabase Backend as a Service을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Supabase Backend as a Service을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Supabase Backend as a Service은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“애플리케이션에 함수 통합하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Supabase Backend as a Service 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Supabase Backend as a Service 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Edge Functions 입문
  2. 첫 함수 배포하기
  3. 애플리케이션에 함수 통합하기
  4. 비밀, 환경 변수 및 예약 함수
← Supabase Backend as a Service(으)로 돌아가기