Connect to databases
Cloudflare Workers can connect to and query your data in both SQL and NoSQL databases, including:
- Traditional hosted relational databases, including Postgres and MySQL.
- Serverless databases: Supabase, MongoDB Atlas, PlanetScale, FaunaDB, and Prisma.
- Cloudflare's own D1, a serverless SQL-based database.
Database | Integration | Library or Driver | Connection Method |
---|---|---|---|
Postgres | - | Postgres.js ↗,node-postgres ↗ | Hyperdrive |
Postgres | - | deno-postgres ↗ | TCP Socket via database driver |
MySQL | - | deno-mysql ↗ | TCP Socket via database driver |
Fauna ↗ | Yes | fauna ↗ | API through client library |
PlanetScale ↗ | Yes | @planetscale/database ↗ | API via client library |
Supabase ↗ | Yes | @supabase/supabase-js ↗ | API via client library |
Prisma ↗ | No | prisma ↗ | API via client library |
Neon ↗ | Yes | @neondatabase/serverless ↗ | API via client library |
Hasura ↗ | No | API | GraphQL API via fetch() |
Upstash Redis ↗ | Yes | @upstash/redis ↗ | API via client library |
TiDB Cloud ↗ | No | @tidbcloud/serverless ↗ | API via client library |
Once you have installed the necessary packages, use the APIs provided by these packages to connect to your database and perform operations on it. Refer to detailed links for service-specific instructions.
There are four ways to connect to a database from a Worker:
- With Hyperdrive (recommended), which dramatically speeds up accessing traditional databases. Hyperdrive currently supports PostgreSQL and PostgreSQL-compatible database providers.
- Database Integrations: Simplifies authentication by managing credentials on your behalf and includes support for PlanetScale, Neon and Supabase.
- TCP Socket API: A direct TCP connection to a database. TCP is the de-facto standard protocol that many databases, such as PostgreSQL and MySQL, use for client connectivity.
- HTTP- or WebSocket-based serverless drivers: Many hosted databases support a HTTP or WebSocket API to enable either clients to connect from environments that do not support TCP, or as their preferred connection protocol.
If your database requires authentication, use Wrangler secrets to securely store your credentials. To do this, create a secret in your Cloudflare Workers project using the following wrangler secret
command:
Then, retrieve the secret value in your code using the following code snippet:
Use the secret value to authenticate with the external service. For example, if the external service requires an API key or database username and password for authentication, include these in using the relevant service's library or API.
For services that require mTLS authentication, use mTLS certificates to present a client certificate.
- Learn how to connect to an existing PostgreSQL database with Hyperdrive.
- Discover other storage options available for use with Workers.
- Create your first database with Cloudflare D1.