Guides

Next.js + Supabase: The Integration Guide, With the Gotchas (2026)

How to connect Next.js to Supabase in 2026: three ways to wire them, the one we would pick, the step list, and what breaks in auth, webhooks, sign-up attribution and cost.

Summarize with AI
Octo Agency cover: Next.js + Supabase, with a purple hexagon pattern

Supabase's API keys page says the company "is deprecating the anon and service_role keys by the end of 2026" (Supabase docs, read 20 November 2026). Any Next.js tutorial that still tells you to set NEXT_PUBLIC_SUPABASE_ANON_KEY is describing the old integration. The current one uses a publishable key, a secret key, the @supabase/ssr package and, on Next.js 16, a file called proxy.ts.

This guide covers what the pairing is for, the three ways to connect the two, the one we would choose, a step list, what breaks and what it costs at scale. Every limit and price comes from Supabase's or Next.js's own documentation and pricing pages, read on 20 November 2026.

What the pairing is for

Next.js renders pages and runs server code. Supabase is a hosted Postgres database with auth, file storage, realtime and an auto-generated Data API on top. Teams pick the pair when they want a signed-in product without running servers: a client portal, an internal tool or a SaaS MVP.

The integration has two jobs. A signed-in user must stay signed in across server-rendered pages, and every query must return only the rows that user is allowed to see.

We covered the wider build in "Next.js and Supabase for a SaaS MVP: Architecture, Auth, Billing and the Parts People Underestimate", which goes deep on Row Level Security speed, Stripe billing and launch costs. This page is narrower: how the two connect, and where the connection fails. If the database is still undecided, see "Supabase vs Firebase for a B2B SaaS MVP".

The three ways to connect them

Three ways to connect Next.js to Supabase
MethodHow it worksWho enforces accessBest forMain risk
Supabase client with cookie auth@supabase/supabase-js and @supabase/ssr call the Data API with a publishable key and the user's session cookiePostgres Row Level SecuritySigned-in products, realtime, file uploadsA table without policies, or a session leaked through a cache
Direct Postgres with an ORMServer code connects through the pooler with Drizzle, Prisma or Postgres.jsYour server codeComplex queries, typed schemas, teams that already use an ORMConnection limits and pooler quirks in serverless
Server-only client with a secret keyRoute Handlers and Server Functions call the Data API with sb_secret_; the browser never talks to SupabaseYour server codeWebhook handlers, admin jobs, back-office scriptsOne missing check exposes every row

Sources: Supabase docs, Creating a Supabase client for SSR, Connect to your database, API keys (read 20 November 2026)

Supabase client with cookie auth. You create a browser client for Client Components and a server client for everything that runs on the server. Both use the publishable key, which Supabase calls "safe to expose online" because Row Level Security limits what it can reach. The docs also warn that "RLS with no policies denies every request", so an empty result on a new table is usually a missing policy.

Direct Postgres with an ORM. Supabase's connection guide points serverless and edge code at the shared pooler in transaction mode on port 6543, and keeps the direct connection on port 5432 for "persistent backends". Its Drizzle guide notes that if you use Drizzle alone you can turn the Data API off. The connection signs in as a database role, not as your end user, so we would treat authorisation as the server code's job on this route.

Server-only client with a secret key. Secret keys map to the service_role Postgres role, which bypasses Row Level Security. Supabase says never to use one in a browser, "even on localhost", and blocks the attempt with a 401. That is a safety net, not a design.

Not a fourth method. The Vercel Marketplace integration creates a Supabase project from the Vercel dashboard, bills it on the Vercel invoice at identical prices and syncs environment variables such as NEXT_PUBLIC_SUPABASE_URL and POSTGRES_URL. It changes who sends the invoice, not how the code connects, and Supabase lists custom domains as unsupported on it.

The route we would use, and why

For a signed-in B2B product we would use the Supabase client with cookie auth for everything a user touches, and a secret key only inside webhook handlers and scheduled jobs. We build applications in Next.js, so we state that bias plainly. This is the setup we would choose from the documentation, not a client case study.

The reason is where the access rule lives. With the first method the database refuses the row even when a page forgets a check. With the other two, every query in every Server Function is one refactor away from a leak. The Next.js Proxy reference makes the same point from the other side: "Always verify authentication and authorization inside each Server Function rather than relying on Proxy alone" (Next.js docs, updated 18 November 2026).

We would add an ORM later, and only for reporting queries the Data API handles badly.

Step list

  1. Start from the template or install by hand. npx create-next-app@latest my-app -e with-supabase sets up cookie-based auth. By hand, install @supabase/supabase-js and @supabase/ssr.
  2. Set two public variables. NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY in .env.local. Keep any secret key in a variable without the NEXT_PUBLIC prefix.
  3. Create two clients in lib/supabase, one for the browser and one for the server. Supabase says to create the client inside the request handler, not at module level.
  4. Add the Proxy. On Next.js 16 the file is proxy.ts; on 15 and earlier it is middleware.ts. It calls getClaims() to refresh the token. Return the response object the cookie handler built, or copy its cookies and cache headers onto yours.
  5. Set a matcher. Without one, the Next.js docs say Proxy runs on every request, including static files and images.
  6. Protect data with getClaims() in every server path that reads user data. Supabase says never to trust getSession() in server code.
  7. Enable Row Level Security and write policies for every table the Data API exposes.
  8. Configure redirect URLs. Change the Site URL from http://localhost:3000 to production and add preview patterns, covered below.
  9. Only then add webhooks, with a shared secret header and an idempotent handler.

What breaks: auth, webhooks and attribution

Common failure points and the documented rule behind each
AreaWhat goes wrongThe documented rule
AuthUsers signed out after an upgrade or downgradeproxy.ts is only called on Next.js 16 and later; earlier versions need middleware.ts
AuthRandom sign-outsRefreshing in two places triggers refresh token reuse detection
AuthA visitor sees another user's sessionCached responses can carry a refreshed token; no ISR on routes where a session can refresh
Keys401 on a key that worked yesterdayNew keys are not JWTs and go in the apikey header, not Authorization: Bearer
WebhooksAn insert never reaches your routepg_net cancels after 2,000 ms by default; the docs describe no retry
WebhooksNo trace of last week's failureResponses are kept for 6 hours, in unlogged tables that do not survive a crash
Auth HooksSign-ups fail under load5 seconds for an HTTP hook including retries; 2 seconds for a Postgres hook
AttributionConfirmation link lands on the wrong domainWith no redirectTo, the Site URL is the default redirect
ConnectionsORM errors in serverless codeShared pooler in transaction mode has no prepared statements

Sources: Supabase docs on SSR clients, the advanced SSR guide, API keys, Database Webhooks, pg_net, Auth Hooks, Redirect URLs and connecting to Postgres (read 20 November 2026)

Auth. Most failures here are cache and file-name problems, not logic problems. Supabase's advanced guide is direct: "Do not enable ISR on any route where authentication is handled or where a session refresh can occur." It also warns that a CDN can serve a cached response carrying someone else's Set-Cookie header.

Database Webhooks. These wrap Postgres triggers and the pg_net extension. They fire after a row is inserted, updated or deleted and post a JSON payload with the new and old record. Because pg_net is asynchronous, a slow Next.js route does not block the write. The cost is delivery you cannot fully audit: responses are stored for 6 hours by default, in unlogged tables. Supabase's pages describe no retry policy, so we would treat a Database Webhook as a hint and reconcile with a scheduled query. And because pg_net is meant for at most 200 requests per second, a bulk import can swamp a webhook that works well in normal use.

Auth Hooks. These are different from Database Webhooks and stricter. HTTP hooks follow the Standard Webhooks specification and are signed. They attempt up to three retries with a two second back-off, only on 429 or 503, and only inside a total budget of 5 seconds. A Next.js Route Handler that starts slowly is a poor home for one; a Postgres hook stays inside the database.

Attribution. By this we mean knowing which campaign produced a sign-up. The landing page has the UTM parameters; the account is confirmed later, often from an email link. Supabase's Redirect URLs page does not say whether query parameters survive that round trip, so we would not depend on it. We would read the parameters on the first visit, keep them in a first-party cookie and send them with the sign-up call in options.data. Supabase stores that in the raw_user_meta_data column of auth.users, and a trigger can copy it into a profiles table. The docs carry one warning about that trigger: "If the trigger fails, it could block signups, so test your code thoroughly."

Redirects need care on previews. For Vercel previews the docs suggest adding a wildcard pattern for your team's vercel.app preview domains to the allow list, using exact paths for production, and replacing {{ .SiteURL }} with {{ .RedirectTo }} in email templates when you pass redirectTo.

Cost at scale

What grows with a Next.js and Supabase app, and what it costs
ItemIncluded on ProWhat scales it
PlanFrom $25 a month; Free allows 2 active projects, paused after 1 week of inactivityTeam starts at $599 a month
Monthly active users100,000$0.00325 per user above that
Compute$10 credit, covers one Micro instanceSmall $15, Medium $60, Large $110 a month; each extra project pays in full
ConnectionsMicro: 60 direct, 200 through the poolerMedium: 120 and 600; Large: 160 and 800
Egress250 GB$0.09 per GB; cached egress $0.03 per GB

Source: Supabase pricing page (read 20 November 2026). Vendor list prices.

A worked example, using our arithmetic on those list prices. An app with 150,000 monthly active users on a Medium instance, sending 400 GB of egress, pays $25 for the plan, $60 for compute less the $10 credit, $162.50 for the 50,000 users above the allowance and $13.50 for 150 GB of extra egress: $251 a month. A staging project on Micro adds $10, because the credit covers only one.

One definition matters in that sum. Supabase counts a monthly active user as anyone who signs in or refreshes a token during the billing cycle, so a returning session counts even without a fresh login. Hosting for the Next.js side is priced separately, and our SaaS MVP post works through those figures.

What this means for a team wiring Next.js to Supabase

Use the publishable and secret keys from day one, because the legacy pair is due to go by the end of 2026. Put user-facing reads and writes through the cookie-auth client with Row Level Security, keep the secret key in server-only handlers, and refresh the session in the Proxy only. Treat Database Webhooks as best effort, capture attribution at sign-up, and budget for users and projects, not servers. Our web apps service page explains how we would scope an integration like this.

Frequently asked questions

How do I connect Next.js to Supabase?

Install @supabase/supabase-js and @supabase/ssr, or start from npx create-next-app -e with-supabase. Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY, create a browser client and a server client, and add a Proxy file that refreshes the session cookie. Then enable Row Level Security on every exposed table. Supabase's Next.js quickstart and SSR guide cover each step.

Do I use the anon key or the publishable key with Next.js?

Use the publishable key. Supabase calls the anon key the legacy version of publishable keys and says it is deprecating anon and service_role by the end of 2026. Legacy keys stay valid until you disable them in the dashboard. The new keys are not JWTs, so they go in the apikey header, not in a bearer token.

Is it proxy.ts or middleware.ts for Supabase auth?

It depends on your Next.js version. Next.js 16 deprecated the middleware file convention and renamed it to Proxy, with a codemod to migrate. Supabase's guide uses proxy.ts on Next.js 16 and later and middleware.ts before that, with the same code inside. Use the wrong name on Next.js 15 and the file is never called, so sessions never refresh and users get signed out.

Do Supabase Database Webhooks retry when my Next.js route fails?

Supabase's Database Webhooks and pg_net pages describe no retry behaviour, so do not count on one. A request is cancelled after 2,000 ms by default, and its response is kept in net._http_response for 6 hours. We would make the handler idempotent and run a scheduled query that picks up any rows the webhook missed. Auth Hooks differ: HTTP hooks retry up to three times on 429 or 503.

How much does Supabase cost for a Next.js app at scale?

Pro starts at $25 a month and includes 100,000 monthly active users and 250 GB of egress, with a $10 compute credit that covers one Micro instance. Beyond that, users cost $0.00325 each and egress $0.09 per GB. On our arithmetic, 150,000 users on a Medium instance with 400 GB of egress comes to $251 a month, according to Supabase's pricing page in November 2026.

Sources

  1. Creating a Supabase client for SSR Supabase Docs, 2026
  2. Advanced guide Supabase Docs, 2026
  3. Use Supabase with Next.js Supabase Docs, 2026
  4. API keys Supabase Docs, 2026
  5. Connect to your database Supabase Docs, 2026
  6. Drizzle Supabase Docs, 2026
  7. Database Webhooks Supabase Docs, 2026
  8. pg_net: Async Networking Supabase Docs, 2026
  9. Auth Hooks Supabase Docs, 2026
  10. Redirect URLs Supabase Docs, 2026
  11. User Management Supabase Docs, 2026
  12. Vercel Marketplace Supabase Docs, 2026
  13. Manage Monthly Active Users usage Supabase Docs, 2026
  14. Pricing and Fees Supabase, 2026
  15. proxy.js Next.js, 2026

Tags

  • Next.js
  • Supabase
  • Integrations
  • Web Apps
Mihajlo Stojanovic

Mihajlo Stojanovic

Co-founder, Octo Agency

Mihajlo runs the technical side of Octo Agency: Webflow builds, custom backends and the systems that keep a site editable after launch. He has shipped more than twenty Webflow sites a year as a white-label partner and writes about what survives contact with a real marketing team.

Veljko Nikolic

Reviewed by

Veljko Nikolic

Founder, Octo Agency

Veljko runs the build side of Octo Agency. He has shipped marketing sites for B2B teams in legal tech, health and manufacturing, and writes about what survives contact with a real review cycle.