Skip to content

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.
DatabaseIntegrationLibrary or DriverConnection Method
Postgres-Postgres.js,node-postgresHyperdrive
Postgres-deno-postgresTCP Socket via database driver
MySQL-deno-mysqlTCP Socket via database driver
FaunaYesfaunaAPI through client library
PlanetScaleYes@planetscale/databaseAPI via client library
SupabaseYes@supabase/supabase-jsAPI via client library
PrismaNoprismaAPI via client library
NeonYes@neondatabase/serverlessAPI via client library
HasuraNoAPIGraphQL API via fetch()
Upstash RedisYes@upstash/redisAPI via client library
TiDB CloudNo@tidbcloud/serverlessAPI 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.

Connect to a database from a Worker

There are four ways to connect to a database from a Worker:

  1. With Hyperdrive (recommended), which dramatically speeds up accessing traditional databases. Hyperdrive currently supports PostgreSQL and PostgreSQL-compatible database providers.
  2. Database Integrations: Simplifies authentication by managing credentials on your behalf and includes support for PlanetScale, Neon and Supabase.
  3. 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.
  4. 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.

Authentication

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:

Terminal window
wrangler secret put <SECRET_NAME>

Then, retrieve the secret value in your code using the following code snippet:

const secretValue = env.<SECRET_NAME>;

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.

Next steps