Skip to content

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

Create edge function (#33726)

Saxon Fletcher1cefb95a7341
diff --git a/apps/studio/components/interfaces/Functions/Functions.templates.ts b/apps/studio/components/interfaces/Functions/Functions.templates.ts
new file mode 100644
index 00000000000..f0c82f5fa93
--- /dev/null
+++ b/apps/studio/components/interfaces/Functions/Functions.templates.ts
@@ -0,0 +1,98 @@
+export const EDGE_FUNCTION_TEMPLATES = [
+ {
+ value: 'hello-world',
+ name: 'Simple Hello World',
+ description: 'Basic function that returns a JSON response',
+ content: `// Setup type definitions for built-in Supabase Runtime APIs
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+interface reqPayload {
+ name: string;
+}
+
+console.info('server started');
+
+Deno.serve(async (req: Request) => {
+ const { name }: reqPayload = await req.json();
+ const data = {
+ message: \`Hello \${name} from foo!\`,
+ };
+
+ return new Response(
+ JSON.stringify(data),
+ { headers: { 'Content-Type': 'application/json', 'Connection': 'keep-alive' }}
+ );
+});`,
+ },
+ {
+ value: 'database-access',
+ name: 'Supabase Database Access',
+ description: 'Example using Supabase client to query your database',
+ content: `// Setup type definitions for built-in Supabase Runtime APIs
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { createClient } from 'jsr:@supabase/supabase-js@2'
+
+Deno.serve(async (req) => {
+ try {
+ const supabase = createClient(
+ Deno.env.get('SUPABASE_URL') ?? '',
+ Deno.env.get('SUPABASE_ANON_KEY') ?? '',
+ { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
+ )
+
+ const { data, error } = await supabase.from('table_name').select('*')
+
+ if (error) {
+ throw error
+ }
+
+ return new Response(JSON.stringify({ data }), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ })
+ } catch (err) {
+ return new Response(String(err?.message ?? err), { status: 500 })
+ }
+})`,
+ },
+ {
+ value: 'node-api',
+ name: 'Node Built-in API Example',
+ description: 'Example using Node.js built-in crypto and http modules',
+ content: `// Setup type definitions for built-in Supabase Runtime APIs
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { randomBytes } from "node:crypto";
+import { createServer } from "node:http";
+import process from "node:process";
+
+const generateRandomString = (length) => {
+ const buffer = randomBytes(length);
+ return buffer.toString('hex');
+};
+
+const randomString = generateRandomString(10);
+console.log(randomString);
+
+const server = createServer((req, res) => {
+ const message = \`Hello\`;
+ res.end(message);
+});
+
+server.listen(9999);`,
+ },
+ {
+ value: 'express',
+ name: 'Express Server',
+ description: 'Example using Express.js for routing',
+ content: `// Setup type definitions for built-in Supabase Runtime APIs
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import express from "npm:[email protected]";
+
+const app = express();
+
+app.get(/(.*)/, (req, res) => {
+ res.send("Welcome to Supabase");
+});
+
+app.listen(8000);`,
+ },
+]
diff --git a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
index d4406e3d899..09918364b88 100644
--- a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
+++ b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
@@ -1,8 +1,9 @@
+import { useRouter } from 'next/router'
+import { PropsWithChildren } from 'react'
+
import { useParams } from 'common'
import { ProductMenu } from 'components/ui/ProductMenu'
import { withAuth } from 'hooks/misc/withAuth'
-import { useRouter } from 'next/router'
-import { PropsWithChildren } from 'react'
import ProjectLayout from '../ProjectLayout/ProjectLayout'
const EdgeFunctionsProductMenu = () => {
@@ -19,7 +20,7 @@ const EdgeFunctionsProductMenu = () => {
{
name: 'Functions',
key: 'main',
- pages: [undefined, '[functionSlug]'],
+ pages: [undefined, '[functionSlug]', 'new'],
url: `/project/${projectRef}/functions`,
items: [],
},
diff --git a/apps/studio/components/layouts/PageLayout/PageHeader.tsx b/apps/studio/components/layouts/PageLayout/PageHeader.tsx
index 69f56e325ee..2ca4785d98b 100644
--- a/apps/studio/components/layouts/PageLayout/PageHeader.tsx
+++ b/apps/studio/components/layouts/PageLayout/PageHeader.tsx
@@ -26,6 +26,7 @@ interface PageHeaderProps {
secondaryActions?: ReactNode
className?: string
isCompact?: boolean
+ pageMeta?: ReactNode
}
export const PageHeader = ({
@@ -37,6 +38,7 @@ export const PageHeader = ({
secondaryActions,
className,
isCompact = false,
+ pageMeta,
}: PageHeaderProps) => {
const { ref } = useParams()
diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsx b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsx
new file mode 100644
index 00000000000..2c427ef5ab7
--- /dev/null
+++ b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsx
@@ -0,0 +1,264 @@
+import React from 'react'
+import { Edit, File, Plus, Trash } from 'lucide-react'
+import { Button } from 'ui'
+import AIEditor from 'components/ui/AIEditor'
+import {
+ TreeView,
+ TreeViewItem,
+ flattenTree,
+ ContextMenu_Shadcn_,
+ ContextMenuTrigger_Shadcn_,
+ ContextMenuContent_Shadcn_,
+ ContextMenuItem_Shadcn_,
+ ContextMenuSeparator_Shadcn_,
+} from 'ui'
+
+interface FileData {
+ id: number
+ name: string
+ content: string
+ selected?: boolean
+}
+
+interface FileExplorerAndEditorProps {
+ files: FileData[]
+ onFilesChange: (files: FileData[]) => void
+ aiEndpoint?: string
+ aiMetadata?: {
+ projectRef?: string
+ connectionString?: string
+ includeSchemaMetadata?: boolean
+ }
+}
+
+const getLanguageFromFileName = (fileName: string): string => {
+ const extension = fileName.split('.').pop()?.toLowerCase()
+ switch (extension) {
+ case 'ts':
+ case 'tsx':
+ return 'typescript'
+ case 'js':
+ case 'jsx':
+ return 'javascript'
+ case 'json':
+ return 'json'
+ case 'html':
+ return 'html'
+ case 'css':
+ return 'css'
+ case 'md':
+ return 'markdown'
+ default:
+ return 'typescript' // Default to typescript
+ }
+}
+
+const FileExplorerAndEditor = ({
+ files,
+ onFilesChange,
+ aiEndpoint,
+ aiMetadata,
+}: FileExplorerAndEditorProps) => {
+ const selectedFile = files.find((f) => f.selected) ?? files[0]
+
+ const handleChange = (value: string) => {
+ const updatedFiles = files.map((file) =>
+ file.id === selectedFile.id ? { ...file, content: value } : file
+ )
+ onFilesChange(updatedFiles)
+ }
+
+ const addNewFile = () => {
+ const newId = Math.max(...files.map((f) => f.id)) + 1
+ const updatedFiles = files.map((f) => ({ ...f, selected: false }))
+ onFilesChange([
+ ...updatedFiles,
+ {
+ id: newId,
+ name: `file${newId}.ts`,
+ content: '',
+ selected: true,
+ },
+ ])
+ }
+
+ const handleFileNameChange = (id: number, newName: string) => {
+ if (!newName.trim()) return // Don't allow empty names
+ const updatedFiles = files.map((file) => (file.id === id ? { ...file, name: newName } : file))
+ onFilesChange(updatedFiles)
+ }
+
+ const handleFileDelete = (id: number) => {
+ if (files.length <= 1) {
+ // Don't allow deleting the last file
+ return
+ }
+
+ const fileToDelete = files.find((f) => f.id === id)
+ const isSelected = fileToDelete?.selected
+
+ const updatedFiles = files.filter((file) => file.id !== id)
+
+ // If the deleted file was selected, select another file
+ if (isSelected && updatedFiles.length > 0) {
+ updatedFiles[0].selected = true
+ }
+
+ onFilesChange(updatedFiles)
+ }
+
+ const handleFileSelect = (id: number) => {
+ const updatedFiles = files.map((file) => ({
+ ...file,
+ selected: file.id === id,
+ }))
+ onFilesChange(updatedFiles)
+ }
+
+ const handleStartRename = (id: number) => {
+ const updatedTreeData = {
+ name: '',
+ children: files.map((file) => ({
+ id: file.id.toString(),
+ name: file.name,
+ metadata: {
+ isEditing: file.id === id,
+ originalId: file.id,
+ },
+ })),
+ }
+
+ // Force re-render of the TreeView with the updated metadata
+ setTreeData(updatedTreeData)
+ }
+
+ const [treeData, setTreeData] = React.useState({
+ name: '',
+ children: files.map((file) => ({
+ id: file.id.toString(),
+ name: file.name,
+ metadata: {
+ isEditing: false,
+ originalId: file.id,
+ },
+ })),
+ })
+
+ // Update treeData when files change
+ React.useEffect(() => {
+ setTreeData({
+ name: '',
+ children: files.map((file) => ({
+ id: file.id.toString(),
+ name: file.name,
+ metadata: {
+ isEditing: false,
+ originalId: file.id,
+ },
+ })),
+ })
+ }, [files])
+
+ return (
+ <div className="flex-1 overflow-hidden flex h-full">
+ <div className="w-64 border-r bg-surface-200 flex flex-col">
+ <div className="py-4 px-6 border-b flex items-center justify-between">
+ <h3 className="text-sm font-normal font-mono uppercase text-lighter tracking-wide">
+ Files
+ </h3>
+ <Button size="tiny" type="default" icon={<Plus size={14} />} onClick={addNewFile}>
+ Add File
+ </Button>
+ </div>
+ <div className="flex-1 overflow-y-auto">
+ <TreeView
+ data={flattenTree(treeData)}
+ aria-label="files tree"
+ nodeRenderer={({ element, isBranch, isExpanded, getNodeProps, level }) => {
+ const nodeProps = getNodeProps()
+ const originalId =
+ typeof element.metadata?.originalId === 'number'
+ ? element.metadata.originalId
+ : null
+
+ return (
+ <ContextMenu_Shadcn_ modal={false}>
+ <ContextMenuTrigger_Shadcn_ asChild>
+ <div>
+ <TreeViewItem
+ {...nodeProps}
+ isExpanded={isExpanded}
+ isBranch={isBranch}
+ isSelected={files.find((f) => f.id === originalId)?.selected}
+ level={level}
+ xPadding={16}
+ name={element.name}
+ icon={<File size={14} className="text-foreground-light" />}
+ isEditing={Boolean(element.metadata?.isEditing)}
+ onEditSubmit={(value) => {
+ if (originalId !== null) handleFileNameChange(originalId, value)
+ }}
+ onClick={() => {
+ if (originalId !== null) handleFileSelect(originalId)
+ }}
+ />
+ </div>
+ </ContextMenuTrigger_Shadcn_>
+ <ContextMenuContent_Shadcn_ onCloseAutoFocus={(e) => e.stopPropagation()}>
+ <ContextMenuItem_Shadcn_
+ className="gap-x-2"
+ onSelect={() => {
+ if (originalId !== null) handleStartRename(originalId)
+ }}
+ onFocusCapture={(e) => e.stopPropagation()}
+ >
+ <Edit size={14} />
+ Rename file
+ </ContextMenuItem_Shadcn_>
+
+ {files.length > 1 && (
+ <>
+ <ContextMenuSeparator_Shadcn_ />
+ <ContextMenuItem_Shadcn_
+ className="gap-x-2"
+ onSelect={() => {
+ if (originalId !== null) handleFileDelete(originalId)
+ }}
+ onFocusCapture={(e) => e.stopPropagation()}
+ >
+ <Trash size={14} />
+ Delete file
+ </ContextMenuItem_Shadcn_>
+ </>
+ )}
+ </ContextMenuContent_Shadcn_>
+ </ContextMenu_Shadcn_>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <div className="flex-1 min-h-0 relative px-3 bg-surface-200">
+ <AIEditor
+ language={getLanguageFromFileName(selectedFile?.name || 'index.ts')}
+ value={selectedFile?.content}
+ onChange={handleChange}
+ aiEndpoint={aiEndpoint}
+ aiMetadata={aiMetadata}
+ options={{
+ tabSize: 2,
+ fontSize: 12,
+ minimap: { enabled: false },
+ wordWrap: 'on',
+ lineNumbers: 'on',
+ folding: false,
+ padding: { top: 20, bottom: 20 },
+ lineNumbersMinChars: 3,
+ }}
+ />
+ </div>
+ </div>
+ )
+}
+
+export default FileExplorerAndEditor
diff --git a/apps/studio/middleware.ts b/apps/studio/middleware.ts
index 11f161156bd..0a8ac7f4e54 100644
--- a/apps/studio/middleware.ts
+++ b/apps/studio/middleware.ts
@@ -10,6 +10,7 @@ const HOSTED_SUPPORTED_API_URLS = [
'/ai/sql/suggest',
'/ai/sql/generate-v2',
'/ai/sql/generate-v3',
+ '/ai/edge-function/complete',
'/ai/onboarding/design',
'/ai/sql/complete',
'/ai/sql/title',
diff --git a/apps/studio/pages/api/ai/edge-function/complete.ts b/apps/studio/pages/api/ai/edge-function/complete.ts
new file mode 100644
index 00000000000..afbf3aac4b4
--- /dev/null
+++ b/apps/studio/pages/api/ai/edge-function/complete.ts
@@ -0,0 +1,292 @@
+import { openai } from '@ai-sdk/openai'
+import pgMeta from '@supabase/pg-meta'
+import { streamText } from 'ai'
+import { executeSql } from 'data/sql/execute-sql-query'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { getTools } from '../sql/tools'
+
+export const maxDuration = 30
+const openAiKey = process.env.OPENAI_API_KEY
+const pgMetaSchemasList = pgMeta.schemas.list()
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return new Response(
+ JSON.stringify({
+ error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',
+ }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } }
+ )
+ }
+
+ const { method } = req
+
+ switch (method) {
+ case 'POST':
+ return handlePost(req, res)
+ default:
+ return new Response(
+ JSON.stringify({ data: null, error: { message: `Method ${method} Not Allowed` } }),
+ {
+ status: 405,
+ headers: { 'Content-Type': 'application/json', Allow: 'POST' },
+ }
+ )
+ }
+}
+
+async function handlePost(req: NextApiRequest, res: NextApiResponse) {
+ try {
+ const { completionMetadata, projectRef, connectionString, includeSchemaMetadata } = req.body
+ const { textBeforeCursor, textAfterCursor, language, prompt, selection } = completionMetadata
+
+ if (!projectRef) {
+ return res.status(400).json({
+ error: 'Missing project_ref in request body',
+ })
+ }
+
+ const authorization = req.headers.authorization
+
+ const { result: schemas } = includeSchemaMetadata
+ ? await executeSql(
+ {
+ projectRef,
+ connectionString,
+ sql: pgMetaSchemasList.sql,
+ },
+ undefined,
+ {
+ 'Content-Type': 'application/json',
+ ...(authorization && { Authorization: authorization }),
+ }
+ )
+ : { result: [] }
+
+ const result = await streamText({
+ model: openai('gpt-4o-mini-2024-07-18'),
+ maxSteps: 5,
+ tools: getTools({ projectRef, connectionString, authorization, includeSchemaMetadata }),
+ system: `
+ # Writing Supabase Edge Functions
+
+ You're an expert in writing TypeScript and Deno JavaScript runtime. Generate **high-quality Supabase Edge Functions** that adhere to the following best practices:
+
+ ## Guidelines
+
+ 1. Try to use Web APIs and Deno's core APIs instead of external dependencies (eg: use fetch instead of Axios, use WebSockets API instead of node-ws)
+ 2. Do NOT use bare specifiers when importing dependencies. If you need to use an external dependency, make sure it's prefixed with either \`npm:\` or \`jsr:\`. For example, \`@supabase/supabase-js\` should be written as \`npm:@supabase/supabase-js\`.
+ 3. For external imports, always define a version. For example, \`npm:@express\` should be written as \`npm:[email protected]\`.
+ 4. For external dependencies, importing via \`npm:\` and \`jsr:\` is preferred. Minimize the use of imports from @\`deno.land/x\` , \`esm.sh\` and @\`unpkg.com\` . If you have a package from one of those CDNs, you can replace the CDN hostname with \`npm:\` specifier.
+ 5. You can also use Node built-in APIs. You will need to import them using \`node:\` specifier. For example, to import Node process: \`import process from "node:process"\`. Use Node APIs when you find gaps in Deno APIs.
+ 6. Do NOT use \`import { serve } from "https://deno.land/[email protected]/http/server.ts"\`. Instead use the built-in \`Deno.serve\`.
+ 7. Following environment variables (ie. secrets) are pre-populated in both local and hosted Supabase environments. Users don't need to manually set them:
+ * SUPABASE_URL
+ * SUPABASE_ANON_KEY
+ * SUPABASE_SERVICE_ROLE_KEY
+ * SUPABASE_DB_URL
+ 8. To set other environment variables the user can go to project settings then edge functions to set them
+ 9. A single Edge Function can handle multiple routes. It is recommended to use a library like Express or Hono to handle the routes as it's easier for developer to understand and maintain. Each route must be prefixed with \`/function-name\` so they are routed correctly.
+ 10. File write operations are ONLY permitted on \`/tmp\` directory. You can use either Deno or Node File APIs.
+ 11. Use \`EdgeRuntime.waitUntil(promise)\` static method to run long-running tasks in the background without blocking response to a request. Do NOT assume it is available in the request / execution context.
+
+ ## Example Templates
+
+ ### Simple Hello World Function
+
+ \`\`\`edge
+ // Setup type definitions for built-in Supabase Runtime APIs
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+ interface reqPayload {
+ name: string;
+ }
+
+ console.info('server started');
+
+ Deno.serve(async (req: Request) => {
+ const { name }: reqPayload = await req.json();
+ const data = {
+ message: \`Hello \${name} from foo!\`,
+ };
+
+ return new Response(
+ JSON.stringify(data),
+ { headers: { 'Content-Type': 'application/json', 'Connection': 'keep-alive' }}
+ );
+ });
+ \`\`\`
+
+ ### Example Function using Node built-in API
+
+ \`\`\`edge
+ // Setup type definitions for built-in Supabase Runtime APIs
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+ import { randomBytes } from "node:crypto";
+ import { createServer } from "node:http";
+ import process from "node:process";
+
+ const generateRandomString = (length) => {
+ const buffer = randomBytes(length);
+ return buffer.toString('hex');
+ };
+
+ const randomString = generateRandomString(10);
+ console.log(randomString);
+
+ const server = createServer((req, res) => {
+ const message = \`Hello\`;
+ res.end(message);
+ });
+
+ server.listen(9999);
+ \`\`\`
+
+ ### Using npm packages in Functions
+
+ \`\`\`edge
+ // Setup type definitions for built-in Supabase Runtime APIs
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+ import express from "npm:[email protected]";
+
+ const app = express();
+
+ app.get(/(.*)/, (req, res) => {
+ res.send("Welcome to Supabase");
+ });
+
+ app.listen(8000);
+ \`\`\`
+
+ ### Generate embeddings using built-in @Supabase.ai API
+
+ \`\`\`edge
+ // Setup type definitions for built-in Supabase Runtime APIs
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+ const model = new Supabase.ai.Session('gte-small');
+
+ Deno.serve(async (req: Request) => {
+ const params = new URL(req.url).searchParams;
+ const input = params.get('text');
+ const output = await model.run(input, { mean_pool: true, normalize: true });
+ return new Response(
+ JSON.stringify(output),
+ {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Connection': 'keep-alive',
+ },
+ },
+ );
+ });
+ \`\`\`
+
+ ## Integrating with Supabase Auth
+
+ \`\`\`edge
+ // Setup type definitions for built-in Supabase Runtime APIs
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+ import { createClient } from \\'jsr:@supabase/supabase-js@2\\'
+ import { corsHeaders } from \\'../_shared/cors.ts\\'
+
+ console.log(\`Function "select-from-table-with-auth-rls" up and running!\`)
+
+ Deno.serve(async (req: Request) => {
+ // This is needed if you\\'re planning to invoke your function from a browser.
+ if (req.method === \\'OPTIONS\\') {
+ return new Response(\\'ok\\', { headers: corsHeaders })
+ }
+
+ try {
+ // Create a Supabase client with the Auth context of the logged in user.
+ const supabaseClient = createClient(
+ // Supabase API URL - env var exported by default.
+ Deno.env.get('SUPABASE_URL')!,
+ // Supabase API ANON KEY - env var exported by default.
+ Deno.env.get('SUPABASE_ANON_KEY')!,
+ // Create client with Auth context of the user that called the function.
+ // This way your row-level-security (RLS) policies are applied.
+ {
+ global: {
+ headers: { Authorization: req.headers.get(\\'Authorization\\')! },
+ },
+ }
+ )
+
+ // First get the token from the Authorization header
+ const token = req.headers.get(\\'Authorization\\').replace(\\'Bearer \\', \\'\\')
+
+ // Now we can get the session or user object
+ const {
+ data: { user },
+ } = await supabaseClient.auth.getUser(token)
+
+ // And we can run queries in the context of our authenticated user
+ const { data, error } = await supabaseClient.from(\\'users\\').select(\\'*\\')
+ if (error) throw error
+
+ return new Response(JSON.stringify({ user, data }), {
+ headers: { ...corsHeaders, \\'Content-Type\\': \\'application/json\\' },
+ status: 200,
+ })
+ } catch (error) {
+ return new Response(JSON.stringify({ error: error.message }), {
+ headers: { ...corsHeaders, \\'Content-Type\\': \\'application/json\\' },
+ status: 400,
+ })
+ }
+ })
+
+ // To invoke:
+ // curl -i --location --request POST \\'http://localhost:54321/functions/v1/select-from-table-with-auth-rls\\' \\
+ // --header \\'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs\\' \\
+ // --header \\'Content-Type: application/json\\' \\
+ // --data \\'{"name":"Functions"}\\'
+ \`\`\`
+
+ Database Integration:
+ - Use the getSchema tool to understand the database structure when needed
+ - Reference existing tables and schemas to ensure edge functions work with the user's data model
+ - Use proper types that match the database schema
+ - When accessing the database:
+ - Use RLS policies appropriately for security
+ - Handle database errors gracefully
+ - Use efficient queries and proper indexing
+ - Consider rate limiting for resource-intensive operations
+ - Use connection pooling when appropriate
+ - Implement proper error handling for database operations
+
+ # For all your abilities, follow these instructions:
+ - First look at the list of provided schemas and if needed, get more information about a schema to understand the data model you're working with
+ - If the edge function needs to interact with user data, check both the public and auth schemas to understand the authentication setup
+
+ Here are the existing database schema names you can retrieve: ${schemas}
+ `,
+ messages: [
+ {
+ role: 'user',
+ content: `You are helping me write TypeScript/JavaScript code for an edge function.
+ Here is the context:
+ ${textBeforeCursor}<selection>${selection}</selection>${textAfterCursor}
+
+ Instructions:
+ 1. Only modify the selected text based on this prompt: ${prompt}
+ 2. Your response should be ONLY the modified selection text, nothing else. Remove selected text if needed.
+ 3. Do not wrap in code blocks or markdown
+ 4. You can respond with one word or multiple words
+ 5. Ensure the modified text flows naturally within the current line
+ 6. Avoid duplicating variable declarations, imports, or function definitions when considering the full code
+ 7. If there is no surrounding context (before or after), make sure your response is a complete valid Deno Edge Function including imports.
+
+ Modify the selected text now:`,
+ },
+ ],
+ })
+
+ return result.pipeDataStreamToResponse(res)
+ } catch (error) {
+ console.error('Completion error:', error)
+ return res.status(500).json({
+ error: 'Failed to generate completion',
+ })
+ }
+}
diff --git a/apps/studio/pages/api/ai/sql/complete.ts b/apps/studio/pages/api/ai/sql/complete.ts
index 50ef9b1910e..f1f4929dc89 100644
--- a/apps/studio/pages/api/ai/sql/complete.ts
+++ b/apps/studio/pages/api/ai/sql/complete.ts
@@ -1,9 +1,9 @@
-import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
+import pgMeta from '@supabase/pg-meta'
+import { streamText } from 'ai'
+import { executeSql } from 'data/sql/execute-sql-query'
import { NextApiRequest, NextApiResponse } from 'next'
import { getTools } from '../sql/tools'
-import { executeSql } from 'data/sql/execute-sql-query'
-import pgMeta from '@supabase/pg-meta'
export const maxDuration = 30
const openAiKey = process.env.OPENAI_API_KEY
diff --git a/apps/studio/pages/api/ai/sql/generate-v3.ts b/apps/studio/pages/api/ai/sql/generate-v3.ts
index 71187593fe6..e76de029d8e 100644
--- a/apps/studio/pages/api/ai/sql/generate-v3.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v3.ts
@@ -12,7 +12,7 @@ const pgMetaSchemasList = pgMeta.schemas.list()
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!openAiKey) {
- return res.status(400).json({
+ return res.status(500).json({
error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',
})
}
diff --git a/apps/studio/pages/api/ai/sql/suggest.ts b/apps/studio/pages/api/ai/sql/suggest.ts
index 8244d6799ed..206d2bdce5e 100644
--- a/apps/studio/pages/api/ai/sql/suggest.ts
+++ b/apps/studio/pages/api/ai/sql/suggest.ts
@@ -1,8 +1,8 @@
import { StreamingTextResponse } from 'ai'
import { chatRlsPolicy } from 'ai-commands/edge'
+import { DatabasePoliciesData } from 'data/database-policies/database-policies-query'
import { NextRequest } from 'next/server'
import OpenAI from 'openai'
-import { DatabasePoliciesData } from 'data/database-policies/database-policies-query'
export const config = {
runtime: 'edge',
diff --git a/apps/studio/pages/project/[ref]/functions/index.tsx b/apps/studio/pages/project/[ref]/functions/index.tsx
index 6ce1e9e9e0f..f153df25aa8 100644
--- a/apps/studio/pages/project/[ref]/functions/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/index.tsx
@@ -1,4 +1,5 @@
-import { ExternalLink } from 'lucide-react'
+import { ChevronDown, Code, ExternalLink, Terminal } from 'lucide-react'
+import { useRouter } from 'next/router'
import { useParams } from 'common'
import {
@@ -16,14 +17,26 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { DocsButton } from 'components/ui/DocsButton'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
+import { useFlag } from 'hooks/ui/useFlag'
import { useAppStateSnapshot } from 'state/app-state'
import type { NextPageWithLayout } from 'types'
-import { AiIconAnimation, Button, Dialog, DialogContent, DialogSection, DialogTrigger } from 'ui'
+import {
+ AiIconAnimation,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogSection,
+ DialogTrigger,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from 'ui'
const EdgeFunctionsPage: NextPageWithLayout = () => {
const { ref } = useParams()
const { setAiAssistantPanel } = useAppStateSnapshot()
-
+ const router = useRouter()
const {
data: functions,
error,
@@ -31,20 +44,52 @@ const EdgeFunctionsPage: NextPageWithLayout = () => {
isError,
isSuccess,
} = useEdgeFunctionsQuery({ projectRef: ref })
+ const edgeFunctionCreate = useFlag('edgeFunctionCreate')
const hasFunctions = (functions ?? []).length > 0
const deployButton = (
- <Dialog>
- <DialogTrigger asChild>
- <Button type="primary">Deploy a new function</Button>
- </DialogTrigger>
- <DialogContent size="large">
- <DialogSection padding="small">
- <TerminalInstructions />
- </DialogSection>
- </DialogContent>
- </Dialog>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="primary" iconRight={<ChevronDown className="w-4 h-4" strokeWidth={1.5} />}>
+ Deploy a new function
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-80">
+ <Dialog>
+ <DialogTrigger asChild>
+ <DropdownMenuItem className="gap-4" onSelect={(e) => e.preventDefault()}>
+ <Terminal className="shrink-0" size={16} strokeWidth={1.5} />
+ <div>
+ <span className="text-foreground">Via CLI</span>
+ <p>
+ Create an edge function locally and then deploy your function via the Supabase CLI
+ </p>
+ </div>
+ </DropdownMenuItem>
+ </DialogTrigger>
+ <DialogContent size="large">
+ <DialogSection padding="small">
+ <TerminalInstructions />
+ </DialogSection>
+ </DialogContent>
+ </Dialog>
+ {edgeFunctionCreate && (
+ <DropdownMenuItem
+ onSelect={() => router.push(`/project/${ref}/functions/new`)}
+ className="gap-4"
+ >
+ <Code className="shrink-0" size={16} strokeWidth={1.5} />
+ <div>
+ <span className="text-foreground">Via Editor</span>
+ <p>
+ Create an edge function in the Supabase Studio editor and then deploy your function
+ </p>
+ </div>
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
)
const secondaryActions = [
@@ -95,7 +140,7 @@ const EdgeFunctionsPage: NextPageWithLayout = () => {
<PageLayout
size="large"
title="Edge Functions"
- subtitle="Server-side TypeScript functions distributed globally at the edge"
+ subtitle="Deploy edge functions to handle complex business logic"
primaryActions={deployButton}
secondaryActions={secondaryActions}
>
diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsx
new file mode 100644
index 00000000000..ffa685c6475
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/functions/new.tsx
@@ -0,0 +1,366 @@
+import { AlertCircle, Book, Check } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
+import { useForm } from 'react-hook-form'
+import { yupResolver } from '@hookform/resolvers/yup'
+import * as yup from 'yup'
+
+import { useParams } from 'common'
+import { EDGE_FUNCTION_TEMPLATES } from 'components/interfaces/Functions/Functions.templates'
+import DefaultLayout from 'components/layouts/DefaultLayout'
+import EdgeFunctionsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout'
+import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
+import FileExplorerAndEditor from 'components/ui/FileExplorerAndEditor/FileExplorerAndEditor'
+import { useEdgeFunctionDeployMutation } from 'data/edge-functions/edge-functions-deploy-mutation'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { useFlag } from 'hooks/ui/useFlag'
+import { BASE_PATH, IS_PLATFORM } from 'lib/constants'
+import { useAppStateSnapshot } from 'state/app-state'
+import {
+ AiIconAnimation,
+ Button,
+ cn,
+ Command_Shadcn_,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ Input_Shadcn_,
+ Label_Shadcn_,
+ Popover_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { InfoTooltip } from 'ui-patterns/info-tooltip'
+
+// Array of adjectives and nouns for random function name generation
+const ADJECTIVES = [
+ 'quick',
+ 'clever',
+ 'bright',
+ 'swift',
+ 'rapid',
+ 'smart',
+ 'smooth',
+ 'dynamic',
+ 'super',
+ 'hyper',
+]
+const NOUNS = [
+ 'function',
+ 'handler',
+ 'processor',
+ 'responder',
+ 'worker',
+ 'service',
+ 'api',
+ 'endpoint',
+ 'action',
+ 'task',
+]
+
+// Function name validation regex - only allows alphanumeric characters, hyphens, and underscores
+const FUNCTION_NAME_REGEX = /^[A-Za-z0-9_-]+$/
+
+// Define form schema with yup
+const formSchema = yup.object({
+ functionName: yup
+ .string()
+ .required('Function name is required')
+ .matches(FUNCTION_NAME_REGEX, 'Only letters, numbers, hyphens, and underscores allowed'),
+})
+
+// Generate a random function name
+const generateRandomFunctionName = () => {
+ const adjective = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]
+ const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)]
+ return `${adjective}-${noun}`
+}
+
+// Convert invalid function name to valid one
+const sanitizeFunctionName = (name: string): string => {
+ // Replace invalid characters with hyphens
+ return name.replace(/[^A-Za-z0-9_-]/g, '-')
+}
+
+// Type for the form values
+type FormValues = yup.InferType<typeof formSchema>
+
+const NewFunctionPage = () => {
+ const router = useRouter()
+ const { ref } = useParams()
+ const project = useSelectedProject()
+ const isOptedInToAI = useOrgOptedIntoAi()
+ const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
+ const { setAiAssistantPanel } = useAppStateSnapshot()
+ const edgeFunctionCreate = useFlag('edgeFunctionCreate')
+
+ const [files, setFiles] = useState<
+ { id: number; name: string; content: string; selected?: boolean }[]
+ >([
+ {
+ id: 1,
+ name: 'index.ts',
+ selected: true,
+ content: EDGE_FUNCTION_TEMPLATES[0].content,
+ },
+ ])
+ const [open, setOpen] = useState(false)
+ const [isPreviewingTemplate, setIsPreviewingTemplate] = useState(false)
+ const [savedCode, setSavedCode] = useState<string>('')
+
+ // Setup form with react-hook-form and yup resolver
+ const form = useForm<FormValues>({
+ resolver: yupResolver(formSchema),
+ defaultValues: {
+ functionName: generateRandomFunctionName(),
+ },
+ })
+
+ const { mutate: deployFunction, isLoading: isDeploying } = useEdgeFunctionDeployMutation({
+ onSuccess: () => {
+ toast.success('Successfully deployed edge function')
+ const functionName = form.getValues('functionName')
+ if (ref && functionName) {
+ router.push(`/project/${ref}/functions/${functionName}/details`)
+ }
+ },
+ })
+
+ const onSubmit = (values: FormValues) => {
+ if (isDeploying || !ref) return
+
+ deployFunction({
+ projectRef: ref,
+ metadata: {
+ entrypoint_path: 'index.ts',
+ name: values.functionName,
+ verify_jwt: true,
+ },
+ files: files.map(({ name, content }) => ({ name, content })),
+ })
+ }
+
+ const handleChat = () => {
+ const selectedFile = files.find((f) => f.selected) ?? files[0]
+ setAiAssistantPanel({
+ open: true,
+ sqlSnippets: [selectedFile.content],
+ initialInput: 'Help me understand and improve this edge function...',
+ suggestions: {
+ title:
+ 'I can help you understand and improve your edge function. Here are a few example prompts to get you started:',
+ prompts: [
+ 'Explain what this function does...',
+ 'Help me optimize this function...',
+ 'Show me how to add more features...',
+ 'Help me handle errors better...',
+ ],
+ },
+ })
+ }
+
+ const onSelectTemplate = (templateValue: string) => {
+ const template = EDGE_FUNCTION_TEMPLATES.find((t) => t.value === templateValue)
+ if (template) {
+ setFiles((prev) =>
+ prev.map((file) => (file.selected ? { ...file, content: template.content } : file))
+ )
+ setOpen(false)
+ }
+ }
+
+ const handleTemplateMouseEnter = (content: string) => {
+ if (!isPreviewingTemplate) {
+ const selectedFile = files.find((f) => f.selected) ?? files[0]
+ setSavedCode(selectedFile.content)
+ }
+ setIsPreviewingTemplate(true)
+ setFiles((prev) => prev.map((file) => (file.selected ? { ...file, content } : file)))
+ }
+
+ const handleTemplateMouseLeave = () => {
+ if (isPreviewingTemplate) {
+ setIsPreviewingTemplate(false)
+ setFiles((prev) =>
+ prev.map((file) => (file.selected ? { ...file, content: savedCode } : file))
+ )
+ }
+ }
+
+ // Try to sanitize function name when it's invalid
+ const handleDeploy = () => {
+ const currentName = form.getValues('functionName')
+ const isValid = FUNCTION_NAME_REGEX.test(currentName)
+
+ if (!isValid && currentName) {
+ const sanitizedName = sanitizeFunctionName(currentName)
+ form.setValue('functionName', sanitizedName, { shouldValidate: true })
+ }
+
+ form.handleSubmit(onSubmit)()
+ }
+
+ // TODO (Saxon): Remove this once the flag is fully launched
+ useEffect(() => {
+ if (!edgeFunctionCreate) {
+ router.push(`/project/${ref}/functions`)
+ }
+ }, [edgeFunctionCreate, ref, router])
+
+ return (
+ <PageLayout
+ size="full"
+ isCompact
+ title="Create new edge function"
+ breadcrumbs={[
+ {
+ label: 'Edge Functions',
+ href: `/project/${ref}/functions`,
+ },
+ ]}
+ primaryActions={
+ <>
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ size="tiny"
+ type="default"
+ role="combobox"
+ aria-expanded={open}
+ icon={<Book size={14} />}
+ >
+ Templates
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="w-[300px] p-0">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Search templates..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No templates found.</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ {EDGE_FUNCTION_TEMPLATES.map((template) => (
+ <CommandItem_Shadcn_
+ key={template.value}
+ value={template.value}
+ onSelect={onSelectTemplate}
+ onMouseEnter={() => handleTemplateMouseEnter(template.content)}
+ onMouseLeave={handleTemplateMouseLeave}
+ className="cursor-pointer"
+ >
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center">
+ <Check
+ className={cn(
+ 'mr-2 h-4 w-4',
+ files.some((f) => f.selected && f.content === template.content)
+ ? 'opacity-100'
+ : 'opacity-0'
+ )}
+ />
+ <span className="text-foreground">{template.name}</span>
+ </div>
+ <span className="text-xs text-foreground-light pl-6">
+ {template.description}
+ </span>
+ </div>
+ </CommandItem_Shadcn_>
+ ))}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ <Button
+ size="tiny"
+ type="default"
+ onClick={handleChat}
+ icon={<AiIconAnimation size={16} />}
+ >
+ Chat
+ </Button>
+ </>
+ }
+ >
+ <FileExplorerAndEditor
+ files={files}
+ onFilesChange={setFiles}
+ aiEndpoint={`${BASE_PATH}/api/ai/edge-function/complete`}
+ aiMetadata={{
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ includeSchemaMetadata,
+ }}
+ />
+
+ <Form_Shadcn_ {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex items-center bg-background-muted justify-end p-4 border-t bg-surface-100 gap-3"
+ >
+ <div className="flex items-center gap-3">
+ <Label_Shadcn_ htmlFor="functionName">Function name</Label_Shadcn_>
+ <FormField_Shadcn_
+ control={form.control}
+ name="functionName"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex flex-col gap-0 m-0">
+ <div className="flex items-center">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ id="functionName"
+ type="text"
+ size={'large'}
+ placeholder="Give your function a name..."
+ className="w-[250px]"
+ {...field}
+ />
+ </FormControl_Shadcn_>
+ {form.formState.errors.functionName && (
+ <Tooltip>
+ <TooltipTrigger>
+ <AlertCircle className="w-4 h-4 text-destructive ml-2" />
+ </TooltipTrigger>
+ <TooltipContent>
+ {form.formState.errors.functionName.message}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </FormItem_Shadcn_>
+ )}
+ />
+ </div>
+ <Button
+ loading={isDeploying}
+ size="medium"
+ disabled={files.length === 0 || isDeploying}
+ onClick={handleDeploy}
+ >
+ Deploy function
+ </Button>
+ </form>
+ </Form_Shadcn_>
+ </PageLayout>
+ )
+}
+
+NewFunctionPage.getLayout = (page: React.ReactNode) => {
+ return (
+ <DefaultLayout>
+ <EdgeFunctionsLayout>{page}</EdgeFunctionsLayout>
+ </DefaultLayout>
+ )
+}
+
+export default NewFunctionPage