

# Connect to your database

You can connect to your Amplify backend database in two ways:
+  **Data API** – Your app calls the data API over HTTPS with the publishable key, as the signed-in user or as a visitor. The data API reads and changes only the rows allowed by the row-level security (RLS) policies that you configured. Server code can also sign its calls with AWS credentials to get full access to every row.
+  **PostgreSQL connection** – `psql`, GUI clients, server code and ORMs connect over the PostgreSQL protocol and sign in with a token from your AWS credentials.

## Choose a connection method
<a name="backend-database-connect-choose"></a>

Find where your code runs in the following table:


| Where your code runs | Use | Why | 
| --- | --- | --- | 
| Browser or mobile app code |  [Data API with the publishable key](#call-the-data-api-with-the-publishable-key)  | Needs only the publishable key. Returns the rows allowed by the RLS policies that you configured | 
| Server code that calls the data API |  [Data API with the publishable key](#call-the-data-api-with-the-publishable-key) or [Data API with AWS credentials](#call-the-data-api-with-aws-credentials)  | Gets the same rows as the browser when it sends the publishable key. Reads and changes every row when it signs the call with AWS credentials | 
| Server code that runs SQL or uses an ORM |  [PostgreSQL connection from server code](#connect-from-server-code)  | Gives you full access to your database, with your own SQL or ORM | 
|  `psql`, a GUI client, or a terminal or script |  [The `aws amplifygen3 db` CLI commands](#run-sql-with-the-cli)  | Signs in with your AWS credentials. `db connect` opens `psql` or prints the details for a GUI client | 

## Data API and the client SDK
<a name="backend-database-connect-data-api"></a>

The data API serves your tables over HTTPS. Your code calls it with the client SDK, `@aws-amplifygen3/backend-client-js`. Your app can read a table through the data API after you grant access to the table in a migration. For more information, see [Data API overview](backend-data-api.md).

### Call the data API with the publishable key
<a name="call-the-data-api-with-the-publishable-key"></a>

Create the client with the backend URL and the publishable key. The client calls as a visitor until a user signs in, and then sends the user’s token with every call:

```typescript
import { createClient } from '@aws-amplifygen3/backend-client-js'

const backend = createClient(backendUrl, publishableKey) // server code: createClientFromEnv()
const { data, error } = await backend.from('notes').select('id, body')
```

In server code, create the client with `createClientFromEnv()`. It reads the backend URL from `AMPLIFY_BACKEND_URL` and the publishable key from `AMPLIFY_BACKEND_PUBLISHABLE_KEY`. AWS Amplify sets both variables in every deployment.

The call returns an empty list, with no error, when the RLS policies that you configured match no rows. For more information about RLS policies, see [Secure your data](backend-rls.md). To call as the user from server-rendered pages, see [Server-side rendering](backend-auth-server-side.md).

### Call the data API with AWS credentials
<a name="call-the-data-api-with-aws-credentials"></a>

Server code can sign its calls with AWS credentials, using AWS Signature Version 4 (SigV4). A signed call needs no publishable key. It runs as `service_role` and can read and change every row. For more information about the roles, see [API keys and roles](backend-keys.md).

```typescript
import { createClient } from '@aws-amplifygen3/backend-client-js'
import { fromNodeProviderChain } from '@aws-sdk/credential-providers'

const admin = createClient(process.env.AMPLIFY_BACKEND_URL!, {
  awsCredentialsProvider: fromNodeProviderChain(), // no publishable key
})
const { data } = await admin.from('notes').select('id, owner_id') // every row
```

When your code runs outside AWS, such as a script on your computer, set `AWS_REGION` to your app’s AWS Region. A deployed backend URL doesn’t include an AWS Region, so without `AWS_REGION` or `AWS_DEFAULT_REGION`, each SDK call fails with `Cannot determine the SigV4 signing region`.

The SDK in a deployed app signs calls with the IAM role of the environment. The role needs `amplifygen3:Connect`.

**Warning**  
 **Warning:** Sign calls only in server code. Anyone who opens your app can read AWS credentials in browser code, and use them to read and change every row.

## How a PostgreSQL connection signs in
<a name="backend-database-connect-signin"></a>

To connect to a deployed backend, the CLI or the SDK sends AWS Sign-In a request signed with your AWS credentials (SigV4). AWS Sign-In returns a token. Use the token as the database password. You can open new connections with the token for up to an hour. A session that’s already open stays open for up to an hour after it connects.

Your AWS identity needs `signin:CreateOAuth2Token` to get the token, and `amplifygen3:Connect` and `amplifygen3:GetBranch` on the backend branch. For more information about these permissions, see [Permissions for your app](add-IAM-roles.md).

Each connection logs in as `amplify_admin`, the role that owns your tables. RLS doesn’t apply to it, so it can read and change every row. To get the rows that a user gets, sign in as that user and call the data API with the publishable key. Server code that uses a PostgreSQL connection must check which rows each caller may see.

Of the auth tables, `amplify_admin` can read only the `id`, `name`, `email`, `emailVerified` and `createdAt` columns of `auth."user"`. A `select *` on `auth."user"`, or a query on `auth.session` or `auth.account`, fails with `permission denied`. To manage users, use `aws amplifygen3 backend user`. For more information, see [Manage users](backend-users.md).

When your app has no traffic for 5 minutes, the database goes to sleep, along with auth and the data API. The next request wakes them in seconds.

**Warning**  
 **Warning:** SQL that you run through a PostgreSQL connection changes deployed data immediately, and it isn’t saved as a migration. Check `--env` before you write to `production`.

## Get your connection details
<a name="backend-database-connect-details"></a>

Run the following command to print the host, port, user and database for an environment, and the command that creates a token:

```bash
aws amplifygen3 db connect --print --env production
```

 `aws amplifygen3 db token` prints the same details with a token, and a connection URI that has the token as its password. Both commands use the `preview` environment unless you add `--env`.

**Important**  
 **Important:** A token works on every backend branch that your AWS identity can connect to. Treat it like a password: don’t log it or commit it.

## Connect with psql
<a name="backend-database-connect-psql"></a>

Run the following command to open `psql` on the `preview` environment’s backend branch:

```bash
aws amplifygen3 db connect
```

The command uses `psql` from the local backend image while Docker or Finch is running. If neither is running, pass `psql` 16 or later with `--psql`.

To use a GUI client, take the details from `db connect --print`, and use a token as the password. Connect with `sslmode=verify-full sslrootcert=system`. Your client needs libpq 16 or later for these settings. To save the connection as a service that you open with `psql service=notes`, run `aws amplifygen3 db connect --service notes`.

## Connect from server code
<a name="connect-from-server-code"></a>

Server code connects through `@aws-amplifygen3/db-js`. `aws amplifygen3 local init --type fullstack` installs it. Pass its config to your driver or ORM:

```typescript
import pg from 'pg'
import { drizzle } from 'drizzle-orm/node-postgres'
import { PrismaPg } from '@prisma/adapter-pg'
import { createDatabaseConnector } from '@aws-amplifygen3/db-js'

const db = createDatabaseConnector()          // deployed: the deployment's connection; under local run: the local backend
const pool = new pg.Pool(await db.pgConfig()) // postgres.js: db.postgresJsOptions()

const orm = drizzle({ client: pool })             // Kysely and TypeORM also take the pool
const adapter = new PrismaPg(await db.pgConfig()) // Prisma connects through @prisma/adapter-pg
```

The same code runs in a deployment and under `aws amplifygen3 local run`. Don’t put a `DATABASE_URL` in `.env` for your app, because Amplify doesn’t set one in a deployment.

In a deployment, `createDatabaseConnector()` reads `AMPLIFY_BACKEND_BRANCH_ARN`, `AMPLIFY_DATABASE_HOST`, `AMPLIFY_DATABASE_PORT`, and `AMPLIFY_DATABASE_NAME`. Without them, it throws an error. A script that you start outside `local run`, such as a seed or admin script, must pass `backendUrl` with the local backend’s URL. Otherwise it throws too.

### Use ORM tools
<a name="backend-database-connect-orm"></a>

ORM tools such as `drizzle-kit pull` and `prisma db pull` read `DATABASE_URL`. Set it for a single command:

```bash
DATABASE_URL=$(aws amplifygen3 db token --output text --query uri) npx drizzle-kit pull
```

To have an ORM write the SQL for a schema change, run a command such as `drizzle-kit generate`. Then create a migration file with `aws amplifygen3 local migration create`, and put the SQL in it. Don’t let the ORM apply schema with `drizzle-kit push`, `prisma migrate dev`, `prisma db push` or TypeORM `synchronize`, because deployments apply only the SQL files in `migrations/`.

## Run SQL with the CLI
<a name="run-sql-with-the-cli"></a>

Each `aws amplifygen3 db` command opens its own PostgreSQL connection to a deployed backend:


| Command | What it does | 
| --- | --- | 
|  `aws amplifygen3 db query "<sql>"`  | Runs SQL in one session. `--file` reads it from a file | 
|  `aws amplifygen3 db connect`  | Opens `psql`  | 
|  `aws amplifygen3 db token`  | Prints the connection details and a token | 
|  `aws amplifygen3 db dump`  | Runs `pg_dump` on your app’s schemas. Add `--output-file`, `--table`, `--schema`, `--exclude` or `--data-only`  | 
|  `aws amplifygen3 db lint`  | Checks your schema, including tables with RLS turned off that `anon` has access to | 
|  `aws amplifygen3 db inspect <name>`  | Runs one diagnostic, such as `table-stats` or `locks`  | 
|  `aws amplifygen3 db report`  | Writes every diagnostic as a CSV file to `--output-dir`  | 

For example, run the following command to count the rows in `public.notes` in `production`:

```bash
aws amplifygen3 db query "select count(*) from public.notes" --env production
```

To pick a different backend branch, add `--branch-arn` or `--deployment-id`. `db dump` uses `pg_dump` 17 or later, from the local backend image or the one that you pass with `--pg-dump`. Commands that run from the local backend image can’t open files on your computer. To load a file, pipe it in, as in `db query "\copy public.notes from stdin csv" < notes.csv`.

A `db dump --data-only` file also has a `SELECT pg_catalog.setval(…​)` line for each identity column. If you load it into a table that already has rows, it sets the sequence back, and the next inserts fail on duplicate keys. Load it into empty tables, or delete the `setval` lines first.

The data API doesn’t serve a table or function that you create with `db query` until it reloads its schema. To reload it, run `aws amplifygen3 db query "notify pgrst, 'reload schema'" --env <env>`. A migration reloads the schema for you.

## Connect to the local backend
<a name="backend-database-connect-local"></a>

To connect to the local backend on your computer, see [Develop locally](backend-local.md).

## Connection errors
<a name="backend-database-connect-errors"></a>


| Error | What to do | 
| --- | --- | 
|  `IAM authentication failed`  | Allow your identity `amplifygen3:Connect` on the backend branch | 
|  `AWS Sign-In refused the token request` or `sign-in has expired`  | Run `aws login`, or `aws sso login --profile <profile>`, and try again | 
|  `the backend is paused; resume it to connect` or `the branch is paused; resume it to connect`  | Run `aws amplifygen3 backend resume`. For more information about when a backend pauses, see [Capacity](backend-capacity.md)  | 
|  `Docker is not running or not installed.`  | Start Docker or Finch, or add `--psql`  | 
|  `too many connections for database`  | Close connections that your code leaves open. For more information about the connection limit, see [Quotas](quotas-chapter.md)  | 
|  `ENOENT: …​ open 'system'` from node-postgres | Pass the fields from `aws amplifygen3 db token --output json`, with `ssl: true`  | 