Deploying to Cloudflare Workers

Today you'll be building and deploying a Cloudflare Worker that uses Prisma to save every request to a MongoDB database for inspection later.

This guide covers Prisma, TypeScript, MongoDB, Data Proxy, and Cloudflare Workers from the ground up. Let's get started!

Note

We are continuously testing the Data Proxy with Cloudflare Workers. Open an issue if you run into problems or have questions about deploying to Cloudflare Workers.

Prerequisites

1. Get a MongoDB Atlas connection string

After you create a MongoDB Atlas database cluster, you can get its connection string. By default, that connection string does not include a database name.

When you import your project in the Prisma Data Platform at step 8, you must provide a connection string that includes a database name.

However, you do not need to manually create a database in MongoDB Atlas. The project creation workflow in the Prisma Data Platform will create a database with the name you define in the connection string.

  1. Create a free shared cluster in MongoDB Atlas.

  2. On the Security Quickstart screen, complete the initial security configuration.

    1. Add a new database user.
    2. Click Add My Current IP Address so that you can connect to the MongoDB shared cluster from your current system.
    3. Click Finish and Close.
  3. Get the database cluster connection string.

  4. Paste the connection string in a text editor and add the collection name Log.

    The code sample below shows a connection string, that is originally provided by MongoDB Atlas, with the database name now added.

    # The first line is a default-style MongoDB Atlas connection string.
    # The second line includes the inserted `Log` database name.
    mongodb+srv://<user>:<password>@cluster.mongodb.net/?retryWrites=true&w=majority
    mongodb+srv://<user>:<password>@cluster.mongodb.net/Log?retryWrites=true&w=majority

You now have a complete connection string. You will paste the connection string when you create your project in 8. Import your project into the Prisma Data Platform.

For security reasons, do not keep the connection string in the text editor or save it in a text file.

2. Set up your application

Open your terminal and navigate to a location of your choice. Run the following commands to set up your application.

$mkdir prisma-mongodb-cloudflare
$cd prisma-mongodb-cloudflare
$npm init -y
$npm install -D prisma typescript @cloudflare/wrangler webpack

3. Set up Wrangler

Wrangler is the official Cloudflare Worker CLI. You will use it to develop and deploy to Cloudflare Workers.

$npx wrangler init

This will create a wrangler.toml file with some initial configuration.

Next, authenticate the Wrangler CLI with your Cloudflare Workers account. To do this, run the following command in your terminal:

$npx wrangler login
$Allow Wrangler to open a page in your browser? [y/n] y

You can now verify that you're logged in by running npx wrangler whoami.

$npx wrangler whoami

4. Set up TypeScript

The Cloudflare Worker environment natively supports Javascript, Rust, C, and C++. To get TypeScript working on Cloudflare Workers, you need to compile TypeScript to JavaScript before deploying to a Worker.

To set this up, create a tsconfig.json in your project root with the following content:

{
"compilerOptions": {
"outDir": "./dist",
"module": "commonjs",
"target": "esnext",
"lib": ["esnext"],
"alwaysStrict": true,
"strict": true,
"preserveConstEnums": true,
"moduleResolution": "node",
"sourceMap": true,
"esModuleInterop": true,
"types": ["@cloudflare/workers-types"]
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}

And then install @cloudflare/workers-types with npm:

$npm install -D @cloudflare/workers-types ts-loader@8.3.0

You need to pin ts-loader to version @8.3.0 for the Wrangler CLI to work properly.

5. Set up Webpack

Wrangler has built-in webpack support that can be used to compile your code in development and before deploying to Cloudflare.

To configure webpack support, first create a webpack.config.js in the project root with the following code:

const path = require('path')
module.exports = {
entry: './src/index.ts',
output: {
filename: 'worker.js',
path: path.join(__dirname, 'dist'),
},
// Cloudflare Worker environment is similar to a webworker
target: 'webworker',
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
mode: 'development',
// wrangler doesn't like eval which devtools use in development
devtool: 'none',
module: {
rules: [
{
// Compile Typescript code
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
},
}

Next, add the following line to your wrangler.toml file to point Wrangler to use this webpack configuration:

name = "prisma-mongodb-cloudflare"
type = "webpack"
webpack_config = "webpack.config.js"

6. Set up Prisma

Now you're ready to add Prisma to the project.

$npx prisma init

This creates a Prisma schema in prisma/schema.prisma.

Note:

This process also creates an .env file, but this file has no effect when you use Cloudflare Workers.

Inside prisma/schema.prisma, add the following schema:

generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model Log {
id String @id @default(auto()) @map("_id") @db.ObjectId
level Level
message String
meta Json
}
enum Level {
Info
Warn
Error
}

This data model will be used to store incoming requests from your Worker.

7. Create a repository and push to GitHub

To prepare for the steps ahead, let's create a private repository on GitHub.

Create a private repository

Next, initialize your repository, then push your changes up to GitHub.

$git init -b main
$git remote add origin https://github.com/<username>/prisma-mongodb-cloudflare
$git add .
$git commit -m "initial commit"
$git push -u origin main

You're ready to import your project into the Prisma Data Platform.

8. Import your Project into the Prisma Data Platform

With Cloudflare Workers, you can't directly access your database because there is no TCP support. Fortunately, Prisma has your back with the Data Proxy.

  1. To get started, sign up for a free Prisma Data Platform account.

    Note

    A GitHub account is required to sign up for the Prisma Data Platform.

    Signup for Prisma Data Platform

  2. Click New Project and then select Import a Prisma repository.

  3. Fill in the repository and project details, and click Next.

    Import a Project

  4. Next, you connect the Prisma Data Platform to the MongoDB Atlas database and set up the Data Proxy.

    1. Paste the MongoDB Atlas connection string which also includes the database name as described in 1. Get a MongoDB Atlas connection string.

    2. Under Location, select a Data Proxy location that is geographically close to your MongoDB database location.

    3. Enable Static IPs and copy and paste them in the Network Access screen in MongoDB Atlas.

      Connect your Database

    4. Click Create Project to test the connection and set up the Data Proxy.

      If you see, "The database needs to be empty to proceed", you can simply use a different database name. Using the screenshot above, that would be renaming Log to something else.

      If all goes well, you'll be greeted with a new connection string that starts with prisma://.

  5. Copy the prisma:// connection string to your clipboard.

    Data Proxy Page

9. Set the Data Proxy Connection string in your environment

  1. Add the Data Proxy connection string to your local environment .env file.

    .env
    - DATABASE_URL = "mongodb+srv://<user>:<password>@cluster.mongodb.net/Log?retryWrites=true&w=majority"
    + DATABASE_URL = "prisma://aws-us-east-1.prisma-data.com/?api_key=•••••••••••••••••"
  2. In your code editor, add the connection string in the wrangler.toml file.

    wrangler.toml
    1 name = "prisma-mongodb-cloudflare"
    2 type = "webpack"
    3 webpack_config = "webpack.config.js"
    4
    + [vars]
    + DATABASE_URL = "prisma://aws-us-east-1.prisma-data.com/?api_key=•••••••••••••••••"

You are now ready to generate a Prisma Client.

10. Generate a Prisma Client

Next, you'll generate a Prisma Client that connects through the Data Proxy over HTTP.

$npx prisma generate --data-proxy

The generated Client has a smaller bundle size and is optimized for edge environments like Cloudflare Workers.

The smaller bundle size is due to the fact that the interfaces talking to the database (the Prisma engines) are no longer bundled with the Client as this logic is now handled by the Data Proxy.

11. Develop the Cloudflare Worker function

You're now ready to create a Cloudflare Worker. Create a src/index.ts file with the following code:

import { PrismaClient } from '@prisma/client/edge'
const prisma = new PrismaClient()
addEventListener('fetch', (event) => {
event.respondWith(handleEvent(event))
})
async function handleEvent(event: FetchEvent): Promise<Response> {
const { request } = event
// waitUntil method is used for sending logs, after response is sent
event.waitUntil(
prisma.log.create({
data: {
level: 'Info',
message: `${request.method} ${request.url}`,
meta: {
headers: JSON.stringify(request.headers),
},
},
}).then()
)
return new Response(`request method: ${request.method}!`)
}

Run npx wrangler dev to see your worker in development:

👂 Listening on http://127.0.0.1:8787

Go ahead and open http://127.0.0.1:8787. If all goes well, you should see:

request method: GET!

Refresh the page a couple times to verify that it's working. Now if you click on the Data Browser tab on your Prisma Cloud project, you should see Info logs written to your database.

Prisma Data Browser

It's working locally!

12. Publish to Cloudflare Workers

You're now ready to deploy to Cloudflare Workers. Run the following command:

$npx wrangler publish

This will pack your application with webpack and upload to Cloudflare. With a bit of luck, you'll see the following:

✨ Built successfully, built project size is 94 KiB.
✨ Successfully published your script to
https://prisma-mongodb-cloudflare.mattm.workers.dev

Visit your deployment URL and you'll again see:

request method: GET!

You're all set! You've successfully deployed a Cloudflare Worker written in TypeScript that uses Prisma to talk to your MongoDB database.

Give yourself a pat on the back, you deserve it!

Edit this page on GitHub