Merge branch 'feat/launch-week-4-thursday' of https://github.com/supabase/supabase into feat/launch-week-4-thursday

This commit is contained in:
Jonathan Summers-Muir committed 2022-03-31 15:30:42 +02:00
commit f424f23650
2 files changed
+292

No files matched your search

+286
View File
@@ -0,0 +1,286 @@
---
id: functions
title: Edge Functions
description: 'Globally distributed Typescript functions.'
---
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
const examples = [
{
name: 'With supabase-js',
description: 'Use the Supabase client inside your Edge Function.',
href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions',
},
{
name: 'With Stripe',
description: 'Use the Stripe client inside your Edge Function.',
href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions',
},
]
:::caution
Edge Functions are Experimental until 1 August 2022. There will breaking changes. Do not use them in Production.
:::
Edge Functions are server-side Typescript functions, distributed globally at the edge - close to your users. They can be used for listening to webhooks or integrating your Supabase project with third-parties, like Stripe.
Edge Functions are developed using [Deno](https://deno.com), which offers a few benefits to you as a developer:
- It is open source.
- It is portable. Supabase Edge Functions run locally, and on any other Deno-compatible platform (including self-hosted infrastructure).
- It is Typescript first and supports WASM.
- Edge Functions are globally distributed for low-latency.
:::note
For data-intensive operations we recommend using [Database Functions](/docs/guides/database/functions), which are executed within your database, and can be called remotely using the [REST and GraphQL API](/docs/guides/database/functions).
:::
## Quickstart
Learn how to develop Edge Functions in less than 7 minutes:
<iframe
className="w-full video-with-border"
width="640"
height="385"
src="https://www.youtube-nocookie.com/embed/9TK6oTzibmk"
frameBorder="1"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
></iframe>
## Prerequisites
Follow the steps to prepare your Supabase project on your local machine.
- Install the Supabase CLI. [Installing and Updating Docs](/docs/reference/cli/installing-and-updating).
- Login to the CLI
- Command: `supabase login`
- Docs: [`login`](/docs/reference/cli/supabase-login)
- Initialize Supabase inside your project
- Command: `supabase login`
- Docs: [Getting Started](/docs/guides/local-development#getting-started)
- Link to your Remote Project
- Command: `supabase link --project-ref your-project-ref`
- Docs: `[link](/docs/reference/cli/supabase-link)`
- Optional
- Follow [this setup guide](https://deno.land/manual/getting_started/setup_your_environment) to integrate the Deno language server with your editor.
## Getting Started
Let's build an Edge Function locally, then deploy it to the Supabase Platform.
### Creating a function
Let's create a new Edge Function called `hello-world` inside your project:
```bash
supabase functions new hello-world
```
This creates a function stub in your `supabase` folder at `./functions/hello-world/index.ts`.
### Deploy to production
```bash
supabase functions deploy hello-world
```
This command bundles and deploys your Edge Function from `./functions/hello-world/index.ts`
- [ ] TODO - output the URL after running deploy
### Executing Remote Functions
You can execute any Edge Function using curl - just like you executed it locally - except this time we'll switch `[localhost](http://localhost)` with your remote URL.
```jsx
curl --request POST 'https://<project-ref>.functions.supabase.co/functions/v1/hello-world' \
--header 'Authorization: Bearer ANON_KEY' \
--header 'Content-Type: application/json' \
--data '{ "name":"Functions" }'
```
NOTE!! Use your PROD keys
## Debugging your Functions
- Go to the log explorer
## Developing locally
You can run your Edge Function locally using `[supabase functions serve](/docs/reference/cli/supabase-functions-serve)`:
```bash
supabase start # start the supabase stack
supabase functions serve hello-world # start the Function watcher
```
The `functions serve` command has hot-reloading capabilities. It will watch for any changes to your files and restart the Deno server.
### Invoking Functions locally
While serving your local Function, you can execute it using curl:
```bash
curl --request POST 'http://localhost:54321/functions/v1/hello-world' \
--header 'Authorization: Bearer LOCAL_ANON_KEY' \
--header 'Content-Type: application/json' \
--data '{ "name":"Functions" }'
```
- Implementation details
- All Edge Functions are `POST` requests.
- The `Authorization` header is required. You can use either the `ANON` key, the `SERVICE_ROLE` key, or a logged-in user's JWT.
- The Function is proxied through the local API (`http://localhost:54321`)
You should see the response `{ "message":"Hello Functions!" }`.
If you execute Function with a different payload the response will change. Try modifying the `--data '{"name":"Functions"}'` line to `--data '{"name":"World"}'`.
## Secrets and Environment Variables
It's common that you will need to use sensitive information or environment-specific variables inside your Edge Functions. You can access these using Deno's built-in handler
```js
Deno.env.get(MY_SECRET_NAME)
```
### Default secrets
By default, Edge Functions have access to several secrets:
- `SUPABASE_URL`: The API gateway for your Supabase project.
- `SUPABASE_ANON_KEY`: The `anon` key for your Supabase API. This is safe to use in a browser when you have [Row Level Security](/docs/guides/auth/row-level-security) enabled.
- `SUPABASE_SERVICE_ROLE_KEY`: The `service_role` key for your Supabase API. This is safe to use in Edge Functions, but it should NEVER be used in a browser. This key will bypass [Row Level Security](/docs/guides/auth/row-level-security).
- `SUPABASE_DB_URL`: The URL for your [PostgreSQL database](/docs/guides/database). You can use this to connect directly to your database.
### Local secrets
Let's create a local file for storing our secrets, and inside it we can store a secret `MY_NAME`:
```jsx
echo "MY_NAME=Yoda" >> ./supabase/.env.local
```
This creates a new file `./supabase/.env.local` for storing your local development secrets.
:::caution
Never check your `.env` files into Git!
:::
Now let's use this function inside our Function. Anywhere in your function, add this line:
```jsx
console.log(Deno.env.get(MY_NAME))
```
Now we can invoke our function locally, by serving it with our new `.env.local` file:
```bash
# Serve the Function with the env file
supabase functions serve hello-world --env-file ./supabase/.env.local
# Invoke the function locally
curl --request POST 'http://localhost:54321/functions/v1/hello-world' \
--header 'Authorization: Bearer LOCAL_ANON_KEY' \
--header 'Content-Type: application/json' \
--data '{ "name":"Functions" }'
```
After invoking the function you should see the name “Yoda” output to the terminal.
### Production secrets
Let's create a `.env` for production. In this case we'll just use the same as our local secrets:
```bash
cp ./supabase/.env.local ./supabase/.env.
```
This creates a new file `./supabase/.env` for storing your production secrets.
:::caution
Never check your `.env` files into Git!
:::
Let's push all the secrets from the `.env` file to our remote project using `[secrets set](/docs/reference/cli/supabase-secrets-set)`:
```bash
supabase secrets set --env-file ./supabase/.env
# You can also set secrets individually using
# supabase secrets set MY_NAME=Chewbacca
```
Run the curl again - see the result logged on the dashboard
To see all the secrets which you have set remotely, use `[secrets list](/docs/reference/cli/supabase-secrets-list)`:
```jsx
supabase secrets list
```
## Examples
You can find a list of useful [Edge Function Examples](https://github.com/supabase/supabase/tree/master/examples/flutter-user-management) in our GitHub repository.
<div class="container" style={{ padding: 0 }}>
<div class="row is-multiline">
{examples.map((x) => (
<div class="col col--6">
<a class="card" to={x.href} style={{ height: '100%' }}>
<div class="card__body">
<h4>{x.name}</h4>
<p>{x.description}</p>
</div>
</a>
</div>
))}
</div>
</div>
## Limitations and Suggestions
### Organizing your Edge Functions
We recommend developing “fat functions”. This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (`_`). We recommend this folder structure:
```bash
└── supabase
├── functions
│ ├── _shared
│ │ ├── supabaseAdmin.ts # Supabase client with SERVICE_ROLE key
│ │ └── supabaseClient.ts # Supabase client with ANON key
│ ├── function-one # use hyphens to name functions
│ │ └── index.ts
│ └── function-two
│ └── index.ts
├── migrations
└── config.toml
```
### Naming Edge Functions
We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase).
### Limitations
Edge Functions are Experimental. They aren't going away, but there will be breaking changes.
- Deno Deploy limitations
- Deno does not support outgoing connections to ports `25`, `465`, and `587`.
- Cannot write to File System
- Edge Functions
- Local development - only one function at a time
- Supabase Functions only supports `POST` responses.
- Supabase Functions does not support HTML responses.
+6
View File
@@ -111,6 +111,12 @@ module.exports = {
collapsed: false,
items: ['guides/api'],
},
{
type: 'category',
label: 'Functions',
collapsed: false,
items: ['guides/functions'],
},
{
type: 'category',
label: 'Auth',