How to Prevent SQL Injection in Supabase RPC Functions and Edge Functions
SQL injection in Supabase apps hides in RPC functions and Edge Functions, not the client SDK. Learn how to find and fix it before it leaks your data.
SQL injection is one of the oldest web vulnerabilities — and one of the most dangerous. In a Supabase application, most developers assume they are automatically safe because the JavaScript client communicates through PostgREST. That assumption is half-right: the standard client path is parameterized and safe. The injection risk in a Supabase application lives somewhere else entirely — inside your database functions, your RPC calls, and your Edge Functions that reach Postgres directly.
This distinction matters because AI code generators do not understand it. When a developer asks an AI tool to build a full-text search feature, a dynamic reporting query, or an admin-only data export, the generated SQL function often uses string concatenation inside a PL/pgSQL function. That concatenation is a SQL injection sink — and it bypasses the Row-Level Security policies you spent time configuring. We cover how RLS policies work and when they fail in our Supabase RLS security guide, but RLS does not protect against injection inside a definer-security function that builds its own query. These are complementary problems, not the same one.
This guide covers exactly where SQL injection occurs in a Supabase application, how to identify vulnerable patterns in your database functions and Edge Functions, and how to rewrite them safely. It also covers what to test and what an automated scanner like DeployReady catches during a pre-launch scan. If your application was built partly with AI assistance or vibe-coded from a prompt, read this before you go live.
Why the Supabase JavaScript Client Does Not Protect Your Database Functions
The Supabase JavaScript client communicates with your Postgres database through PostgREST, which translates every method call into a parameterized HTTP request. When you write supabase.from('orders').select('*').eq('user_id', userId), PostgREST sends the user_id value as a bound parameter, not as an interpolated string. The database sees a parameterized query where the user value is passed separately from the query structure. An attacker who controls userId cannot break out of the parameter slot and inject new SQL — the structure of the query is fixed.
This protection disappears the moment your code calls supabase.rpc('my_function', { searchTerm: userInput }). The JavaScript call is still parameterized — the searchTerm value arrives at the database as a typed SQL argument, not as interpolated text. But what happens inside my_function is entirely up to your PL/pgSQL code. If the function body builds a dynamic query by concatenating that argument into a string and passes it to EXECUTE, you have a SQL injection vulnerability inside a Postgres function. The parameterization that protected you at the network layer does nothing once the database starts building its own SQL.
How SQL Injection Enters a Supabase RPC Function
The vulnerable pattern is dynamic SQL built with string concatenation. A full-text search function that takes a search term and builds a LIKE query is the most common case. The function receives the search term as a PL/pgSQL argument, constructs a query string by concatenating that argument into a SQL fragment, and executes it with EXECUTE. Because EXECUTE takes a plain text string and parses it as SQL, any SQL that an attacker injects into the search term becomes part of the query structure.
- →Full-text search functions: a function that accepts a search term and builds a LIKE query with string concatenation. An attacker can close the LIKE string and append a UNION SELECT to extract data from other tables, or end the query and issue a second statement.
- →Dynamic column selection: a function that accepts a column name from the client and interpolates it directly into a SELECT. Because column names are identifiers, not values, they cannot be passed as bound parameters — but they can be sanitized with format() and the %I specifier, which quotes and escapes identifiers safely.
- →Dynamic table routing: multi-tenant functions that accept a schema or table name and route queries accordingly. This pattern is especially dangerous in definer-security functions, which execute with the privileges of the function owner, not the calling user — bypassing RLS entirely.
- →Admin reporting functions: AI-generated reporting features that accept filter expressions or column lists from a frontend query builder. These are frequently built with direct concatenation because the query structure varies at runtime.
- →Database triggers with dynamic SQL: triggers that call EXECUTE with values derived from NEW or OLD record fields. If those fields contain user-controlled data and the trigger concatenates them into SQL, an insert or update operation can inject into the trigger.
The Safe Pattern: EXECUTE with USING for Values
PostgreSQL provides a safe mechanism for executing dynamic SQL with user-supplied values: the EXECUTE ... USING syntax. The query string contains numbered placeholders ($1, $2, and so on) and the USING clause supplies the actual values. The database engine treats the USING values as bound parameters, not as SQL text, so an attacker cannot break out of the value slot. The query structure is fixed by the SQL you write; the USING values fill the parameter slots and nothing more.
- →Replace every string-concatenated value with a $1, $2, ... placeholder inside the query string passed to EXECUTE.
- →Supply the actual values in the USING clause: EXECUTE 'SELECT id, name FROM items WHERE name LIKE $1' USING '%' || search_term || '%'. The percent signs are part of the value, not the query structure.
- →Never USING a column or table name — these are identifiers, not values, and cannot be parameterized. For dynamic identifiers, use format() with the %I specifier, which quotes and escapes the identifier: EXECUTE format('SELECT %I FROM %I WHERE id = $1', col_name, tbl_name) USING user_id.
- →Combine both patterns when you need dynamic identifiers and dynamic values: use format() to build the query template with quoted identifiers, then supply the values through USING.
- →Review every EXECUTE statement in your database functions. If you see the || operator used to build the query string with a user-supplied function argument, that is a SQL injection sink.
SQL Injection in Supabase Edge Functions
Edge Functions run on Deno. When an Edge Function connects to Postgres directly using a client library — such as postgres.js, pg, or the Supabase admin client bypassing PostgREST — it faces the same SQL injection risks as any Node.js application. The difference is that an Edge Function often runs with the service role key, which bypasses Row-Level Security entirely. A SQL injection vulnerability in an Edge Function that uses the service role key can read and modify every row in every table — not just the rows that belong to the attacking user. We cover other authentication mistakes in vibe-coded apps that compound this risk.
- →Use parameterized queries in every database client. The postgres.js client uses tagged template literals (sql`SELECT * FROM users WHERE id = ${userId}`) that parameterize automatically. Never build SQL strings by concatenating user input.
- →If you use the pg client, always pass values as the second argument to query(): client.query('SELECT * FROM orders WHERE user_id = $1', [userId]). Never interpolate userId into the query string.
- →Avoid the service role key in Edge Functions that process user-supplied input. Use the Supabase client initialized with the user's JWT for data access, so RLS policies apply and an injection cannot access other tenants' data.
- →Validate and normalize input before it reaches database queries. For search terms, strip or escape characters that have meaning in SQL text patterns (backslash, percent sign for LIKE) unless you intend them. For IDs, assert that they match the expected UUID format before using them in a query.
- →Scope Edge Function database permissions with a dedicated role that has SELECT, INSERT, UPDATE, and DELETE only on the tables the function legitimately needs. If the function is read-only, give it SELECT only. A SQL injection in a read-only function cannot write data.
What AI Code Generators Get Wrong About Dynamic SQL
AI coding assistants generate functional SQL, but they optimize for correctness of output, not for security of construction. When you prompt an AI tool to generate a search function, a dynamic filter, or a reporting query, the generated code often takes the shortest path to a working query — which is string concatenation. The output looks correct in a test environment where you control the input, and passes manual review unless the reviewer specifically knows to look for EXECUTE with concatenation.
- →Full-text search is the most common generated vulnerability. AI tools frequently generate patterns like EXECUTE 'SELECT ... WHERE name LIKE ' || '%' || input || '%', which is a SQL injection sink in your search endpoint.
- →Dynamic ORDER BY clauses are almost always generated with concatenation, because column names cannot be bound as USING parameters. The correct fix is to validate the column name against a fixed allowlist before incorporating it into the query with format() and %I.
- →Generated admin functions frequently run with SECURITY DEFINER, which executes the function as the function owner rather than the calling user. A SQL injection in a SECURITY DEFINER function bypasses RLS and runs with elevated privileges.
- →AI-generated triggers that inspect record values often use EXECUTE to handle variable column structures. Each EXECUTE in a trigger should be reviewed for string concatenation with NEW or OLD field values.
- →Review every PL/pgSQL function in your Supabase database, not just the ones you wrote manually. Use the Supabase SQL editor to query pg_proc and pg_get_functiondef to list all custom functions and inspect their bodies for EXECUTE with the || operator.
How to Test Your Supabase Application for SQL Injection
Testing for SQL injection in a Supabase application is different from testing a traditional REST API because the client SDK hides the underlying SQL. You need to test the RPC endpoints directly — both through the application UI and through direct calls to the Supabase REST API. A structured pre-launch security checklist covers this alongside the broader set of checks, but SQL injection in RPC functions deserves a dedicated pass.
- →Test every field that accepts text input and feeds an RPC function. Submit a single quote ( ' ) as the value and observe whether the application returns a 500 error, a PostgreSQL error message, or behaves differently from a normal input. An error that references syntax near the quote is a strong indicator of string concatenation.
- →Test boolean injection: submit a payload like x' OR '1'='1 as a text value. If the query returns all rows instead of matching rows, the input is being treated as SQL structure rather than a value.
- →Test the supabase.rpc() calls in your application by intercepting the HTTP request and modifying the JSON body. The Supabase REST API accepts RPC calls at /rest/v1/rpc/function_name. Send the modified request with SQL injection payloads in the JSON parameter values.
- →Review the Postgres query logs for your database. Enable statement logging in Supabase's database settings and replay your test inputs. If you see the injected text appearing inside the SQL statement rather than as a parameter value, the function is vulnerable.
- →Use the Supabase dashboard's SQL editor to review the source of every EXECUTE statement in your database functions. Look for functions that use the || operator to concatenate arguments into a query string rather than passing them through USING.
Using DeployReady to Catch SQL Injection Patterns Before Launch
DeployReady, Belsoft's open-source CLI tool, runs static analysis across your codebase and flags patterns associated with injection vulnerabilities. For Supabase projects, it checks Edge Function code for string-concatenated SQL queries, service role key usage in client-facing code, and missing input validation before database calls. Running npx deployready before every deploy catches injection sinks that reach production in generated or reviewed code alike.
- →DeployReady flags template literal SQL that interpolates variables directly: any pattern where a variable is embedded inside a SQL string without using a parameterized client's tagged template syntax.
- →It detects .env exposure risks — service role keys in client-side bundles — which compound injection risk by giving an attacker elevated database access.
- →For TypeScript Edge Functions, it checks whether database queries pass user-controlled values as arguments to a parameterized client or embed them in a string.
- →DeployReady produces a 0-100 readiness score. A score below 80 indicates unresolved findings that should block a production deploy. Run it as a CI gate on every pull request so injection sinks are caught in code review, not in a post-launch audit.
- →DeployReady does not replace a manual review of your Supabase database functions — it cannot introspect your SQL definitions without connecting to the database. Use it alongside the SQL editor review described above, not instead of it.
Frequently Asked Questions
Can Supabase get SQL injected?
Yes, in specific contexts. The standard Supabase JavaScript client communicates through PostgREST using parameterized queries, which are safe. The injection risk exists inside your Supabase database functions (RPC functions written in PL/pgSQL) and inside Edge Functions that build SQL strings with string concatenation. If your application uses dynamic SQL with EXECUTE and the || operator, it is vulnerable to SQL injection regardless of how the data arrived at the database.
Is Supabase PostgREST safe from SQL injection?
PostgREST is safe from SQL injection for all standard CRUD operations (.from().select().insert() and so on). It parameterizes all values before sending them to Postgres. PostgREST does not protect you from SQL injection that occurs inside a database function that your code calls via supabase.rpc() — that vulnerability is in your PL/pgSQL code, not in PostgREST.
How do I write safe dynamic SQL in a Supabase RPC function?
Use EXECUTE ... USING for all value parameters. Write your dynamic query as a string with $1, $2, ... placeholders and pass the actual values in the USING clause: EXECUTE 'SELECT id FROM items WHERE name LIKE $1' USING search_term. For dynamic identifiers (column names, table names), use PostgreSQL's format() function with the %I specifier, which quotes and escapes the identifier safely. Never concatenate user-supplied function arguments directly into a query string.
What is the risk of SQL injection in a SECURITY DEFINER Supabase function?
A SECURITY DEFINER function runs with the privileges of the function owner, which is typically a highly privileged role in Supabase. A SQL injection inside a SECURITY DEFINER function bypasses Row-Level Security policies and can read or modify data across all tenants, regardless of which user called the function. This is one of the most critical SQL injection scenarios in a multi-tenant Supabase application. Avoid SECURITY DEFINER unless strictly necessary, and review every such function for injection vulnerabilities first.
Does an AI code generator like Cursor or Lovable produce SQL-safe database functions?
Not reliably. AI code generators produce working SQL but do not consistently apply parameterization in dynamic queries. Full-text search functions, dynamic ORDER BY clauses, and admin reporting queries generated by AI tools frequently use string concatenation rather than EXECUTE ... USING. All AI-generated PL/pgSQL functions that contain EXECUTE should be reviewed manually for the || operator and replaced with safe alternatives before production deployment.
How Belsoft Helps You Find and Fix SQL Injection Before It Finds You
SQL injection vulnerabilities in Supabase RPC functions and Edge Functions are invisible to automated scanners that only test the HTTP surface — they require a manual review of your database function definitions and your server-side code. A Belsoft security audit includes exactly this: engineers who know how Supabase applications break read your database functions, your Edge Functions, and your RLS policies by hand. We review every EXECUTE statement, every dynamic query, and every location where user input touches database code. We find the injection sinks before an attacker does, write the fixes alongside you, and retest to confirm they hold.
DeployReady runs the automated baseline — a 30-check scan that catches injection patterns, exposed secrets, and missing security headers in seconds, with a free npx command and no data leaving your machine. A Belsoft audit adds the depth that static analysis cannot reach: the logic inside your database, the authorization checks in your Edge Functions, and the interaction between your application components. Together they give you confidence that your Supabase application is production-ready, not just demo-ready.
“The Supabase client protects the path you can see. The vulnerabilities live in the SQL you wrote yourself — usually the functions you asked an AI to generate.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
