Connect to a PostgreSQL database with Cl·续
// Return the result as JSON return new Response(JSON.stringify(result.rows), { headers: { "Content-Type": "application/json", }, }); }, } satisfies ExportedHandler<Env>;
This code establishes a connection to the PostgreSQL database within your Worker application and queries the `products` table, returning the results as a JSON response.
## 6. Deploy your Worker
Run the following command to deploy your Worker:
```sh
npx wrangler deploy
Your application is now live and accessible at <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev.
After deploying, you can interact with your PostgreSQL products database using your Cloudflare Worker. Whenever a request is made to your Worker's URL, it will fetch data from the products table and return it as a JSON response. You can modify the query as needed to retrieve the desired data from your products database.
7. Insert a new row into the products database
To insert a new row into the products table, create a new API endpoint in your Worker that handles a POST request. When a POST request is received with a JSON payload, the Worker will insert a new row into the products table with the provided data.
Assume the products table has the following columns: id, name, description, and price.
Add the following code snippet inside the fetch event handler in your worker.ts file, before the existing query code:
import { Client } from "pg";
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a new Client instance using the connection string
// or explicit parameters as shown in the previous steps.
// Here, we are using the connection string method.
const sql = new Client({
connectionString: env.DB_URL,
});
// Connect to the PostgreSQL database
await sql.connect();
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/products") {
// Parse the request's JSON payload
const productData = (await request.json()) as {
name: string;
description: string;
price: number;
};
const name = productData.name,
description = productData.description,
price = productData.price;
// Insert the new product into the products table
const insertResult = await sql.query(
`INSERT INTO products(name, description, price) VALUES($1, $2, $3)
RETURNING *`,
[name, description, price],
);
// Return the inserted row as JSON
return new Response(JSON.stringify(insertResult.rows), {
headers: { "Content-Type": "application/json" },
});
}
// Query the products table
const result = await sql.query("SELECT * FROM products");
// Return the result as JSON
return new Response(JSON.stringify(result.rows), {
headers: {
"Content-Type": "application/json",
},
});
},
} satisfies ExportedHandler<Env>;
This code snippet does the following:
- Checks if the request is a
POSTrequest and the URL path is/products. - Parses the JSON payload from the request.
- Constructs an
INSERTSQL query using the provided product data. - Executes the query, inserting the new row into the
productstable. - Returns the inserted row as a JSON response.
Now, when you send a POST request to your Worker's URL with the /products path and a JSON payload, the Worker will insert a new row into the products table with the provided data. When a request to / is made, the Worker will return all products in the database.
After making these changes, deploy the Worker again by running:
npx wrangler deploy
You can now use your Cloudflare Worker to insert new rows into the products table. To test this functionality, send a POST request to your Worker's URL with the /products path, along with a JSON payload containing the new product data:
{
"name": "Sample Product",
"description": "This is a sample product",
"price": 19.99
}
You have successfully created a Cloudflare Worker that connects to a PostgreSQL database and handles fetching data and inserting new rows into a products table.
8. Use Hyperdrive to accelerate queries
Create a Hyperdrive configuration using the connection string for your PostgreSQL database.
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name" --caching-disabled
This command outputs the Hyperdrive configuration id that will be used for your Hyperdrive binding. Set up your binding by specifying the id in the Wrangler file.
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "hyperdrive-example",
"main": "src/index.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-10-27",
"compatibility_flags": [
"nodejs_compat"
],
// Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
}
]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "hyperdrive-example"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-10-27"
compatibility_flags = [ "nodejs_compat" ]
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
Create the types for your Hyperdrive binding using the following command:
npx wrangler types
Replace your existing connection string in your Worker code with the Hyperdrive connection string.
export default {
async fetch(request, env, ctx): Promise<Response> {
const sql = new Client({connectionString: env.HYPERDRIVE.connectionString})
const url = new URL(request.url);
//rest of the routes and database queries
},
} satisfies ExportedHandler<Env>;
9. Redeploy your Worker
Run the following command to deploy your Worker:
npx wrangler deploy
Your Worker application is now live and accessible at <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev, using Hyperdrive. Hyperdrive accelerates database queries by pooling your connections and caching your requests across the globe.
Next steps
To build more with databases and Workers, refer to Tutorials and explore the Databases documentation.
If you have any questions, need assistance, or would like to share your project, join the Cloudflare Developer community on Discord ↗︎ to connect with fellow developers and the Cloudflare team.
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/workers/tutorials/postgres/#page","headline":"Connect to a PostgreSQL database with Cloudflare Workers","description":"This tutorial explains how to connect to a Postgres database with Cloudflare Workers. The Workers application you create in this tutorial will interact with a product database inside of Postgres.","url":"https://developers.cloudflare.com/workers/tutorials/postgres/","inLanguage":"en","image":"https://developers.cloudflare.com/workers/tutorials/postgres/og.png?v=4e5ca028d70d7723","dateModified":"2026-10-12","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["PostgreSQL","TypeScript","SQL"]}
description: This tutorial explains how to send transactional emails from Workers using Postmark. title: Send Emails With Postmark image: https://developers.cloudflare.com/workers/tutorials/send-emails-with-postmark/og.png?v=12a7e914a925f115
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/workers/llms.txt
Use this file to discover all available pages before exploring further.
Docs