Chapter 1. Managed app and data platforms (Foundations: Vercel & Supabase)
Learning objectives
- Distinguish and configure Vercel's deployment environment (Preview and Production) separation principles and environment variable exposure boundaries (
NEXT_PUBLIC_versus server-only variables). - Lock the preview environment from the outside using Deployment Protection, and securely design bypass secrets (
x-vercel-protection-bypass) so that automated tests and webhooks can pass through. - Place the serverless function region (e.g., Seoul
icn1) to match the database location, and explain the impact of execution time limits (maxDuration), Fluid Compute, and streaming on AI response latency and costs. - Understand the difference between transaction mode (port 6543) and session mode (port 5432) of Supavisor, Supabase Postgres's connection pooler, and choose a connection configuration tailored to the workload.
- Explain the operational difference between the
USINGandWITH CHECKclauses of Row Level Security (RLS), and write policies that preserve the trust boundaries of publishable keys (sb_publishable_) and secret keys (sb_secret_). - Design Supabase Auth redirect URL allowlists (web origins and mobile deep links) and signed URL (Signed URL) access controls for private Storage buckets.
Introduction
There was a startup team that built an impressive AI document summarization web app with a coding agent during a weekend hackathon. When they pushed the code that ran smoothly on their local computer to GitHub and connected it to Vercel, a globally accessible HTTPS address was created within one minute. When they connected a Supabase project, login, database, and file uploads were completed all at once. The team cheered and posted their launch announcement on social media on Monday morning.
However, within two hours of the launch, three incidents occurred in succession. First, a user opened the network tab and JavaScript bundle in browser developer tools and discovered the team's paid LLM API key and Supabase administrator key out in the open. This was because the developer had prepended NEXT_PUBLIC_ to every environment variable to make reading variables easier within the framework. Second, when about 200 concurrent users rushed in, the summary screen froze for more than three seconds and ground to a halt while throwing a database connection exhaustion error: remaining connection slots are reserved for non-replication superuser connections. This happened because the serverless functions were spinning up in US East (iad1) while the database was in Seoul (icn1), which lengthened round-trip latency, and on top of that, each function instance held on to a direct connection (port 5432) without letting go. Third, the preview (Preview) URL for next month's unreleased paid feature branch was exposed to search engines and external communities, allowing anyone to access and view the experimental feature.
While managed platforms such as Vercel and Supabase reduce infrastructure setup time from days to minutes, this by no means implies that "leaving the defaults as they are is secure." Rather, precisely because deployment is easy, a single environment variable, a single port number, or a single RLS checkbox directly links to production security boundaries. In this chapter, we examine step by step the core principles and design criteria that elevate managed app and data platforms from the level of a 'toy prototype' to that of 'real-world production'.
Key concepts
Vercel environment separation: The boundary between Preview and Production
The first pillar to establish in a managed app platform is environment separation (Environment Separation). When connected to a Git repository, Vercel distinguishes three primary environments: Development, which runs on a developer's laptop; Preview, which is automatically generated for each feature branch or pull request (PR); and Production, which is connected to the real customer domain when merged into the main branch (e.g., main) or explicitly promoted.
By way of analogy, Production is the main dining room of a restaurant welcoming guests, and Preview is a test kitchen for tasting new menu items and testing kitchen workflow. What would happen if the test kitchen and the main dining room shared the same safe, the same ingredient pantry, and the same order slips? While testing a new payment cancellation in the test kitchen, someone might cancel a real payment made by a customer in the main dining room, or thousands of fake test orders might get mixed into the main dining room's ledger.
Therefore, environment separation follows three ironclad rules:
| Category | Preview environment | Production environment | Incidents when not separated |
|---|---|---|---|
| Domain | Unique preview URL per branch and commit | Live service domain (e.g., app.example.com) |
Unverified code is exposed to real customers |
| Database and storage | Dedicated development/staging DB or isolated test project | Production DB containing real customer data | Migration experiments or E2E tests corrupt production data |
| External payment and messaging keys | Sandbox (test) keys, dispatch blocking mode | Live payment keys, live dispatch keys | Notifications are sent to real customers or real charges occur during testing |
| Authentication and developer backdoors | Limited test accounts allowed (only behind Deployment Protection) | Test logins and authorization APIs completely disabled | An attacker gains administrator privileges through development authorization paths |
In particular, when registering environment variables in Vercel, the target environments (Production, Preview, Development) can be specified for each variable using individual checkboxes. If someone inadvertently checks all three environments when registering a production database connection string (DATABASE_URL) or a live payment secret key, any developer can open a PR, trigger a Preview build, and print out production secret values in console logs or connect directly to the production DB. Production secrets must be injected exclusively into the Production environment, and separate staging credentials must be injected into the Preview environment. In addition, when isolated configurations are needed for different Preview branches, branch-specific environment variables (Branch-specific Environment Variables) can be configured to narrow the scope of experimentation.
Environment variables and the NEXT_PUBLIC_ exposure boundary
Web application frameworks (such as Next.js) handle code executed on the server and client code sent to and executed in the user's browser together within a single repository. The security incident that both beginners and experienced developers encounter most frequently here is environment variable bundle exposure.
For security purposes, build tools treat all environment variables as server-only (Server-only) by default. That is, variables such as process.env.OPENAI_API_KEY or process.env.SUPABASE_SERVICE_ROLE_KEY can be read only in Vercel's server environment—such as Server Components, API routes, and Server Actions—and are not included in the JavaScript files sent down to the browser.
On the other hand, if a variable name begins with NEXT_PUBLIC_ (e.g., NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_SUPABASE_URL), the story changes completely. At build time, the build tool finds the actual string value of this variable and literally bakes it directly into the client JavaScript bundle file (Inlining).
// Server-only code (Route Handler / Server Action) — safe
// This code runs only on the server and is not included in the browser bundle.
const apiKey = process.env.LLM_SECRET_API_KEY;
// Client Component ("use client") — exposed to the entire world!
// At build time, the code below is replaced with an actual string such as "https://proj.supabase.co",
// allowing anyone to read it in browser developer tools (Sources/Network).
const publicUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
There are two important properties to remember here:
- Values prefixed with
NEXT_PUBLIC_are not secrets. No matter how much one names itNEXT_PUBLIC_SECRET_KEY, that value can be seen by anyone in the world just like text written in the web page's HTML source. Therefore, you must never prepend theNEXT_PUBLIC_prefix to LLM API keys, database connection strings,service_rolekeys, webhook signature verification secrets, or encryption keys. NEXT_PUBLIC_variables are fixed at build time (Build-time). While server-only environment variables can be read when the server processes a request,NEXT_PUBLIC_values inlined into the client bundle are already baked into static files and uploaded to the CDN. Therefore, after changing the value in the dashboard, you must redeploy (Redeploy) and build anew for the change to be reflected in the browser.
Caution
Occasionally, when a server-only variable evaluates to undefined in a Client Component, people attempt to quickly resolve the error by prepending NEXT_PUBLIC_ to an existing secret variable. This is equivalent to hanging the safe key on the bulletin board at the building's front entrance because the safe won't open. Features that require a secret key on the client (e.g., LLM calls, payment authorizations) must have their architecture restructured so that they always go through server API routes or Server Actions.
Deployment Protection and automation bypass design
A Preview deployment creates a unique URL for each PR (e.g., my-app-git-feat-new-ui-team.vercel.app). This URL is a public endpoint accessible from anywhere on the internet as long as the address is known. If Deployment Protection is not turned on, new features that have not yet completed security review, internal admin screen drafts, or pre-launch marketing pages are exposed directly to the outside, and search engine bots might even index them.
Vercel's Deployment Protection (Deployment Protection) is a feature that places an authentication gateway in front of Preview deployments (as well as the default production .vercel.app domain).
- Vercel Authentication: Restricts access to Preview URLs exclusively to logged-in members belonging to the same Vercel team.
- Password Protection: Opens the screen only to external collaborators or reviewers who know an additional password.
- Trusted IPs: Allows access only from designated in-house static IPs or VPN gateway ranges.
Problems arise when automated tools rather than humans must access the Preview URL. For example, when running end-to-end (E2E) tests with Playwright in GitHub Actions against a deployed Preview environment, when a test webhook from an external payment or messaging service calls /api/webhook on the Preview server, or when a backend CI pipeline sends a health check, all of them fail because they are blocked by the Vercel Authentication login screen (HTTP 401/403 or a login redirect).
In such cases, the standard solution used instead of disabling Deployment Protection entirely is Protection Bypass for Automation (Protection Bypass for Automation). When a bypass secret (VERCEL_AUTOMATION_BYPASS_SECRET) is generated in project settings, the automation client sends the following headers with its request:
GET /api/health HTTP/1.1
Host: my-app-git-feat-team.vercel.app
x-vercel-protection-bypass: <issued_bypass_secret_value>
x-vercel-set-bypass-cookie: true
- If the
x-vercel-protection-bypassheader value matches the project's bypass secret, the Vercel Edge skips the authentication screen and passes the request through to the function. - When multiple sub-resources and pages must be requested consecutively after landing on the first page, such as in browser-based E2E tests (Playwright, etc.), sending the
x-vercel-set-bypass-cookie: trueheader (orsamesitenonefor multi-domain/cross-site testing) to set a bypass cookie allows subsequent requests to pass through seamlessly as well. - For services where custom HTTP headers cannot be inserted, such as external third-party webhooks, the query parameter (
?x-vercel-protection-bypass=<secret>) approach can be used in limited scenarios; however, because URLs may be retained in logs, the header approach should be prioritized and must always be paired with HMAC signature verification of the webhook payload itself.
Function region placement, execution time limits, Fluid Compute, and streaming
Static files (images, CSS, bundled JS) are replicated across global CDN edge nodes and delivered immediately from the location closest to the user. However, where should serverless functions (Serverless Function) that query databases and call LLM APIs be placed?
Many developers assume that "functions must also be close to the user to be fast," or configure nothing, leaving the function in Vercel's default region, US East (iad1, Washington, D.C.). However, if the database (Supabase Postgres) is located in Seoul (ap-northeast-2, Vercel region code icn1), a critical issue emerges.
Let us compare two configurations when a user located in Seoul sends a request:
| Configuration | Request flow and round-trip distance | Network latency when executing 5 DB queries |
|---|---|---|
Function iad1 (US) + DB Seoul |
Seoul user → US function (180ms) → Seoul DB 5 round-trip queries (5 × 180ms = 900ms) → Seoul user (180ms) | Approximately 1,260ms or more (explodes as queries increase) |
Function icn1 (Seoul) + DB Seoul |
Seoul user → Seoul function (15ms) → Seoul DB 5 round-trip queries (5 × 3ms = 15ms) → Seoul user (15ms) | Approximately 45ms (database and function in the same region) |
While there is only a single round trip between the user and the function when processing a web request, round trips between the function and the database happen serially (Waterfall) multiple times within a single request—such as for authentication checks, profile lookups, permission checks, and history logging. Therefore, the serverless function region must be pinned to the region closest to the primary database (Primary DB) (e.g., icn1 if the DB is in Korea). The single setting regions: ["icn1"] in vercel.json immediately eliminates hundreds of milliseconds of latency.
In AI applications, the function execution time limit (maxDuration), streaming, and Fluid Compute are just as critical as regional placement.
- Execution time limit (
maxDuration): While ordinary CRUD APIs complete within one second, reasoning model (Reasoning Model) calls or multi-step tool-executing agents take from 30 seconds to several minutes until the response finishes. The default execution limit for Fluid Compute is 300 seconds, and on the Pro plan it can be increased up toexport const maxDuration = 800;on a per-route basis. If the task duration can exceed the default limit, configure the limit separately for that route. Otherwise, the function times out and disconnects while the model is generating an answer, leaving the user with a blank screen and wasting token costs. - Streaming (Streaming, SSE / ReadableStream): Flushing tokens to the browser as soon as the LLM emits the first token significantly reduces time to first byte (TTFB) and perceived latency, while keeping the connection alive to avoid idle timeouts from intermediate proxies.
- Fluid Compute: Traditional serverless functions allocated one instance per request, monopolizing CPU and memory and racking up costs even while the function was idly waiting for slow streaming responses from OpenAI or Anthropic APIs (I/O wait). Taking advantage of the asynchronous I/O characteristics of Node.js and Python runtimes, Vercel's Fluid Compute allows a single warm (Warm) function instance to process other requests concurrently (Concurrency) while waiting on network I/O. As a result, the frequency of cold starts (Cold Start) decreases. Billing is also based on Active CPU, so CPU charges pause while code waits for I/O. However, allocated memory charges continue even during I/O waits as long as there are requests being processed. Furthermore, when audit logging or usage aggregation needs to be wrapped up after the response has already been sent to the user, using the
waitUntil()API completes background post-processing without adding latency to the user response.
Supabase Postgres and Supavisor connection pooling: 6543 versus 5432
PostgreSQL traditionally employs a heavy connection model where the server operating system spawns a separate process (Process) and allocates memory for every single client connection (Connection). Consequently, the number of direct connections (max_connections) that a single database can maintain concurrently is strictly limited to several dozen or a few hundred, depending on instance size.
In a traditional persistent server environment (e.g., two EC2 instances), each server opens only 10 connections at startup and reuses them (20 in total), posing no issues. In a serverless environment like Vercel, however, the moment traffic surges, function instances multiply into dozens or hundreds; if each instance attempts to establish a direct TCP+TLS handshake with PostgreSQL, the connection limit is exhausted in an instant.
To solve this problem, Supabase places a cloud-native connection pooler (Connection Pooler) called Supavisor in front. Supavisor accepts thousands of lightweight client connections and proxies queries while maintaining only a small number of physical connections to the underlying PostgreSQL. At this point, it provides two modes depending on the port number, and distinguishing between these two is central both to exams and to practical work.
| Comparison item | Transaction mode (Transaction Mode) | Session mode (Session Mode) | Direct connection (Direct Connection) |
|---|---|---|---|
| Default port | 6543 (Supavisor) | 5432 (Supavisor pooler host) | 5432 (Direct DB host, IPv6 default) |
| Backend connection holding unit | Borrowed only during a single transaction (BEGIN to COMMIT) and immediately returned to the pool |
Monopolizes backend connection 1:1 until the client disconnects | 1:1 direct connection to Postgres process without a pooler |
| Suitable workloads | Serverless functions (Vercel, Edge, Lambda), high-concurrency web APIs | Persistent backend servers, long-running tasks requiring session state (SET, temporary tables) |
Schema migrations (CREATE/ALTER), pg_dump, administrative tools |
| Session-level feature constraints | Because the connection changes with every transaction, session-level PREPARE (Prepared Statement), SET, LISTEN/NOTIFY, and session temporary tables are not retained |
All session-level features function normally (however, concurrent connection limits fill up just as quickly as direct connections) | All Postgres features available |
There are three practical rules that must be followed when using Supavisor in serverless applications:
- Use port 6543 (transaction mode) for runtime application traffic. Even if hundreds of functions spin up, connection exhaustion is prevented because they borrow a database connection only for the few milliseconds it takes to execute actual queries and return it immediately.
- Disable the prepared statement cache in ORMs/drivers or enable compatibility options. In transaction mode, the backend connection containing
PREPARE stmt_1created in the first query may differ from the backend connection assigned to the second query, which can trigger aprepared statement "s1" does not existerror (e.g., append?pgbouncer=trueto the connection string in Prisma, or specifyprepare: falseinpostgres.js). - Separate database migrations (
migrate) into session mode or direct connections (5432). Many migration tools use PostgreSQL's session-level advisory locks (pg_advisory_lock) to prevent concurrent execution of two migrations, or perform long DDL operations. Therefore, the standard practice is to manage a runtimeDATABASE_URL(6543) and a migration-onlyDIRECT_URL(5432) separately. If configuration values must be injected inside transaction mode, useSET LOCAL(e.g.,SET LOCAL role,SET LOCAL app.user_id = ...), which is valid only within the current transaction and resets automatically upon commit, instead ofSET, which persists across the entire session, preventing state from leaking to other requests.
Row Level Security (RLS): The exact working principles of USING and WITH CHECK
Supabase layers Data API (PostgREST) on top of PostgreSQL, enabling data to be read and written directly from browsers or mobile apps. While an immensely convenient feature, the database table itself becomes the first line of defense on the internet. If Row Level Security (RLS, row-level security) is not enabled on a table in an exposed Data API schema (ALTER TABLE ... ENABLE ROW LEVEL SECURITY is not run), any role with grants can read, modify, and delete every row in that table. If the anon role holds grants, anyone holding only the public publishable key can do the same.
The moment RLS is enabled, the table enters a Default Deny state. That is, unless an operation is explicitly permitted by a policy (Policy), not a single row can be seen or written (with exceptions for the table owner or service_role holding BYPASSRLS privileges).
The most confusing point when designing RLS policies is the distinction in roles between the USING clause and the WITH CHECK clause. By analogy, USING asks, "Which items can be retrieved and viewed from the warehouse? (filtering existing rows)," while WITH CHECK asks, "Does an item newly placed or modified and placed into the warehouse meet acceptance criteria? (validating new rows)."
ALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;
-- SELECT: You can view only rows that you own.
CREATE POLICY "docs_select_own" ON public.documents
FOR SELECT TO authenticated
USING ( (SELECT auth.uid()) = owner_id );
-- INSERT: You can insert new rows only under your own name.
CREATE POLICY "docs_insert_own" ON public.documents
FOR INSERT TO authenticated
WITH CHECK ( (SELECT auth.uid()) = owner_id );
-- UPDATE: Select only your own rows (USING), and they must still remain your own after modification (WITH CHECK).
CREATE POLICY "docs_update_own" ON public.documents
FOR UPDATE TO authenticated
USING ( (SELECT auth.uid()) = owner_id )
WITH CHECK ( (SELECT auth.uid()) = owner_id );
-- DELETE: You can delete only rows that you own.
CREATE POLICY "docs_delete_own" ON public.documents
FOR DELETE TO authenticated
USING ( (SELECT auth.uid()) = owner_id );
Summarizing how both clauses operate by SQL statement in a table yields the following:
| SQL statement | Role of USING clause (checking existing rows) |
Role of WITH CHECK clause (checking new/modified rows) |
Common design mistakes |
|---|---|---|---|
SELECT |
Includes only rows where condition is true (true) in results (silently hides rows that are false) |
Not applicable (no new rows created) | Failing to enable RLS at all, or exposing an entire sensitive table with USING (true) |
INSERT |
Not applicable (no existing rows to compare) | Rejects with an error if the newly inserted row fails the condition | Leaving WITH CHECK (true), allowing inserting rows under someone else's owner_id |
UPDATE |
Filters existing rows that can be targets of modification first | Re-validates whether the new state after modification satisfies the condition | Writing only USING without controlling modified columns, or transferring ownership to someone else |
DELETE |
Filters existing rows that can be deleted | Not applicable (no resulting new rows) | Mistakenly assuming a SELECT policy alone blocks deletions, or omitting conditions |
Note
In an UPDATE policy, if only the USING clause is written and the WITH CHECK clause is omitted, PostgreSQL copies and applies the condition of the USING clause to WITH CHECK by default. In practice, however, conditions before and after modification often differ—such as "only my posts in draft (status = 'draft') can be edited (USING), and after modification the status must be draft or submitted (status IN ('draft', 'submitted')), not directly changed to approved (approved) (WITH CHECK)"—so explicitly writing both clauses separately is a safer practice. Furthermore, wrapping auth.uid() in a scalar subquery like (SELECT auth.uid()) = owner_id and indexing owner_id allows the PostgreSQL optimizer to evaluate the function call result only once (InitPlan), significantly improving performance when querying large volumes of rows.
Trust boundaries of publishable and secret keys
A Supabase project has two kinds of API keys with completely different roles. The current standard is publishable keys starting with sb_publishable_ and secret keys starting with sb_secret_. The former anon keys and service_role keys are legacy keys being sunset by the end of 2026.
- publishable key (
sb_publishable_, legacyanonkey): A public key designed to be safe for inclusion in browsers or mobile apps. Before a user signs in, it operates under PostgreSQL'sanonrole, and once the user signs in with Supabase Auth and receives a JWT access token, requests switch to theauthenticatedrole. In either case, all queries are strictly governed by RLS policies. In other words, public exposure of a publishable key is expected, and security rests not on key secrecy, but on the completeness of RLS policies. - secret key (
sb_secret_, legacyservice_rolekey): A superuser secret key provided for backend administrative tasks, incoming webhook handling, and batch aggregations. When sending requests with this key, PostgreSQL'sBYPASSRLSprivilege activates, completely bypassing all RLS policies on tables and allowing reading, writing, and deleting any row.
Therefore, the secret key is nothing less than the database's root master key.
- It must never be included in browsers (
NEXT_PUBLIC_), mobile app binaries, or public Git repositories. - Even within a backend server, carelessly sharing a common
service_roleclient in paths that process ordinary user requests creates grave danger. The momentservice_roleis used, the RLS safety net is disabled; if a developer accidentally omits a singleWHERE user_id = ?condition in code, another customer's data will be returned directly (the Confused Deputy problem). - Server code handling user requests should receive the user's session and query with an RLS-enforced client (or transaction-local context), while
service_rolemust be isolated and used only in the minimal paths where the server must act on its own without a user session, such as processing payment webhooks or system cron jobs.
Supabase Auth callback allowlist and mobile/web authentication flows
When using social login (Google, Apple, GitHub), email magic links (Magic Link), or password reset links, the authenticated user returns carrying a token or authorization code to the address designated by the service (redirectTo).
If an attacker could arbitrarily alter the redirectTo=https://evil.example.com/callback parameter in the login request and the authentication server permitted it without inspection (Open Redirect vulnerability), the access token or authorization code would be handed straight over to the attacker's server the moment the victim completed a legitimate login.
To prevent this, Supabase Auth enforces configuring two things:
- Site URL: The default production origin to return to when
redirectTois not specified (e.g.,https://aidan.agentcat.app). - Redirect URLs (Allowlist): The exact list of URLs or patterns allowed for
redirectTo. If a redirect is requested to an address not registered here, Supabase Auth rejects it or redirects back to the default Site URL.
Services operating both web and mobile apps must manage this allowlist with precision:
| Environment and platform | Allowlist registration example | Points to watch |
|---|---|---|
| Production web | https://app.example.com/** |
Specify https:// rather than http://, and use subdomain wildcards (https://*.example.com/**) restrictively only when there are no subdomains an attacker could control |
| Preview deployment web | https://*-myteam.vercel.app/** |
Opening too broadly, such as https://*.vercel.app/**, risks leaking tokens to someone else's Vercel app, so scope it strictly to the project and team |
| Mobile native app | myapp://auth/callback |
Register custom URL schemes (Deep Link) or Universal Links / App Links with exact paths |
| Local development environment | http://localhost:3000/** |
Ensure that local development addresses do not become the default Site URL in production |
In addition, when server-side rendering (SSR) and mobile apps coexist, the PKCE (Proof Key for Code Exchange) flow—a one-time authorization code exchange method—is used as the standard. Unlike the implicit (Implicit) flow that transmits tokens directly in the URL hash (#access_token=...), PKCE requires the code_verifier generated by the initiating client to exchange the one-time code for a session token, greatly reducing the risk of intermediary interception.
Supabase Storage: Public versus private buckets and signed URLs (Signed URL)
AI services frequently handle user-uploaded PDF documents, voice recordings, identification and certificate copies, and generated output images. Supabase Storage stores the files themselves in object storage (S3-compatible), while who can access which path (bucket_id, name) in which bucket is controlled by RLS policies placed on the storage.objects table in PostgreSQL.
When creating a bucket, you first choose between a public bucket (Public Bucket) and a private bucket (Private Bucket):
- Public bucket (
public = true): Anyone who knows the file path (URL) within the bucket can download it immediately via the CDN without authentication headers or RLS lookups. It must be used only for assets with zero confidentiality requirements, such as service logos, public course covers, or shared badge images visible to anyone. Believing that putting contracts in a public bucket is safe because the filename was made obscure with a UUID is dangerous (if the URL leaks even once through browser history, referrer headers, or logs, it can be viewed indefinitely). - Private bucket (
public = false): All download and upload requests require authentication and must pass RLS policies onstorage.objects. Customer-uploaded source documents, personalized score report PDFs, photos taken during exams, and all files that must only be viewed by authorized parties must reside in private buckets.
How, then, do we safely serve files in a private bucket to a logged-in user, or allow an external parser worker to read them temporarily? Two primary patterns are used:
- User session-based RLS + path conventions: Store file paths systematically, such as
{user_id}/{document_id}.pdf, and apply an RLS policy to thestorage.objectstable with the condition(storage.foldername(name))[1] = (SELECT auth.uid()::text)so that users can read and write files only in their own folder. - Time-limited signed URLs (Signed URL): After verifying user authorization on the server, issue an authenticated cryptographically signed URL with a short expiration time (e.g., 60 seconds to 5 minutes) via
createSignedUrl(path, 60)and deliver it to the client. Because this URL becomes invalid automatically once the expiration timestamp passes, even if the link leaks, the exposure window is minimized. When a client uploads large files directly to storage without passing through the server, issuing a signed upload URL (createSignedUploadUrl) bypasses serverless function payload size limits (e.g., Vercel's 4.5 MB request body limit) while still maintaining access control.
Active CPU billing and Vercel Sandbox
The calculation method for Vercel function pricing has fundamentally changed (as of June 2026 documentation). Previously, billing was calculated by converting the wall-clock time a function was running into GB-seconds. It is now divided into three categories: Active CPU, allocated memory, and invocation count. Active CPU accumulates only while code is actively executing instructions. During I/O intervals waiting for LLM responses, CPU billing halts, but memory billing does not. As long as even one request being processed remains, charges for memory allocated to the instance continue. When estimating costs for AI routes with long response waiting times, treating waiting time as KRW 0 will lead to incorrect calculations.
Code generated by agents or scripts uploaded by users is not executed inside ordinary functions. This is because functions have access to production data and secrets. Vercel Sandbox runs such unverified code inside an isolated Firecracker microVM. Each sandbox has a separate file system and network. Pricing is billed based on Active CPU and allocated memory, and limits vary significantly by plan (as of September 2026):
| Item | Hobby | Pro | Enterprise |
|---|---|---|---|
| Maximum session duration | 45 minutes | 24 hours | 24 hours |
| Concurrent sandboxes | 10 | 10,000 | 10,000 |
| Maximum resources per sandbox | 4 vCPU / 8 GB | 8 vCPU / 16 GB | 32 vCPU / 64 GB |
Side-project team 'Acorn Lab' moved code modified by a coding agent into a sandbox on the Hobby plan to run integration tests. If a test suite took 50 minutes, it ran into the 45-minute session limit first. The team had two choices: split the tests and distribute them within the limit of 10 concurrent executions, or upgrade to Pro to use 24-hour sessions.
Note
For deployment features as well, check the plan limits first. Rolling Releases, which roll out new deployments in phases, are available only on Pro and Enterprise plans. Pro teams can enable it for only one project, and Enterprise limits are set individually per team (as of September 2026).
Discontinuation of automatic Data API exposure and RLS
Supabase changed its default settings for table exposure. Previously, creating a table in the public schema opened it immediately to Data API. New projects have followed the new rule since May 30, 2026, and existing projects have followed it since October 30, 2026. Currently, newly created tables in public across all projects are not automatically exposed to Data API. Whether or not to expose a table to the API has effectively become a decision that teams must make explicitly.
Exposure and RLS are distinct gates. Exposure determines whether an API request can reach that table, while RLS determines which rows a request that reaches it can read and modify. Supabase documentation advises enabling RLS on every single table without exception if the schema is exposed. This is because any role holding grants can read and write to an exposed table that has RLS disabled. If the anon role holds grants, anyone with just the publishable key embedded in the app can take the entire table. The cessation of automatic exposure does not reduce the work required for RLS. What has changed is the order. Only after enabling RLS and writing policies should a table be exposed.
GraphQL defaults have also shifted toward being closed. Supabase has stopped automatically enabling the pg_graphql extension since January 2026. Starting with pg_graphql 1.6.0 released in May 2026, introspection is also turned off by default. Tools that automatically generate type code usually read schemas via introspection. Teams using such tools should check these default settings first.
Suppose a course review service team created a new public.review_drafts table in November 2026, but the draft list did not appear in their app. Because the table was created after October 30, the first place the engineer checked was the exposure setting rather than policies. Even so, they did not rush to expose it first. Only after enabling RLS and attaching a SELECT policy that made only one's own drafts visible did they open the table to Data API.
Legacy API key and Postgres version schedules
Supabase is sunsetting anon keys and service_role keys by the end of 2026 and migrating to keys starting with sb_publishable_ and sb_secret_. The permission distinction remains the same. The publishable key is a public key that can be embedded in browsers and apps, and its security boundary is still RLS. The secret key bypasses RLS, so it is kept only on the server. What changes are the key names and the replacement procedures. The prefix alone distinguishes whether a key is for public use or server-only use. If sb_secret_ appears in client code during code reviews or secret scanning, it is treated immediately as an incident.
Replacement begins with introducing the new key. Issue the new key, insert it into environment variables, deploy, and verify normal operation. Disabling the legacy key is the very last step. Reversing the order causes code still using the old key to stop all at once. Clean up environment variable names at the same time. If ANON or SERVICE_ROLE remains in the name, the next maintainer will be confused about which system the key belongs to.
Postgres versions share the same calendar. Supabase ended support for Postgres 14 on July 1, 2026. If a project is still running 14, schedule an upgrade first. The default database image for self-hosted Supabase switched from Postgres 15 to Postgres 17 on June 17, 2026. If spinning up a new environment with the default image, check that major versions do not clash with existing 15 environments.
The iOS older-version binary of the learning app 'GatherNote' contained the anon key. Unlike web applications, a mobile app cannot migrate all users to a new key with a single deployment. The team first published a new version containing the publishable key to the app store, verified through logs that requests from older versions had decreased sufficiently, and only then disabled the legacy key. They scheduled the release date for the new version by counting backward from the end-of-2026 sunset date.
Going deeper
Serverless cold starts, DB TLS handshakes, and transaction-local context
Let us examine at the network packet level why regional distance and pooler mode are so critical when connecting serverless functions to PostgreSQL.
When a function instance wakes up anew (Cold Start) and establishes a new connection to remote PostgreSQL, it must step through the following process in order:
- Looks up the IP of the database host through a DNS query.
- Spends one round trip (1 RTT) on the TCP 3-way handshake (
SYN→SYN-ACK→ACK). - Spends 1–2 more round trips (1–2 RTT) on PostgreSQL
SSLRequestnegotiation and the TLS 1.2/1.3 handshake to verify certificates and exchange symmetric keys. - Spends 2 round trips (2 RTT) on sending the PostgreSQL startup packet and SCRAM-SHA-256 authentication (Challenge-Response).
- Finally sends the first
SELECTquery and receives the answer (1 RTT).
In other words, executing even a single first query requires at least 5–6 network round trips (RTT). If 1 RTT between the function (iad1) and the DB (icn1) is 180 ms, then even if the query is an index scan that completes in 1 ms, 1 second (1,000 ms) is lost merely in establishing the connection. On the other hand, placing the function in icn1 reduces 1 RTT to 2–3 ms, and when Supavisor stands by with heavy connections already pre-established to the backend PostgreSQL, this connection establishment overhead is compressed to within tens of milliseconds.
Security adds another layer here. When connecting to a remote database, one must enforce TLS encryption and server certificate verification (rejectUnauthorized: true and specifying the provider root CA certificate) to prevent man-in-the-middle (MITM) attacks. Putting ssl: { rejectUnauthorized: false } into code because a connection fails means agreeing to establish encrypted communication even if an attacker impersonates a fake database server, which is strictly prohibited in production.
Additionally, when using custom session management or server-side authentication, there are times when the identity of the current requester must be passed to PostgreSQL RLS or triggers. As seen earlier, in Supavisor transaction mode (6543), executing a standard SET app.current_user_id = 'u_123' leaves that setting intact on the connection in the connection pool, causing a major security incident where privileges are handed over to an entirely different user who sends the next request (session pollution). Therefore, behind a transaction pooler, one must use SET LOCAL (or set_config('...', '...', true)) within a single BEGIN ... COMMIT block so that the configured value automatically expires the moment the transaction ends.
RLS performance pitfalls and bypass pattern inspection in multi-tenant AI services
RLS is a powerful security mechanism, but if policy condition expressions are written incorrectly, database CPU can spike to 100% and slow down the entire service even when table rows merely exceed 100,000. This is because PostgreSQL executes RLS condition expressions as a security barrier that is forcibly appended to the WHERE clause of every query (Security Barrier).
Let us compare the two most common performance pitfalls and their solutions.
| Pattern | Slow RLS example | Fast RLS optimization solution | Difference in principle |
|---|---|---|---|
| Repeated function calls | USING ( auth.uid() = user_id ) |
USING ( (SELECT auth.uid()) = user_id ) |
Wrapping in a scalar subquery avoids re-calling the function for every row; it evaluates exactly once per query (InitPlan) and then performs an index scan |
| Many-to-many membership join | USING ( team_id IN (SELECT team_id FROM members WHERE members.user_id = auth.uid()) ) with no index |
Create a composite index on members(user_id, team_id) + utilize a SECURITY DEFINER helper function or JWT claims |
If there is no index on the joined column, a full table scan (Seq Scan) occurs every time |
Particular caution is required when using SECURITY DEFINER functions here. The default for PostgreSQL functions is SECURITY INVOKER, which follows the caller's privileges and RLS as they are. In contrast, SECURITY DEFINER executes with the privileges of the user who created the function (usually an administrator), bypassing RLS. If one creates a SECURITY DEFINER function to quickly process complex membership verification, but that function accepts arbitrary arguments, returns table data directly, and leaves execute permission (EXECUTE) open to the public/anon roles, an attacker can completely bypass RLS with a single RPC call and extract the entire dataset. Therefore, when using SECURITY DEFINER functions, one must explicitly specify SET search_path = '' (to prevent schema hijacking), restrict return values to strict booleans (boolean) or minimal identifiers, and REVOKE EXECUTE permissions from unnecessary roles.
At work
Bright Light Edu: Environment variable leak and Supavisor connection exhaustion discovered right before launch
EdTech startup Bright Light Edu developed a web service that proofreads students' essay answers using Next.js (Vercel) and Supabase (Seoul region). Three days before launch, the team conducted a load test by hosting a mock essay competition where 500 students simultaneously submitted answers and received real-time streaming feedback.
Within three minutes of starting the load test, two critical issues were discovered. First, an engineer conducting a security audit searched the page source and JavaScript bundles under _next/static/chunks/ in a browser and found the string NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY along with the actual service_role JWT included in its entirety. When a junior developer encountered an RLS permission error on the student score aggregation screen, the developer had prefixed NEXT_PUBLIC_ to the service_role key to run the aggregation directly from client code. Second, when 150 students pressed the proofread button simultaneously, responses were delayed by 10 seconds each, and more than half of the requests failed with 500 errors (too many clients already, FUNCTION_INVOCATION_TIMEOUT).
The infrastructure lead immediately overhauled the architecture.
- Key revocation and boundary resetting: A
service_rolekey that had been exposed even once in a client bundle was considered compromised. The team immediately issued and deployed freshsb_secret_andsb_publishable_keys and disabled the legacy keys. On the client, they kept onlyNEXT_PUBLIC_SUPABASE_URLandNEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY. Score aggregation was moved to a server-only Route Handler and refactored to be processed using appropriate RLS policies and verified server queries instead ofservice_role. - Function region and execution time adjustments: An inspection revealed that the Vercel function region was set to the default US East (
iad1), communicating across the Pacific Ocean with the Seoul Supabase DB on every request. Specifying"regions": ["icn1"]invercel.jsonmoved the functions to Seoul, and for the proofreading streaming route, they enabled Fluid Compute and explicitly set an upper bound withexport const maxDuration = 60;. This measure prevented stalled requests from accumulating memory charges during the default 300-second limit. - Switch to Supavisor transaction mode: Because
DATABASE_URLpointed to port5432(session mode), concurrently executing functions quickly exhausted available connections. The team changed the runtime connection string to port6543(Supavisor transaction mode) and turned off the driver's Prepared Statement option. They isolated schema migration scripts to use a separateDIRECT_URL(port 5432).
In the 500-user concurrent load test run again the following day, the number of active database connections remained stable at around 15, and the time to display the first proofread sentence on screen (TTFB) dropped from an average of 4.2 seconds to 0.8 seconds.
Clear Stream Bio: RLS WITH CHECK and signed upload URLs preventing leaks of confidential research notes
Clear Stream Bio, which uses AI to analyze new drug candidate literature, operated a B2B SaaS providing independent workspaces for each research laboratory. Each researcher uploaded experimental result PDFs (up to 30 MB) and authored summary notes. In the initial version, two complaints were received.
First, whenever a PDF exceeding 10 MB was uploaded, a 413 Payload Too Large error occurred in the Vercel API route. The architecture had the client send the file first to a Vercel serverless function, which then uploaded it to Supabase Storage, running into the request body size limit of Vercel functions. Second, during an internal penetration test, after logging in with an account from Lab A and executing supabase.from('notes').update({ lab_id: 'lab_B' }).eq('id', myNoteId) in the browser console, researchers discovered that their note was transferred directly into Lab B's list.
The platform team analyzed the causes and made the following fixes:
| Problem area | Flaw in previous design | Improved design |
|---|---|---|
notes table RLS |
Contained only FOR UPDATE USING (lab_id = current_user_lab()) without separate immutability controls for WITH CHECK, or the INSERT policy was open with WITH CHECK (true), allowing injection of another laboratory's lab_id |
Explicitly specified WITH CHECK (lab_id = current_user_lab()) for both INSERT and UPDATE, and blocked altering lab_id after creation using a trigger |
| Large PDF uploads | Browser → Vercel function (4.5 MB limit) → Supabase Storage relay | Server verifies permissions and issues createSignedUploadUrl → Browser uploads directly to private Supabase Storage bucket |
| PDF viewing | Left Storage bucket as Public for convenience and merely concealed URLs |
Switched bucket to Private, and upon viewing, server verifies affiliated laboratory and issues a 60-second expiring signed URL (createSignedUrl) |
Initially, someone suggested, "Let us make the bucket Public so that clients can upload directly to Storage," but this was rejected immediately due to the risk of leaking research data. Thanks to the combination of a private bucket and a server-issued one-time signed upload URL, the team bypassed the request body size limit of serverless functions while completely upholding the security boundary that "only authorized researchers can upload and read files in their own laboratory's path."
Common mistakes
- "
NEXT_PUBLIC_environment variables are encrypted and stored in the Vercel dashboard, so they are safe in the browser as well." Being encrypted in the dashboard is merely the state of storage at rest prior to building. The moment a variable prefixed withNEXT_PUBLIC_is built, it is embedded as a plain-text string directly inside the JavaScript files and delivered down to the browsers of users all over the world. It must never under any circumstances be used for secret values. - "Since the value of a
NEXT_PUBLIC_variable was changed in the dashboard, it is reflected on the site immediately." Unlike server-only variables, variables inlined into the client bundle are permanently fixed at build time. After modifying the value, you must without fail redeploy a new build for the changes to take effect. - "Serverless functions are always faster the more they are deployed simultaneously to all regions around the world, just like a CDN." If a function is architected to query a single-region database (such as Seoul) multiple times, executing the function in a region located far away from the database causes multiple round-trip time (RTT) latencies between the function and the database to surge explosively. As an established rule, functions must be co-located in a region close to the primary database (
icn1). - "Since port 5432 is the standard PostgreSQL port, serverless applications can simply use 5432 as well." In an environment where short-lived instances rapidly multiply and shrink, such as serverless functions, utilizing session mode or a direct connection (5432) rapidly depletes available connection slots. Runtime traffic must use Supavisor transaction mode (6543), and only schema migrations should be isolated to port 5432.
- "As long as a proper
SELECTRLS policy is placed on a table, other users cannot modify or delete data." On tables where RLS is turned on, policies are evaluated individually on a per-command basis. ASELECTpolicy controls only read queries; if you create anINSERTorUPDATEpolicy and leave it loosely wide open, such as withWITH CHECK (true), unauthorized users can insert data under someone else's owner ID or overwrite existing data. - "If a file is given a name with a long UUID that is difficult to guess, placing confidential documents in a Public bucket is safe." The fact that an address is difficult to guess (security by obscurity) does not constitute access control. Because the URLs of public buckets open without authentication, if a URL leaks even once through server logs, browser history, or shared links, there is no way to revoke it. Sensitive files must strictly be handled using private buckets and signed URLs with short expiration periods.
Summary at a glance
| Core topic | Essential design principles to remember |
|---|---|
| Environment separation | Thoroughly isolate databases, storage, and external API keys between Preview and Production environments, and inject production secrets exclusively into Production |
NEXT_PUBLIC_ boundary |
Inlined into client JavaScript bundles as plain-text strings at build time. Strictly prohibited for secret keys and service_role keys, and redeployment is required whenever values are changed |
| Deployment protection and bypass | Lock Preview deployments using mechanisms such as Vercel Authentication, and allow CI E2E tests and webhooks to pass through via the x-vercel-protection-bypass header |
| Function regions and execution | Co-locate functions in the same region as the primary database (for example, Seoul icn1), and configure maxDuration, streaming, and Fluid Compute for long-running LLM invocations |
| Supavisor 6543 vs 5432 | Serverless runtimes use transaction mode (6543, with caution regarding prepared statements), whereas schema migrations and session-level locks use session/direct connections (5432) |
RLS USING vs WITH CHECK |
USING filters existing rows that are to be read, modified, or deleted, while WITH CHECK validates the new row state to be inserted or updated via INSERT or UPDATE |
| Publishable vs secret keys | Publishable keys (legacy anon) operate on the premise of being public, with RLS serving as the security boundary. Secret keys (legacy service_role) bypass RLS (BYPASSRLS) and must therefore be isolated exclusively to minimal server execution paths. Legacy keys will be sunset by the end of 2026 |
| Auth redirect allowlist | Maintain web origins and application deep links (myapp://...) with an exact allowlist in order to prevent open redirects and token theft, and use PKCE |
| Storage access control | Keep sensitive files in private buckets, and issue signed URLs with short expiration periods for viewing and direct large-file uploads |
Check the official docs
- Vercel — Deployments & Environments: Differences between Production, Preview, and Development environments, and principles of environment variable separation across environments.
- Vercel — Environment Variables: Server-only variables and the build-time inlining behavior of framework public prefixes (
NEXT_PUBLIC_). - Vercel — Deployment Protection & Protection Bypass for Automation: Instructions for configuring the
x-vercel-protection-bypassheader and bypass cookies. - Vercel — Configuring Functions & Fluid Compute: Function regions (
icn1),maxDuration, streaming, and the Fluid Compute concurrency model. - Supabase — Connecting to Postgres & Supavisor: Transaction mode (6543) versus session mode (5432), and serverless ORM configuration.
- Supabase — Row Level Security (RLS):
USINGandWITH CHECKsyntax, and performance optimization utilizing(SELECT auth.uid()). - Supabase — Auth Redirect URLs and Storage Access Control: Redirect URL wildcard rules and signed URLs for private storage buckets.
- Vercel — Functions Usage & Pricing: Function pricing categorized into Active CPU, allocated memory, and invocation counts, along with conditions under which memory billing continues even while waiting on I/O.
- Vercel — Sandbox Pricing and Rolling Releases: Sandbox session duration, concurrent sandbox limits, and resource quotas by plan, along with plans offering Rolling Releases.
- Supabase — API Keys: Use cases for
sb_publishable_andsb_secret_keys, as well as the deprecation and sunset schedule for legacyanonandservice_rolekeys. - Supabase — Breaking Change: Tables Not Exposed to Data API Automatically and Breaking Changes: Timeline for terminating automatic Data API exposure for newly created tables,
pg_graphqlschema introspection defaults, end-of-life for Postgres 14, and changes to the default self-hosted image.
Self-check
1-1. When deploying a Next.js application to Vercel, explain how environment variables with the NEXT_PUBLIC_ prefix and those without it are processed differently at build time and runtime, and state the mandatory operation that must be performed to reflect changes in the browser after modifying the value of NEXT_PUBLIC_API_BASE in the dashboard.
1-2. In a web service where the primary database (Supabase Postgres) is located in the Seoul region and the primary users are also located in South Korea, explain from the perspective of network round-trip time (RTT) why latency increases drastically within a single HTTP request when the Vercel serverless function region is configured to the default of US East (iad1).
1-3. Compare the timing of when backend database connections are borrowed and returned between Supavisor's transaction mode (port 6543) and session mode (port 5432), and explain, along with the underlying technical reasons, which mode should be used for serverless application runtime queries and database schema migrations, respectively.
1-4. Distinguish when the USING clause and the WITH CHECK clause are each evaluated in PostgreSQL Row Level Security (RLS), and explain, providing a concrete example, the security vulnerability that can arise when an UPDATE policy has only USING properly specified while the WITH CHECK condition is left loose.
1-5. When Vercel Deployment Protection is enabled on a Preview deployment, state the two HTTP request headers that allow an automated E2E test script running in GitHub Actions to sequentially test multiple pages of the Preview URL without disabling deployment protection.
1-6. Design task: A user's uploaded personal contract PDF (up to 25MB) must be stored securely so that only the user themselves can view it. Describe how to design (1) the public/private visibility setting of the Supabase Storage bucket, (2) the upload flow, and (3) the viewing flow, while avoiding the request body size limit of Vercel functions and maintaining end-to-end security.
Hands-on tasks
Exercise
Creating an environment variable and connection string security audit sheet (40 minutes)
- List 10 environment variables from an AI web service that you currently operate or have hypothetically designed (e.g.,
NEXT_PUBLIC_SITE_URL,NEXT_PUBLIC_SUPABASE_URL,NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,SUPABASE_SECRET_KEY,DATABASE_URL,DIRECT_URL,OPENAI_API_KEY,STRIPE_WEBHOOK_SECRET,VERCEL_AUTOMATION_BYPASS_SECRET,SESSION_SECRET). - Fill in the following five columns in a table for each variable: (a) whether it is included in the client bundle, (b) whether the Preview and Production values must differ, (c) damage scenarios in the event of exposure, (d) correct call location (browser / server Route Handler / migration CLI / CI runner), and (e) whether a rebuild is required when the value is modified.
- Specify the port numbers (6543 vs. 5432) and query parameters (such as
?pgbouncer=true) to be included inDATABASE_URLandDIRECT_URL.
Done when: Among the 10 variables, the 3 variables that are safe to be included in the client bundle and the 7 server-only variables that must never be included are clearly distinguished, and the ports and purposes of the runtime pooler connection and the migration connection are separated.
Exercise
Designing RLS policies for multi-tenant tables and a Storage signed URL flow (50 minutes)
- Write the SQL defining the
projects (id, org_id, owner_id, title, status)table and enable RLS (ENABLE ROW LEVEL SECURITY). - Write four respective policies for
SELECT,INSERT,UPDATE, andDELETEtargeting theauthenticatedrole. At this time, writeauth.uid()in the scalar subquery form of(SELECT auth.uid()), and explicitly specify bothUSINGandWITH CHECKin theUPDATEpolicy to prevent arbitrarily modifying the owner (owner_id) or affiliated organization (org_id) to a different value. - When uploading and reading files in the private Storage bucket
project-files, describe a four-step sequence detailing what the server API verifies, which method (createSignedUploadUrl,createSignedUrl) it calls, and the duration in seconds of the URL it issues.
Done when: The four SQL policies are written with correct syntax, impersonation or spoofing of another user's owner_id/org_id during INSERT and UPDATE is blocked via WITH CHECK, and both uploading to and downloading from the private bucket are controlled via time-limited signed URLs.