Databases
Use Cloudflare Workers to connect your application to external databases, such as Postgres, MySQL, FaunaDB, Supabase, MongoDB Atlas, PlanetScale, Prisma, and more. To use these Cloudflare Workers integrations, you need to install the relevant packages for the databases you want to use. For more information on ways to connect, refer to Connect to databases.
Overview
Database | Native Integration | Library or Driver | Connection Method |
---|---|---|---|
Postgres | - | node-postgres | Workers Socket API |
Postgres | - | deno-postgres | Cloudflare Tunnel |
MySQL | - | deno-mysql | Cloudflare Tunnel |
FaunaDB | No | faunadb | API via client library |
PlanetScale | Yes | @planetscale/database | API via client library |
Supabase | Yes | @supabase/supabase-js | API via client library |
Mongo | No | realm-web | 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() |
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.
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:
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.
Native Database Integrations (beta)
Connect to databases using the new Database Integrations (beta) experience. Enable native Database Integrations in the Cloudflare dashboard. With native Database Integrations, Cloudflare automatically handles the process of creating a connection string and adding it as secrets to your Worker. Today, we have support for connecting to PlanetScale, Supabase and Neon through native integrations.
PlanetScale
PlanetScale is a MySQL-compatible platform that makes databases infinitely scalable, easier and safer to manage.
To set up an integration with PlanetScale, you need to have an existing PlanetScale database to connect to. Create a PlanetScale database or import an existing database to PlanetScale.
From the PlanetScale web console, create a
products
table with the following query:CREATE TABLE products (id int NOT NULL AUTO_INCREMENT PRIMARY KEY,name varchar(255) NOT NULL,image_url varchar(255),category_id INT,KEY category_id_idx (category_id));Insert some data in your newly created table. Run the following command to add a product and category to your table:
INSERT INTO products (name, image_url, category_id)VALUES ('Ballpoint pen', 'https://example.com/500x500', '1');Add the PlanetScale integration to your Worker:
- Log in to the Cloudflare dashboard and select your account.
- In Account Home, select Workers & Pages.
- In Overview, select your Worker.
- Select Settings > Integrations > PlanetScale.
- Follow the setup flow, selecting the database created in step 1.
In your Worker, install the
@planetscale/database
driver to connect to your PlanetScale database and start manipulating data:npm install @planetscale/databaseThe following example shows how to make a query to your PlanetScale database in a Worker. The credentials needed to connect to PlanetScale have been automatically added as secrets to your Worker through the integration.
import { connect } from '@planetscale/database';export default {async fetch(request, env) {const config = {host: env.DATABASE_HOST,username: env.DATABASE_USERNAME,password: env.DATABASE_PASSWORD,fetch: (url, init) => {delete (init)["cache"];return fetch(url, init);}}const conn = connect(config)const data = await conn.execute('SELECT * FROM products;')return new Response(JSON.stringify(data.rows), {status: 200,headers: {'Content-Type': 'application/json'}});},};
To learn more about PlanetScale, refer to Planetscale’s official documentation.
Supabase
Supabase is an open source Firebase alternative and a PostgreSQL database service that offers real-time functionality, database backups, and extensions. With Supabase, developers can quickly set up a PostgreSQL database and build applications.
To set up an integration with Supabase, you to have an existing Supabase database to connect to. Create a Supabase database or have an existing database to connect to Supabase and load data from.
Create a
countries
table with the following query. You can create a table in your Supabase dashboard in two ways:- Use the table editor, which allows you to set up Postgres similar to a spreadsheet.
- Alternatively, use the SQL editor:
CREATE TABLE countries (id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL);Insert some data in your newly created table. Run the following commands to add countries to your table:
INSERT INTO countries (name) VALUES ('United States');INSERT INTO countries (name) VALUES ('Canada');INSERT INTO countries (name) VALUES ('The Netherlands');Add the Supabase database integration to your Worker:
- Log in to the Cloudflare dashboard and select your account.
- In Account Home, select Workers & Pages.
- In Overview, select your Worker.
- Select Settings > Integrations > Supabase.
- Follow the setup flow, selecting the database created in step 1.
In your Worker, install the
@supabase/supabase-js
driver to connect to your database and start manipulating data:npm install @supabase/supabase-jsThe following example shows how to make a query to your Supabase database in a Worker. The credentials needed to connect to Supabase have been automatically added as secrets to your Worker through the integration.
import { createClient } from '@supabase/supabase-js';export default {async fetch(request, env) {const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_KEY);const { data, error } = await supabase.from("countries").select('*');if (error) throw error;return new Response(JSON.stringify(data), {headers: {"Content-Type": "application/json",},});},};
To learn more about Supabase, refer to Supabase’s official documentation.
Neon
Neon is a fully managed serverless PostgreSQL. It separates storage and compute to offer modern developer features, such as serverless, branching, and bottomless storage.
To set up an integration with Neon, you to have an existing Neon database to connect to. Create a Neon database or load data from an existing database to Neon.
Create an
elements
table using the Neon SQL editor. The SQL Editor allows you to query your databases directly from the Neon Console.CREATE TABLE elements (id INTEGER NOT NULL,elementName TEXT NOT NULL,atomicNumber INTEGER NOT NULL,symbol TEXT NOT NULL);Insert some data into your newly created table.
INSERT INTO elements (id, elementName, atomicNumber, symbol)VALUES(1, 'Hydrogen', 1, 'H'),(2, 'Helium', 2, 'He'),(3, 'Lithium', 3, 'Li'),(4, 'Beryllium', 4, 'Be'),(5, 'Boron', 5, 'B'),(6, 'Carbon', 6, 'C'),(7, 'Nitrogen', 7, 'N'),(8, 'Oxygen', 8, 'O'),(9, 'Fluorine', 9, 'F'),(10, 'Neon', 10, 'Ne');Add the Neon database integration to your Worker:
- Log in to the Cloudflare dashboard and select your account.
- In Account Home, select Workers & Pages.
- In Overview, select your Worker.
- Select Settings > Integrations > Neon.
- Follow the setup flow, selecting the database created in step 1.
In your Worker, install the
@neondatabase/serverless
driver to connect to your database and start manipulating data:npm install @neondatabase/serverlessThe following example shows how to make a query to your Neon database in a Worker. The credentials needed to connect to Neon have been automatically added as secrets to your Worker through the integration.
import { Client } from '@neondatabase/serverless';export default {async fetch(request, env, ctx) {const client = new Client(env.DATABASE_URL);await client.connect();const { rows } = await client.query('SELECT * FROM elements');ctx.waitUntil(client.end()); // this doesn’t hold up the responsereturn new Response(JSON.stringify(rows));}}
To learn more about Neon, refer to Neon’s official documentation.
FAQs
What happens to the Database Integration if I rotate my database credentials?
If you rotate or delete database credentials, you must delete the integration and go through the setup flow again.
Can I select multiple databases per database service?
At this time, Database Integrations only support access to one database per provider. To add multiple, you must manually configure secrets.