Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: sync all examples.

thorwebdev805358d0da7b
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 3a0cd161cca..88c2d614951 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -553,6 +553,7 @@ export const functions = {
url: '/guides/functions/examples/connect-to-postgres',
items: [],
},
+ { name: 'Discord Bot', url: '/guides/functions/examples/discord-bot', items: [] },
{ name: 'GitHub Actions', url: '/guides/functions/examples/github-actions', items: [] },
{ name: 'OG Image', url: '/guides/functions/examples/og-image', items: [] },
{ name: 'OpenAI', url: '/guides/functions/examples/openai', items: [] },
diff --git a/apps/docs/pages/guides/functions.mdx b/apps/docs/pages/guides/functions.mdx
index a382f7ccde1..b19ddb81872 100644
--- a/apps/docs/pages/guides/functions.mdx
+++ b/apps/docs/pages/guides/functions.mdx
@@ -43,12 +43,12 @@ export const examples = [
{
name: 'With supabase-js',
description: 'Use the Supabase client inside your Edge Function.',
- href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts',
+ href: '/guides/functions/auth',
},
{
name: 'With CORS headers',
description: 'Send CORS headers for invoking from the browser.',
- href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/browser-with-cors/index.ts',
+ href: '/guides/functions/cors',
},
{
name: 'React Native with Stripe',
@@ -86,6 +86,71 @@ export const examples = [
description: `Get user location data from user's IP address.`,
href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/location',
},
+ {
+ name: 'Cloudflare Turnstile',
+ description: `Protecting Forms with Cloudflare Turnstile.`,
+ href: '/guides/functions/examples/cloudflare-turnstile',
+ },
+ {
+ name: 'Connect to Postgres',
+ description: `Connecting to Postgres from Edge Functions.`,
+ href: '/guides/functions/examples/connect-to-postgres',
+ },
+ {
+ name: 'Github Actions',
+ description: `Deploying Edge Functions with GitHub Actions.`,
+ href: '/guides/functions/examples/github-actions',
+ },
+ {
+ name: 'Oak Server Middleware',
+ description: `Request Routing with Oak server middleware.`,
+ href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/oak-server',
+ },
+ {
+ name: 'OpenAI',
+ description: `Using OpenAI in Edge Functions.`,
+ href: '/guides/functions/examples/openai',
+ },
+ {
+ name: 'Stripe Webhooks',
+ description: `Handling signed Stripe Webhooks with Edge Functions.`,
+ href: '/guides/functions/examples/stripe-webhooks',
+ },
+ {
+ name: 'Send emails',
+ description: `Send emails in Edge Functions.`,
+ href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/send-email-smtp',
+ },
+ {
+ name: 'Web Stream',
+ description: `Server-Sent Events in Edge Functions.`,
+ href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/streams',
+ },
+ {
+ name: 'Puppeteer',
+ description: `Generate screenshots with Puppeteer.`,
+ href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/puppeteer',
+ },
+ {
+ name: 'Discord Bot',
+ description: `Building a Slash Command Discord Bot with Edge Functions.`,
+ href: '/guides/functions/examples/discord-bot',
+ },
+ {
+ name: 'Telegram Bot',
+ description: `Building a Telegram Bot with Edge Functions.`,
+ href: '/guides/functions/examples/telegram-bot',
+ },
+ {
+ name: 'Upload File',
+ description: `Process multipart/form-data.`,
+ href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/file-upload-storage',
+ },
+ {
+ name: 'Upstash Redis',
+ description: `Build an Edge Functions Counter with Upstash Redis.`,
+ href: '/guides/functions/examples/upstash-redis',
+ },
]
export const Page = ({ children }) => <Layout meta={meta} children={children} hideToc={true} />
diff --git a/apps/docs/pages/guides/functions/auth.mdx b/apps/docs/pages/guides/functions/auth.mdx
index 871c16bd6f2..29ad1505034 100644
--- a/apps/docs/pages/guides/functions/auth.mdx
+++ b/apps/docs/pages/guides/functions/auth.mdx
@@ -20,7 +20,7 @@ By creating a supabase client with the auth context from the function, you can d
2. Run queries in the context of the user with [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies enforced.
```js lines=14,17-19,22-23 title=supabase/functions/select-from-table-with-auth-rls/index.ts
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
serve(async (req: Request) => {
diff --git a/apps/docs/pages/guides/functions/cors.mdx b/apps/docs/pages/guides/functions/cors.mdx
index 766da74ae86..7274d810b02 100644
--- a/apps/docs/pages/guides/functions/cors.mdx
+++ b/apps/docs/pages/guides/functions/cors.mdx
@@ -24,7 +24,7 @@ export const corsHeaders = {
You can then import and use the CORS headers within your functions:
```ts index.ts
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { corsHeaders } from '../_shared/cors.ts'
console.log(`Function "browser-with-cors" up and running!`)
diff --git a/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx b/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx
index ef38552855f..830e91723c8 100644
--- a/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx
+++ b/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx
@@ -34,7 +34,7 @@ supabase functions new cloudflare-turnstile
And add the code to the `index.ts` file:
```ts index.ts
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { corsHeaders } from '../_shared/cors.ts'
console.log('Hello from Cloudflare Trunstile!')
diff --git a/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx b/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx
index de9f2378359..d99931b58e8 100644
--- a/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx
+++ b/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx
@@ -20,7 +20,7 @@ Supabase Edge Functions allow you to go beyond HTTP and can connect to your Post
```ts index.ts
import * as postgres from 'https://deno.land/x/[email protected]/mod.ts'
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
// Get the connection string from the environment variable "DATABASE_URL"
const databaseUrl = Deno.env.get('DATABASE_URL')!
diff --git a/apps/docs/pages/guides/functions/examples/discord-bot.mdx b/apps/docs/pages/guides/functions/examples/discord-bot.mdx
new file mode 100644
index 00000000000..281a2ac0e3e
--- /dev/null
+++ b/apps/docs/pages/guides/functions/examples/discord-bot.mdx
@@ -0,0 +1,178 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ id: 'examples-discord-bot',
+ title: 'Discord Bot',
+ description: 'Building a Slash Command Discord Bot with Edge Functions.',
+ video: 'https://www.youtube.com/v/J24Bvo_m7DM',
+}
+
+<div class="video-container">
+ <iframe
+ src="https://www.youtube-nocookie.com/embed/J24Bvo_m7DM"
+ frameBorder="1"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen
+ ></iframe>
+</div>
+
+## Create an application on Discord Developer Portal
+
+1. Go to [https://discord.com/developers/applications](https://discord.com/developers/applications) (login using your discord account if required).
+2. Click on **New Application** button available at left side of your profile picture.
+3. Name your application and click on **Create**.
+4. Go to **Bot** section, click on **Add Bot**, and finally on **Yes, do it!** to confirm.
+
+That's it. A new application is created which will hold our Slash Command. Don't close the tab as we need information from this application page throughout our development.
+
+Before we can write some code, we need to curl a discord endpoint to register a Slash Command in our app.
+
+Fill `DISCORD_BOT_TOKEN` with the token available in the **Bot** section and `CLIENT_ID` with the ID available on the **General Information** section of the page and run the command on your terminal.
+
+```bash
+BOT_TOKEN='replace_me_with_bot_token'
+CLIENT_ID='replace_me_with_client_id'
+curl -X POST \
+-H 'Content-Type: application/json' \
+-H "Authorization: Bot $BOT_TOKEN" \
+-d '{"name":"hello","description":"Greet a person","options":[{"name":"name","description":"The name of the person","type":3,"required":true}]}' \
+"https://discord.com/api/v8/applications/$CLIENT_ID/commands"
+```
+
+This will register a Slash Command named `hello` that accepts a parameter named `name` of type string.
+
+## Code
+
+```ts index.ts
+// Sift is a small routing library that abstracts away details like starting a
+// listener on a port, and provides a simple function (serve) that has an API
+// to invoke a function for a specific path.
+import { json, serve, validateRequest } from 'sift'
+// TweetNaCl is a cryptography library that we use to verify requests
+// from Discord.
+import nacl from 'nacl'
+
+enum DiscordCommandType {
+ Ping = 1,
+ ApplicationCommand = 2,
+}
+
+// For all requests to "/" endpoint, we want to invoke home() handler.
+serve({
+ '/discord-bot': home,
+})
+
+// The main logic of the Discord Slash Command is defined in this function.
+async function home(request: Request) {
+ // validateRequest() ensures that a request is of POST method and
+ // has the following headers.
+ const { error } = await validateRequest(request, {
+ POST: {
+ headers: ['X-Signature-Ed25519', 'X-Signature-Timestamp'],
+ },
+ })
+ if (error) {
+ return json({ error: error.message }, { status: error.status })
+ }
+
+ // verifySignature() verifies if the request is coming from Discord.
+ // When the request's signature is not valid, we return a 401 and this is
+ // important as Discord sends invalid requests to test our verification.
+ const { valid, body } = await verifySignature(request)
+ if (!valid) {
+ return json(
+ { error: 'Invalid request' },
+ {
+ status: 401,
+ }
+ )
+ }
+
+ const { type = 0, data = { options: [] } } = JSON.parse(body)
+ // Discord performs Ping interactions to test our application.
+ // Type 1 in a request implies a Ping interaction.
+ if (type === DiscordCommandType.Ping) {
+ return json({
+ type: 1, // Type 1 in a response is a Pong interaction response type.
+ })
+ }
+
+ // Type 2 in a request is an ApplicationCommand interaction.
+ // It implies that a user has issued a command.
+ if (type === DiscordCommandType.ApplicationCommand) {
+ const { value } = data.options.find(
+ (option: { name: string; value: string }) => option.name === 'name'
+ )
+ return json({
+ // Type 4 responds with the below message retaining the user's
+ // input at the top.
+ type: 4,
+ data: {
+ content: `Hello, ${value}!`,
+ },
+ })
+ }
+
+ // We will return a bad request error as a valid Discord request
+ // shouldn't reach here.
+ return json({ error: 'bad request' }, { status: 400 })
+}
+
+/** Verify whether the request is coming from Discord. */
+async function verifySignature(request: Request): Promise<{ valid: boolean; body: string }> {
+ const PUBLIC_KEY = Deno.env.get('DISCORD_PUBLIC_KEY')!
+ // Discord sends these headers with every request.
+ const signature = request.headers.get('X-Signature-Ed25519')!
+ const timestamp = request.headers.get('X-Signature-Timestamp')!
+ const body = await request.text()
+ const valid = nacl.sign.detached.verify(
+ new TextEncoder().encode(timestamp + body),
+ hexToUint8Array(signature),
+ hexToUint8Array(PUBLIC_KEY)
+ )
+
+ return { valid, body }
+}
+
+/** Converts a hexadecimal string to Uint8Array. */
+function hexToUint8Array(hex: string) {
+ return new Uint8Array(hex.match(/.{1,2}/g)!.map((val) => parseInt(val, 16)))
+}
+```
+
+## Deploy the Slash Command Handler
+
+```bash
+supabase functions deploy discord-bot --no-verify-jwt
+supabase secrets set DISCORD_PUBLIC_KEY=your_public_key
+```
+
+Navigate to your Function details in the Supabase Dashboard to get your Endpoint URL.
+
+### Configure Discord application to use our URL as interactions endpoint URL
+
+1. Go back to your application (Greeter) page on Discord Developer Portal
+2. Fill **INTERACTIONS ENDPOINT URL** field with the URL and click on **Save Changes**.
+
+The application is now ready. Let's proceed to the next section to install it.
+
+## Install the Slash Command on your Discord server
+
+So to use the `hello` Slash Command, we need to install our Greeter application on our Discord server. Here are the steps:
+
+1. Go to **OAuth2** section of the Discord application page on Discord Developer Portal
+2. Select `applications.commands` scope and click on the **Copy** button below.
+3. Now paste and visit the URL on your browser. Select your server and click on **Authorize**.
+
+Open Discord, type `/Promise` and press **Enter**.
+
+## Run locally
+
+```bash
+supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/.env.local
+ngrok http 54321
+```
+
+export const Page = ({ children }) => <Layout meta={meta} children={children} />
+
+export default Page
diff --git a/apps/docs/pages/guides/functions/examples/og-image.mdx b/apps/docs/pages/guides/functions/examples/og-image.mdx
index efa8eb99e59..be4f4dc46d2 100644
--- a/apps/docs/pages/guides/functions/examples/og-image.mdx
+++ b/apps/docs/pages/guides/functions/examples/og-image.mdx
@@ -50,7 +50,7 @@ export default function handler(req: Request) {
Create an `index.ts` file to execute the handler on incoming requests:
```ts index.ts
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import handler from './handler.tsx'
console.log('Hello from og-image Function!')
diff --git a/apps/docs/pages/guides/integrations/onesignal.mdx b/apps/docs/pages/guides/integrations/onesignal.mdx
index 3f270c6f60e..bf4922e749f 100644
--- a/apps/docs/pages/guides/integrations/onesignal.mdx
+++ b/apps/docs/pages/guides/integrations/onesignal.mdx
@@ -8,7 +8,7 @@ export const meta = {
video: 'https://www.youtube.com/v/mw0DLwItue4',
}
-[OneSignal](https://onesignal.com/) is a tool that allows you to send messages across different channels such as the following to keep your users engaged.
+[OneSignal](https://onesignal.com/) is a tool that allows you to send messages across different channels such as the following to keep your users engaged.
- Push notifications
- SMS
@@ -36,7 +36,6 @@ You can find the complete example app along with the edge functions code to send
![Ordering app UI](/docs/img/guides/integrations/onesignal/app-ui.png)
-
## Step 1: Getting started
Before we dive into the code, this guide assumes that you have the following ready
@@ -80,8 +79,7 @@ const supabase = createClient(supabaseUrl, supabaseAnonKey)
const Home: NextPage = () => {
const [user, setUser] = useState<User | null>(null)
- const [oneSignalInitialized, setOneSignalInitialized] =
- useState<boolean>(false)
+ const [oneSignalInitialized, setOneSignalInitialized] = useState<boolean>(false)
/**
* Initializes OneSignal SDK for a given Supabase User ID
@@ -123,9 +121,7 @@ const Home: NextPage = () => {
const { price } = Object.fromEntries(new FormData(event.currentTarget))
if (typeof price !== 'string') return
- const { error } = await supabase
- .from('orders')
- .insert({ price: Number(price) })
+ const { error } = await supabase.from('orders').insert({ price: Number(price) })
if (error) {
alert(error.message)
}
@@ -142,15 +138,13 @@ const Home: NextPage = () => {
initialize()
- const authListener = supabase.auth.onAuthStateChange(
- async (event, session) => {
- const user = session?.user ?? null
- setUser(user)
- if (user) {
- initializeOneSignal(user.id)
- }
+ const authListener = supabase.auth.onAuthStateChange(async (event, session) => {
+ const user = session?.user ?? null
+ setUser(user)
+ if (user) {
+ initializeOneSignal(user.id)
}
- )
+ })
return () => {
authListener.data.subscription.unsubscribe()
@@ -175,10 +169,7 @@ const Home: NextPage = () => {
<option value="200">$200</option>
<option value="300">$300</option>
</select>
- <button
- type="submit"
- className="py-1 px-4 text-lg bg-green-400 rounded"
- >
+ <button type="submit" className="py-1 px-4 text-lg bg-green-400 rounded">
Place an Order
</button>
</form>
@@ -190,10 +181,7 @@ const Home: NextPage = () => {
name="email"
placeholder="Email"
/>
- <button
- type="submit"
- className="py-1 px-4 text-lg bg-green-400 rounded"
- >
+ <button type="submit" className="py-1 px-4 text-lg bg-green-400 rounded">
Send Magic Link
</button>
</form>
@@ -211,7 +199,7 @@ There is quite a bit of stuff going on here, but basically, it’s creating a si
Notice that inside the `initializeOneSignal()` function, we are setting the Supabase user ID as an [external user ID of OneSignal](https://documentation.onesignal.com/docs/external-user-ids). This allows us to later send push notifications to the user using their Supabase user ID from the backend, which is very handy.
```tsx
-await OneSignal.setExternalUserId(uid);
+await OneSignal.setExternalUserId(uid)
```
The front-end side of things is done here. Let’s get into the backend.
@@ -237,7 +225,7 @@ supabase functions new notify
Replace the contents of `supabase/functions/notify/index.ts` with the following
```tsx
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import * as OneSignal from 'https://esm.sh/@onesignal/[email protected]'
const _OnesignalAppId_ = Deno.env.get('ONESIGNAL_APP_ID')!
@@ -263,12 +251,9 @@ serve(async (req) => {
}
const onesignalApiRes = await onesignal.createNotification(notification)
- return new Response(
- JSON.stringify({ onesignalResponse: onesignalApiRes }),
- {
- headers: { 'Content-Type': 'application/json' },
- }
- )
+ return new Response(JSON.stringify({ onesignalResponse: onesignalApiRes }), {
+ headers: { 'Content-Type': 'application/json' },
+ })
} catch (err) {
console.error('Failed to create OneSignal notification', err)
return new Response('Server error.', {
@@ -295,7 +280,6 @@ ONESIGNAL_REST_API_KEY=YOUR_ONESIGNAL_REST_API_KEY
![Where to find OneSignal User Auth Key](/docs/img/guides/integrations/onesignal/onesignal-api-key.png)
-
Once your environment variables are filled in, you can run the following command to set the environment variable.
```bash
@@ -313,35 +297,35 @@ supabase functions deploy notify --no-verify-jwt
Finally, we get to set up the database! Run the following SQL to set up the `orders` table.
```sql
-create table if not exists public.orders (
- id uuid not null primary key default uuid_generate_v4(),
- created_at timestamptz not null default now(),
- user_id uuid not null default auth.uid(),
+create table
+ if not exists public.orders (
+ id uuid not null primary key default uuid_generate_v4 (),
+ created_at timestamptz not null default now (),
+ user_id uuid not null default auth.uid (),
price int8 not null
-);
+ );
```
As you can see, the `orders` table has 4 columns and 3 of them have default values. That means all we need to send from the front-end app is the price. That is why our insert statement looked very simple.
```tsx
const { error } = await supabase.from('orders').insert({
- price: 100,
- })
+ price: 100,
+})
```
Let’s also set up the webhook so that whenever a new row is inserted in the `orders` table, it calls the edge function. Go to `Database > Webhooks` and create a new Database Webhook. The table should be set to `orders` and Events should be inserted. The type should be HTTP Request, the HTTP method should be POST, and the URL should be the URL of your edge function. Hit confirm to save the webhook configuration.
![Supabase Webhooks configuration](/docs/img/guides/integrations/onesignal/webhook.png)
-At this point, the app should be complete! Run your app locally with `npm run dev`, or deploy your app to a hosting service and see how you receive a push notification when you place an order!
+At this point, the app should be complete! Run your app locally with `npm run dev`, or deploy your app to a hosting service and see how you receive a push notification when you place an order!
Remember that if you decide to deploy your app to a hosting service, you would need to create another OneSignal app configured for your local address.
![Ordering app UI](/docs/img/guides/integrations/onesignal/app-ui.png)
-
## Resources
-This particular example was using Next.js, but you can apply the same principles to implement send push notification, SMS, Emails, and in-app-notifications on other platforms as well.
+This particular example was using Next.js, but you can apply the same principles to implement send push notification, SMS, Emails, and in-app-notifications on other platforms as well.
- [OneSignal + Flutter + Supabase example](https://github.com/OneSignalDevelopers/onesignal-supabase-sample-integration-supabase)
- [OneSignal Mobile Quickstart](https://documentation.onesignal.com/docs/mobile-sdk-setup)