Files
supabase/apps/docs/content/guides/database/prisma.mdx
supabase-vercel-tedd[bot]andalexisintech ac87f00328 docs(functions): explain how a local function reaches the local stack and host services (#54557)
## Problem

When a function runs locally with `supabase start` or `supabase
functions serve`, calls to `localhost` or `127.0.0.1` inside it fail
with "Connection refused". The Edge Functions development environment
page didn't say that the function runs in a Docker container, or how to
reach the local Supabase services and servers on the reader's machine.

Related to
[FDBKIN-6695](https://linear.app/supabase/issue/FDBKIN-6695/document-how-local-edge-functions-can-call-services-on-the-host)
Closes
[DOCS-1853](https://linear.app/supabase/issue/DOCS-1853/explain-how-a-local-edge-function-reaches-the-local-stack-and-services)

## Solution

Adds a "Reach other services from a local function" section to the Edge
Functions development environment page. It explains that `localhost`
inside a local function means the container, points to `SUPABASE_URL`
(and `SUPABASE_DB_URL`) for the local Supabase services, and shows
`host.docker.internal:<port>` for a server on the host, including the
Linux requirement to listen on `0.0.0.0`. Under `supabase start`,
`SUPABASE_DB_URL` uses a `supabase_db_` host that some clients, such as
Postgres.js, can't resolve, so the section says to swap that host for
`db`. A one-line `.env` example keeps the host URL in a local secret, so
deployed code uses a production secret instead. It also drops the claim
under `supabase start` that local development is the exact same
environment as production, which the new section contradicts.

The Postgres tab note on the CLI getting-started page told readers to
reach the database from a function through `host.docker.internal`. It
now says a local function can't reach the database at that URL, and
links to the new section, so both pages give the same advice.

On the Drizzle page, the garbled note in the "Connect" step now says the
`db.ts` sample swaps the `supabase_db_` host for `db` in a local Edge
Function, and links to the new section. The same step now links the
**Connect** panel straight to the **Transaction pooler** URI, since the
panel has no "Shared pooler" option. The `db.ts` comment now says
`prepare: false` disables prepared statements, not prefetch. The page
gets a task title and a description that say what it helps the reader
do. Smaller fixes: the password instruction is plainer, "connection
pooler" is lowercase, a double space is gone, and "Related resources" is
in sentence case.

The Prisma and Postgres.js quickstarts had the same bare title and
"Quickstart" description, so they get task titles and descriptions too,
and the three ORM quickstarts now match. The Postgres.js page uses
"Query" rather than "Connect to", because "Connect to Postgres with
Postgres.js" is over the style guide's 35-character title limit.

## How to verify

1. Open
https://docs-git-tedd-docs-1853-supabase.vercel.app/docs/guides/functions/development-environment#reach-other-services-from-a-local-function,
https://docs-git-tedd-docs-1853-supabase.vercel.app/docs/guides/local-development/cli/getting-started
(the **Postgres** tab under "Access your project's services"),
https://docs-git-tedd-docs-1853-supabase.vercel.app/docs/guides/database/drizzle
(step 3, "Connect"),
https://docs-git-tedd-docs-1853-supabase.vercel.app/docs/guides/database/prisma,
and
https://docs-git-tedd-docs-1853-supabase.vercel.app/docs/guides/database/postgres-js.
2. The section states that a locally served function runs in a Docker
container, so `localhost` and `127.0.0.1` in function code mean the
container.
3. Under "Reach the local Supabase services", the section says to use
`SUPABASE_URL` for the local Supabase services, notes it is
`http://kong:8000` locally, and links to the default secrets table on
the secrets page. It says to swap a `supabase_db_` host in
`SUPABASE_DB_URL` for `db` for clients that can't resolve it.
4. The section says to reach a server on the host through
`host.docker.internal:<port>`, and that on Linux the server must listen
on `0.0.0.0`.
5. The example sets `API_URL` in `supabase/functions/.env`. The local
secrets and production secrets links open the matching sections of the
secrets page.
6. The `supabase start` paragraph no longer claims the local environment
is identical to production.
7. The getting-started Postgres tab note no longer mentions
`host.docker.internal`, and its link opens the "Reach the local Supabase
services" section.
8. On the Drizzle page, step 3 says the `db.ts` sample swaps the
`supabase_db_` host for `db` in a local Edge Function, and links to
"Reach the local Supabase services". The **Connect** panel link opens
the **Direct** tab with **Transaction pooler** selected. The `db.ts`
comment mentions prepared statements, and the last heading reads
"Related resources".
9. The Drizzle page's title reads "Connect to Postgres with Drizzle",
the Prisma page's reads "Connect to Postgres with Prisma", and the
Postgres.js page's reads "Query Postgres with Postgres.js". The sidebar
keeps its existing labels for all three.

## Checks

Ran `pnpm exec oxfmt --check` on the changed files. Typechecked the
snippet with `tsc --strict` (with a `Deno` declaration); it was also run
with `deno check`, `deno lint`, and served with `supabase functions
serve` on Linux, where `localhost` and a `127.0.0.1`-bound host server
were refused and `host.docker.internal` to a `0.0.0.0`-bound server
returned 200. Under `supabase start`, Postgres.js failed to resolve the
`supabase_db_` host in `SUPABASE_DB_URL` and connected with the host set
to `db`, and `localhost:54322` from a function was refused. The Drizzle
`db.ts` host check was run under `supabase start` with a project ID that
contains an underscore: it rewrote the host to `db` and a Drizzle query
succeeded. Checked `SUPABASE_URL=http://kong:8000`, `SUPABASE_DB_URL`,
and the Linux `host.docker.internal:host-gateway` mapping against
`supabase/cli` (`apps/cli/src/shared/functions/serve.ts`,
`apps/cli/src/commands/start/start.handler.ts`,
`apps/cli/src/commands/start/services/edge-runtime.service.ts`). Checked
the **Connect** panel labels and its `connectTab` and `method` query
parameters against `apps/studio/components/interfaces/ConnectSheet`, and
`prepare: false` against the Postgres.js source. The ORM quickstart
titles and descriptions follow the style guide's length limits, and each
description matches its page's steps. The navigation sets its own
labels, and no nav entry, breadcrumb, or test reads the old titles.
ESLint ignores MDX files, and the docs build was not run in the sandbox.

## Follow-ups

- `apps/docs/content/guides/database/drizzle.mdx`: the `db.ts` sample is
written for Node (`import 'dotenv/config'`, `process.env.DATABASE_URL`),
but its `supabase_db_` host check only applies inside a Deno Edge
Function under `supabase start`. A reader in either runtime gets a
sample that half fits.
- `apps/docs/content/guides/database/drizzle.mdx`: the page has no value
statement and no next steps. It opens straight into the gerund heading
"Connecting with Drizzle" and ends after the connection step. Step 1
installs `drizzle-kit`, but no step uses it, so the reader can't create
the `users` table from `schema.ts`.

## Checklist

- [x] I have read the [Contributing
Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] I have checked that the change works in the preview deployment

## Feedback for Tedd

To ask Tedd for a change to this PR, reply in Tedd's session on
[DOCS-1853](https://linear.app/supabase/issue/DOCS-1853/explain-how-a-local-edge-function-reaches-the-local-stack-and-services).
Tedd doesn't read comments on this PR.

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
Co-authored-by: alexisintech <98043211+alexisintech@users.noreply.github.com>
2026-12-03 16:22:21 -07:00

471 lines
16 KiB
Plaintext

---
id: 'prisma'
title: 'Connect to Postgres with Prisma'
description: 'Create a Prisma database user, connect your Prisma app to Supabase Postgres through the connection pooler, run migrations, and query tables with Prisma Client.'
breadcrumb: 'ORM Quickstarts'
hideToc: true
---
This guide shows how to connect your Prisma application to Supabase Postgres. If you encounter any problems, reference the [Prisma troubleshooting docs](/docs/guides/database/prisma/prisma-troubleshooting).
<Admonition type="note">
If you plan to solely use Prisma instead of the Supabase Data API (PostgREST), turn it off in the [API Settings](/dashboard/project/_/settings/api).
</Admonition>
<StepHikeCompact>
<StepHikeCompact.Step step={1}>
<StepHikeCompact.Details title="Create a custom user for Prisma">
- In the [SQL Editor](/dashboard/project/_/sql/new), create a Prisma DB user with full privileges on the public schema.
- This gives you better control over Prisma's access and makes it easier to monitor using Supabase tools like the [Query Performance Dashboard](/dashboard/project/_/advisors/query-performance) and [Logs](/dashboard/project/_/logs).
<Admonition type="note" title="Password manager">
For security, consider using a [password generator](https://bitwarden.com/password-generator/) for the Prisma role.
</Admonition>
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```sql
-- Create custom user
create user "prisma" with password 'custom_password' bypassrls createdb;
-- extend prisma's privileges to postgres (necessary to view changes in Dashboard)
grant "prisma" to "postgres";
-- Grant it necessary permissions over the relevant schemas (public)
grant usage on schema public to prisma;
grant create on schema public to prisma;
grant all on all tables in schema public to prisma;
grant all on all routines in schema public to prisma;
grant all on all sequences in schema public to prisma;
alter default privileges for role postgres in schema public grant all on tables to prisma;
alter default privileges for role postgres in schema public grant all on routines to prisma;
alter default privileges for role postgres in schema public grant all on sequences to prisma;
```
```sql
-- alter prisma password if needed
alter user "prisma" with password 'new_password';
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={2}>
<StepHikeCompact.Details title="Create a Prisma Project">
Create a new Prisma Project on your computer
</StepHikeCompact.Details>
<StepHikeCompact.Code>
Create a new directory
```bash Terminal
mkdir hello-prisma
cd hello-prisma
```
Initiate a new Prisma project
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="npm_initiate"
queryGroup="initiate"
>
<TabPanel id="npm_initiate" label="npm">
```bash
npm init -y
npm install prisma tsx @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg dotenv pg
npx tsc --init
npx prisma init
```
</TabPanel>
<TabPanel id="pnpm_initiate" label="pnpm">
```bash
pnpm init
pnpm install prisma tsx @types/pg --save-dev
pnpm install @prisma/client @prisma/adapter-pg dotenv pg
pnpx tsc --init
pnpx prisma init
```
</TabPanel>
<TabPanel id="yarn_initiate" label="yarn">
```bash
yarn init -y
yarn add prisma tsx @types/pg --save-dev
yarn add @prisma/client @prisma/adapter-pg dotenv pg
yarn tsc --init
yarn prisma init
```
</TabPanel>
<TabPanel id="bun_initiate" label="bun">
```bash
bun init -y
bun install prisma tsx @types/pg --save-dev
bun install @prisma/client @prisma/adapter-pg dotenv pg
bunx tsc --init
bunx prisma init
```
</TabPanel>
</Tabs>
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={3}>
<StepHikeCompact.Details title="Add your connection information to your .env file">
- On your project dashboard, click [Connect](/dashboard/project/_?showConnect=true)
- Find your Session pooler string. It should end with 5432. It will be used in your `.env` file.
<Admonition type="note">
If you're in an [IPv6 environment](https://github.com/orgs/supabase/discussions/27034) or have the IPv4 Add-On, you can use the direct connection string instead of the Session pooler.
</Admonition>
- If you plan on deploying Prisma to a serverless or auto-scaling environment, you'll also need your Transaction [pooler](/docs/guides/database/connecting-to-postgres/pooling-and-limits) string.
- The string is identical to the session mode string but uses port 6543 at the end.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
<Tabs type="underlined" size="small">
<TabPanel id="serverful" label="server-based deployments">
In your .env file, set the DATABASE_URL variable to your connection string
```dotenv .env
# Used for Prisma Migrations and within your application
DATABASE_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@[DB-REGION].pooler.supabase.com:5432/postgres"
```
Change your string's `[DB-USER]` to `prisma` and add the password you created in step 1
```md
postgres://prisma.[PROJECT-REF]...
```
</TabPanel>
<TabPanel id="serverless" label="serverless deployments">
Assign the Transaction pooler connection string (using port 6543) to the DATABASE_URL variable in your .env file. Make sure to append "pgbouncer=true" to the end of the string, which turns off prepared statements.
Next, create a DIRECT_URL variable in your .env file and assign the connection string that ends with port 5432 to it.
```dotenv .env # Used in your application (use transaction mode)
DATABASE_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@aws-0-us-east-1.pooler.supabase.com:6543/postgres?pgbouncer=true"
# Used for Prisma Migrations (use session mode or direct connection)
DIRECT_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@aws-0-us-east-1.pooler.supabase.com:5432/postgres"
```
Change both your strings' `[DB-USER]` to `prisma` and then add the password created in step 1
```md
postgres://prisma.[PROJECT-REF]...
```
</TabPanel>
</Tabs>
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={4}>
<StepHikeCompact.Details title="Configure prisma.config.ts">
Add `import "dotenv/config"` to the generated `prisma.config.ts`. If you are using a serverless environment, change the data source URL to `DIRECT_URL`.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
<Tabs type="underlined" size="small">
<TabPanel id="serverful" label="server-based deployments">
```ts prisma.config.ts
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DATABASE_URL"),
},
});
```
</TabPanel>
<TabPanel id="serverless" label="serverless deployments">
```ts prisma.config.ts
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DIRECT_URL"),
},
});
```
</TabPanel>
</Tabs>
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={5}>
<StepHikeCompact.Details title="Migrate and generate your Prisma client">
If you have already modified your Supabase database, synchronize it with your migration file. Otherwise create new tables for your database, then generate the Prisma client.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
<Tabs type="underlined" size="small">
<TabPanel id="new-projects" label="New Projects">
Create new tables in your prisma.schema file
```ts prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
```
commit your migration
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="npm_migrate"
queryGroup="migrate"
>
<TabPanel id="npm_migrate" label="npm">
```bash
npx prisma migrate dev --name first_prisma_migration
npx prisma generate
```
</TabPanel>
<TabPanel id="pnpm_migrate" label="pnpm">
```bash
pnpx prisma migrate dev --name first_prisma_migration
pnpx prisma generate
```
</TabPanel>
<TabPanel id="yarn_migrate" label="yarn">
```bash
yarn prisma migrate dev --name first_prisma_migration
yarn prisma generate
```
</TabPanel>
<TabPanel id="bun_migrate" label="bun">
```bash
bunx prisma migrate dev --name first_prisma_migration
bunx prisma generate
```
</TabPanel>
</Tabs>
</TabPanel>
<TabPanel id="established-projects" label="Populated Projects">
Synchronize changes from your project:
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="npm_sync"
queryGroup="sync"
>
<TabPanel id="npm_sync" label="npm">
```bash
npx prisma db pull
```
Create a migration file
```bash
mkdir -p prisma/migrations/0_init_supabase
```
Synchronize the migrations
```bash
npx prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script > prisma/migrations/0_init_supabase/migration.sql
```
<Admonition type="note" title="Conflict management">
If there are any conflicts, reference [Prisma's official doc](https://www.prisma.io/docs/orm/prisma-migrate/getting-started#work-around-features-not-supported-by-prisma-schema-language) or the [trouble shooting guide](/docs/guides/database/prisma/prisma-troubleshooting) for more details
</Admonition>
```bash
npx prisma migrate resolve --applied 0_init_supabase
npx prisma generate
```
</TabPanel>
<TabPanel id="pnpm_sync" label="pnpm">
```bash
pnpx prisma db pull
```
Create a migration file
```bash
mkdir -p prisma/migrations/0_init_supabase
```
Synchronize the migrations
```bash
pnpx prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script > prisma/migrations/0_init_supabase/migration.sql
```
<Admonition type="note" title="Conflict management">
If there are any conflicts, reference [Prisma's official doc](https://www.prisma.io/docs/orm/prisma-migrate/getting-started#work-around-features-not-supported-by-prisma-schema-language) or the [trouble shooting guide](/docs/guides/database/prisma/prisma-troubleshooting) for more details
</Admonition>
```bash
pnpx prisma migrate resolve --applied 0_init_supabase
pnpx prisma generate
```
</TabPanel>
<TabPanel id="yarn_sync" label="yarn">
```bash
yarn prisma db pull
```
Create a migration file
```bash
mkdir -p prisma/migrations/0_init_supabase
```
Synchronize the migrations
```bash
yarn prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script > prisma/migrations/0_init_supabase/migration.sql
```
<Admonition type="note" title="Conflict management">
If there are any conflicts, reference [Prisma's official doc](https://www.prisma.io/docs/orm/prisma-migrate/getting-started#work-around-features-not-supported-by-prisma-schema-language) or the [trouble shooting guide](/docs/guides/database/prisma/prisma-troubleshooting) for more details
</Admonition>
```bash
yarn prisma migrate resolve --applied 0_init_supabase
yarn prisma generate
```
</TabPanel>
<TabPanel id="bun_sync" label="bun">
```bash
bunx prisma db pull
```
Create a migration file
```bash
mkdir -p prisma/migrations/0_init_supabase
```
Synchronize the migrations
```bash
bunx prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script > prisma/migrations/0_init_supabase/migration.sql
```
<Admonition type="note" title="Conflict management">
If there are any conflicts, reference [Prisma's official doc](https://www.prisma.io/docs/orm/prisma-migrate/getting-started#work-around-features-not-supported-by-prisma-schema-language) or the [trouble shooting guide](/docs/guides/database/prisma/prisma-troubleshooting) for more details
</Admonition>
```bash
bunx prisma migrate resolve --applied 0_init_supabase
bunx prisma generate
```
</TabPanel>
</Tabs>
</TabPanel>
</Tabs>
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={6}>
<StepHikeCompact.Details title="Test your API">
Create a index.ts file and run it to test your connection
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```ts index.ts
import "dotenv/config";
import { PrismaClient } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
export const prisma = new PrismaClient({ adapter });
async function main() {
const val = await prisma.user.findMany({
take: 10,
});
console.log(val);
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
</StepHikeCompact>