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
Find where your code runs in the following table:
| Where your code runs | Use | Why |
|---|---|---|
|
Browser or mobile app code |
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 or 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 |
Gives you full access to your database, with your own SQL or ORM |
|
|
|
Signs in with your AWS credentials. |
Data API and the client SDK
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.
Call the data API with the publishable key
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:
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. To call as the user from server-rendered pages, see Server-side rendering.
Call the data API with AWS credentials
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.
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: 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
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.
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.
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: 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
Run the following command to print the host, port, user and database for an environment, and the command that creates a token:
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: 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
Run the following command to open psql on the preview environment’s backend branch:
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
Server code connects through @aws-amplifygen3/db-js. aws amplifygen3 local init --type fullstack installs it. Pass its config to your driver or ORM:
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
ORM tools such as drizzle-kit pull and prisma db pull read DATABASE_URL. Set it for a single command:
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
Each aws amplifygen3 db command opens its own PostgreSQL connection to a deployed backend:
| Command | What it does |
|---|---|
|
|
Runs SQL in one session. |
|
|
Opens |
|
|
Prints the connection details and a token |
|
|
Runs |
|
|
Checks your schema, including tables with RLS turned off that |
|
|
Runs one diagnostic, such as |
|
|
Writes every diagnostic as a CSV file to |
For example, run the following command to count the rows in public.notes in production:
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
To connect to the local backend on your computer, see Develop locally.
Connection errors
| Error | What to do |
|---|---|
|
|
Allow your identity |
|
|
Run |
|
|
Run |
|
|
Start Docker or Finch, or add |
|
|
Close connections that your code leaves open. For more information about the connection limit, see Quotas |
|
|
Pass the fields from |