Serverless API with Cloudflare Workers (Hono, D1 & Drizzle ORM)

CodeBrew
22 Mar 202413:06

Summary

TLDRThis video script outlines a comprehensive guide on deploying a full-fledged API using Cloudflare Workers, Hano, and Drizzle ORM. It demonstrates the process of setting up a serverless SQL database with D1, integrating key-value storage with KV, and utilizing Cloudflare's extensive capabilities for routing and data handling. The tutorial covers local development, database migration, and deploying to production, offering a step-by-step approach to building and scaling cloud-based applications.

Takeaways

  • 🌐 Cloudflare has been gaining popularity in the development community, especially with its Cloudflare Workers which have been around since 2017.
  • πŸ› οΈ The video aims to demonstrate deploying a full-fledged API using Cloudflare Workers, which includes database access.
  • πŸ” The presenter highlights other Cloudflare products like D1, a serverless SQL database, and KV, a low-latency key-value storage for caching.
  • πŸš€ The video provides a walkthrough on deploying a Bun Rust API, showcasing the ease of returning JSON data with Cloudflare Workers.
  • πŸ“š Hano, a lightweight and fast framework, is introduced for routing in the project, alongside Drizzle ORM for database management.
  • πŸ’» The project setup involves using Bun to create a Hano app, with a template specifically for Cloudflare Workers.
  • πŸ”§ Wrangler, Cloudflare's CLI tool, is used for local testing and deploying the API to Cloudflare Workers.
  • πŸ”‘ Environmental variables are integrated into the API for type safety and to avoid exposing sensitive information.
  • πŸ—ƒοΈ A D1 database is created and configured for the project, with steps provided for setting up the schema and migrations.
  • πŸ”„ The video demonstrates applying database migrations locally and remotely, ensuring the database is ready for production use.
  • πŸ“ˆ The final part of the video shows the deployment process and testing the API endpoints to create and retrieve posts from the database.

Q & A

  • What has been gaining momentum in the developer community regarding Cloudflare Workers?

    -The hype around Cloudflare Workers has been gaining momentum, especially with the introduction of various products and the ease of deploying APIs with access to databases.

  • What is the purpose of the video mentioned in the script?

    -The purpose of the video is to demonstrate how to deploy a full-fledged API using Cloudflare Workers that has access to a database.

  • What are some of the additional products offered by Cloudflare mentioned in the script?

    -Some additional products offered by Cloudflare include D1, a serverless SQL database, and KV, a low-latency key-value storage system, which is ideal for caching.

  • What is Hano and how does it relate to the project discussed in the script?

    -Hano is a lightweight and fast framework that is being used in the project for routing in the Cloudflare Workers environment.

  • What is Drizzle RM and how is it used in the video?

    -Drizzle RM is an ORM (Object-Relational Mapping) tool used in the video for interacting with the D1 database in the Cloudflare Workers project.

  • How does the script describe the process of deploying a Cloudflare Worker?

    -The script describes deploying a Cloudflare Worker by using the Wrangler CLI tool, which simplifies the process of pushing the API to Cloudflare and obtaining a URL for access.

  • What is the role of the 'wrangler.toml' file in the project?

    -The 'wrangler.toml' file is used to configure the project settings for the Wrangler CLI, including development and deployment commands.

  • How does the script handle environment variables in the Cloudflare Workers project?

    -The script discusses using '.env' files for public variables and a separate '.env.dov' file for private variables, ensuring that sensitive information is not exposed.

  • What is the significance of the 'bun' package manager in the script?

    -The 'bun' package manager is used throughout the script for installing dependencies, running commands, and managing the project's package.json file.

  • How does the script address database migrations for the Cloudflare Workers project?

    -The script uses Drizzle to manage database migrations, including generating new migrations and applying them to both local and remote databases.

  • What is the final step described in the script for deploying the project to production?

    -The final step described in the script for deploying the project to production is running the 'bun run deploy' command after ensuring that the database migrations have been applied remotely.

Outlines

00:00

πŸš€ Cloudflare Workers and D1 Database Integration

The video script discusses the advancements in Cloudflare's offerings, particularly focusing on Cloudflare Workers and the recent interest in them. The speaker aims to deploy a full-fledged API using Cloudflare Workers that interfaces with a database. The script mentions additional Cloudflare products like D1, a serverless SQL database, and KV, a low-latency key-value store suitable for caching. The speaker introduces Hano, a lightweight and fast framework for routing, and Drizzle ORM for database interactions. The tutorial covers setting up a project with Bun, Hano, and Drizzle, deploying the API to Cloudflare, and utilizing Wrangler CLI for local testing and deployment. The script also provides a GitHub link for the source code and a 'routing and Drizzle' branch for the finished product.

05:01

πŸ”§ Configuring Environment Variables and Database Setup

This paragraph delves into the configuration of environment variables for routing in Cloudflare Workers and the setup of a D1 database. The speaker explains how to import environment variables into routes for type safety and discusses the use of '.env' files for both public and private variables. It covers the process of creating a D1 database using Wrangler CLI and setting up the necessary configurations in the Wrangler file. The script also details the creation of a schema for the database using Drizzle, including a 'posts' table with fields for ID, title, content, and timestamp. The video provides instructions for generating and applying database migrations, as well as troubleshooting steps for common errors like missing tables.

10:01

πŸ›  Finalizing API Deployment and Database Interaction

The final paragraph of the script covers the steps to finalize the deployment of the API and interact with the D1 database. It includes instructions for connecting to a local database using Wrangler and SQL Lite, applying database migrations to both local and remote databases, and deploying the updated API to Cloudflare. The speaker adds a new route to the API for creating posts and demonstrates how to send POST and GET requests to the server using Insomnia, a REST client. The video concludes with a successful demonstration of creating and retrieving posts from the database, validating the functionality on the Cloudflare side. The speaker invites viewers to like, subscribe, and explore other videos, and expresses openness to creating similar content using different databases like Firebase.

Mindmap

Keywords

πŸ’‘Cloudflare Workers

Cloudflare Workers are a serverless execution environment that allows developers to run JavaScript directly at Cloudflare's edge network. In the video, they are used to deploy an API that interacts with a database, demonstrating their ability to handle web requests and responses efficiently.

πŸ’‘Hano

Hano is a lightweight and fast web framework for Deno, which is used in the video to create a routing system for the Cloudflare Workers project. It is chosen for its simplicity and performance, which are crucial for the API's functionality.

πŸ’‘Drizzle ORM

Drizzle ORM is an Object-Relational Mapping library for Deno, which simplifies database interactions by mapping database tables to JavaScript objects. In the video, it is used to manage database operations for the API, making it easier to work with the serverless SQL database D1.

πŸ’‘D1

D1 is a serverless SQL database offered by Cloudflare. It is highlighted in the video as a product that can be used alongside Cloudflare Workers for data storage and retrieval. The video demonstrates how to integrate D1 with an API to manage a posts table.

πŸ’‘KV

KV stands for Key-Value storage, which is a low-latency, highly available data storage system provided by Cloudflare. In the video, it is mentioned as a perfect solution for caching, although it is not directly used in the demonstration.

πŸ’‘Wrangler CLI

The Wrangler CLI is a command-line tool designed for developing and deploying Cloudflare Workers. In the video, it is used to test the API locally and to deploy it to Cloudflare's network, showcasing its utility in the development workflow.

πŸ’‘JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. In the video, JSON is used as the format for returning data from the API, such as the 'hello world' example.

πŸ’‘Routing

Routing in web development refers to the process of determining how an application responds to a client request to a particular endpoint. In the video, Hano is used to set up routing for the API, allowing it to handle different types of requests.

πŸ’‘Environment Variables

Environment variables are a set of dynamic values that can affect the way running processes will behave on a computer. In the video, they are used to store configuration settings and sensitive information like database credentials, ensuring they are not hard-coded into the application.

πŸ’‘Database Migrations

Database migrations are versions of database schema changes. In the video, Drizzle ORM is used to generate and apply migrations to create and update the database schema for the posts table, which is essential for managing data persistence in the API.

πŸ’‘API Deployment

API deployment refers to the process of making an API accessible to users or other services. In the video, the deployment process involves using the Wrangler CLI to push the API to Cloudflare Workers, making it live and accessible over the internet.

Highlights

Cloudflare has made significant advancements in the past year, particularly from a developer's perspective.

Cloudflare Workers have been around since 2017, but their popularity has surged recently.

The video demonstrates deploying a full-fledged API with database access using Cloudflare Workers.

Introduction to other Cloudflare products like D1, a serverless SQL database, and KV, a low-latency key-value storage.

The presenter has been working with technologies like Bun, Hano, and Drizzle RM for their project.

Hano is a lightweight and fast framework used for routing in the project.

Bun is used as the package manager for the project, facilitating dependency management.

Wrangler CLI is used for deploying to Cloudflare Workers and managing databases.

The project structure includes a source folder with an index.ts file for the API.

Local testing of the API is possible using the Wrangler CLI.

The video covers how to set up environment variables for the API with type safety.

Private environment variables can be managed through a separate .env file.

Drizzle ORM is introduced for database interactions in the project.

A schema is defined for the posts table in the database with fields like ID, title, content, and timestamp.

Migrations are generated and applied to both local and remote databases using Drizzle.

The video demonstrates creating, retrieving, and interacting with posts in the database.

The final deployment to Cloudflare Workers is shown, including handling of potential errors.

The presenter suggests the possibility of using other databases like PostgreSQL for deployment.

The video concludes with a call to action for likes, subscriptions, and further exploration of related topics.

Transcripts

play00:00

Cloud flare has been killing it in the

play00:01

past year and from a Dev perspective

play00:03

even though Cloud flare workers have

play00:05

been around since 2017 the hype has

play00:07

definitely gained momentum so what

play00:08

better way than to put it all together

play00:10

in this video with things that I've been

play00:12

working with lately like bun Hano and

play00:14

drizzle RM the goal of the video is just

play00:16

to deploy a full-fledged API to it which

play00:18

has access to a database if you're

play00:20

looking for other ways to deploy a bun

play00:22

rust API check out the full video I made

play00:24

on this exact Topic in the description

play00:26

the one thing that surprised me is the

play00:27

amount of other products that they offer

play00:29

like D1 which is a serverless SQL

play00:31

database and we'll actually use this in

play00:33

this video message cues KV which is a

play00:35

low latency key value storage perfect

play00:37

for caching things and a lot more let me

play00:39

know if you want me to cover any of

play00:41

these things in a different video but

play00:43

for now we'll just focus on cloud FL

play00:45

workers and D1 they actually have a lot

play00:47

of different examples on the website

play00:49

here they have a way to return Json they

play00:51

even have ways to alter headers cookie

play00:54

parsing and a lot of different things

play00:55

that you can do just using Cloud flare

play00:57

workers if I take a look at the return

play00:59

Json EX example you'll see here that

play01:01

this is all you need you can actually

play01:02

take this piece of code and deploy it to

play01:04

your Cloud FL worker and whenever it

play01:06

receives a request it'll just return

play01:07

some Json with the data which is just

play01:10

hello world so for this purpose

play01:12

returning Json is actually very

play01:13

straightforward where we need help is

play01:15

things like routing and this is where

play01:16

Hano comes in since Hano is very

play01:18

lightweight and fast we can just use it

play01:20

for our project and to get started I'll

play01:22

just go to my terminal and do bun create

play01:25

Hana and then the name of the project so

play01:27

in this case I'll just call it CFW for

play01:30

Cloud flare workers bun Hano and drizzle

play01:33

since this is our full stack now it's

play01:34

going to ask us what template we want to

play01:36

use I'll use cloudflare workers next

play01:38

it's going to ask if we want to install

play01:40

the project dependencies to which I'll

play01:41

say yes and for the package manager I'll

play01:44

use bun all the source code for this

play01:45

project can be found in my GitHub you

play01:47

can see that it starts off with just the

play01:49

empty blank project for you to follow

play01:52

along but if you go to my branches

play01:54

there's another branch called routing

play01:56

and drizzle RM this is actually the

play01:58

finished product I also updated the read

play02:00

me if you want to just run through the

play02:01

commands and get up and running so now

play02:03

that everything was installed I can just

play02:04

CD into the folder so I'll do CFW and

play02:08

then I'll just open this in my terminal

play02:09

and in my case I'll use vs code so I'll

play02:12

do code Dot and to quickly run you guys

play02:14

through the project structure we have

play02:16

the node modules this comes with pretty

play02:18

much any standard bun or node project so

play02:20

I don't need to go over that we have our

play02:22

get ignore our bun lock file the package

play02:25

Json we'll go into that in a second the

play02:27

read me which just has some simple

play02:28

instructions like M install but these

play02:30

don't apply to us since we're using bun

play02:32

RTS config and a

play02:49

[Music]

play02:53

wrangler.tj you'll see that for the dev

play02:55

command and for the deploy command we're

play02:57

using the Wrangler CLI this is just a

play03:00

CLI tool used for cloud flare but then

play03:02

in our source folder we have the

play03:04

index.ts file and this simply just

play03:06

starts a basic API for us you'll see

play03:09

that it's just creating a Hano app and

play03:11

then from here creating an endpoint

play03:13

which just returns hello Hano Wrangler

play03:15

provides a way for us to test this

play03:17

locally so all we have to do is just

play03:18

open up our terminal and do bun runev

play03:21

and you'll see that it started it on

play03:23

Port 8787 so if we open this up all we

play03:26

have here is just hello Hano going back

play03:28

to the project if I cancel out of this

play03:30

we can actually do Bun Run deploy this

play03:33

will push it out to Cloud flare and

play03:34

provide us with a UR all that we can use

play03:36

to hit our API in my case since I've

play03:38

already had Wrangler set up it just

play03:40

pushed it out for me but in your case

play03:42

you might have to go through the

play03:43

permission step which is it'll open up

play03:45

the browser for you and you just have to

play03:47

accept their uh terms and conditions or

play03:49

whatever but this was it as you can see

play03:51

I have the URL here and if I go to it I

play03:54

am getting hello Hano again and this is

play03:56

coming directly from my cloud flare

play03:57

worker if I actually go to my dashboard

play03:59

on Cloud flare and I go down to workers

play04:02

you'll see that the project that we just

play04:03

deployed is right here and if I go into

play04:05

it it has a lot of different metrics and

play04:07

logs but if I go to deployments the

play04:10

deploy that we just did which is a

play04:11

minute ago and using Wrangler is right

play04:14

here next going back to our terminal I

play04:16

want to install the dependencies that

play04:17

we'll need in this project so I'll start

play04:19

with the drizzle RM by doing bun install

play04:22

drizzle RM and also the uh lib SQL

play04:25

client then I also want to do bun

play04:27

install DD for development M and the

play04:30

drizzle kit we'll quickly check this in

play04:33

the package Json that everything was

play04:34

installed correctly and we see the

play04:36

drizzle kit under Dev dependencies and

play04:38

drizz orm and the lib SQL client under

play04:41

dependencies so now that that's done we

play04:43

can actually create our first database

play04:45

by doing Bon X Wrangler D1 since we're

play04:48

creating a D1 database create CFW this

play04:51

is the name I'll just call it the same

play04:53

as the project- D so I'll do CFW bun

play04:56

Hano drizzle D1 I'll go through the

play04:59

process of of creating the database for

play05:00

us and once that's done you'll see here

play05:02

that it provides us with the values that

play05:04

we want to put in our Wrangler dotl so

play05:06

I'll just copy and paste this inside of

play05:09

here like that but once we have our

play05:11

database we can start focusing on the

play05:14

routes and everything else that we want

play05:15

to do one of the first things I want to

play05:17

show you is how to get your n variables

play05:19

into your routes so we'll do that by

play05:20

exporting a type so we'll do export Type

play05:23

n and in here we can start off with a

play05:26

first value so if I go to variables and

play05:29

I un comment this if I have my VAR my

play05:32

variable I save this go back in here so

play05:35

I'll have my VAR which is just a string

play05:38

then in order to use this value within

play05:39

my API and get some type safety working

play05:42

I have to go to my Hano app and do

play05:45

bindings and then pass in that type so

play05:48

I'll do EnV and that should be all I

play05:50

have to do so now if I go in here and I

play05:52

do c. EnV you'll see that I have my VAR

play05:56

here so if I select that actually I

play05:58

messed up here I'll put it inside of a

play06:01

template string so I'll do that and now

play06:04

that shouldn't complain anymore but if I

play06:06

now do Bun Run Dev and I go back to my

play06:09

API you'll see that I get my variable

play06:11

showing up on the UI this is perfect if

play06:13

you have URLs for other services and

play06:15

things that you want to use you can just

play06:17

add another variable in here and it'll

play06:19

just use it in your application the

play06:21

problem comes if you want to have

play06:23

variables that are a bit more private

play06:25

you don't want to put them in here which

play06:26

you're going to end up having to commit

play06:28

to your repo in that case what you want

play06:30

to do is you want to create a new file

play06:32

and call itev dovar any variables that

play06:35

you put in here are exactly the same way

play06:37

they get imported into your M right here

play06:39

but these will be hidden so if you take

play06:41

a look at your get ignored this already

play06:43

comes in here asev dovar and if I was to

play06:46

do private and just say this is this is

play06:50

private putting this in here and just

play06:53

giving it string private I'll restart my

play06:56

server and in this case you'll see

play06:57

private showing up here with the value

play06:59

of hidden which is exactly what we want

play07:01

we don't want people seeing this value

play07:03

going to our URL you'll see that now

play07:05

this is private we won't be using this

play07:07

in this video but it's just still good

play07:09

to know about the one value that we are

play07:11

going to want in here is our DB value

play07:13

and we can give this the type of D1

play07:15

database this is going to be the way

play07:17

that we access our database by passing

play07:19

this to drizzle I'll start off with the

play07:20

drizzle config this is pretty

play07:22

straightforward so drizzle. config.js

play07:24

I'll copy and paste the config in here

play07:27

it's basically just creating the drizzle

play07:28

folder and putting our migrations in the

play07:30

migrations folder and then using the

play07:32

schema from our source DB schema let's

play07:35

next set up our package Json in here

play07:37

I'll have two commands we'll have the DB

play07:39

generate which just generates a new

play07:40

migration for us in this case since

play07:42

we're using SQ light we'll use that and

play07:44

then we also have DB up which just

play07:46

brings our database up to date next I'll

play07:48

just create the DB folder in here and

play07:50

then my schema file in here so I'll call

play07:52

it schema. TS the schema is pretty

play07:55

straightforward it's a post table that

play07:56

has an ID a title content and a Tim

play07:58

stamp for when this was created if

play08:00

you're curious about drizzle and seeing

play08:02

more of its features in action make sure

play08:04

to check out my drizzle video in the

play08:05

description but for now this should do

play08:07

and then we can go back to our index we

play08:09

don't have this anymore I'll just delete

play08:12

this and we can start by generating our

play08:14

migrations so I'll just open up my

play08:16

terminal and run Bun Run DB generate

play08:19

you'll see that in our drizzle folder we

play08:21

now have our new migration which just

play08:23

creates the table for the posts but yeah

play08:25

with that out of the way we can actually

play08:26

start using our database so I'll just

play08:28

delete this for now and and call this

play08:30

Con DB and this is where we end up using

play08:32

drizzle so I'll call it drizzle and we

play08:34

want to import this from drizzle rmd1 so

play08:37

I'll do that and then we can just do

play08:40

c.m. DB with this in place we should be

play08:43

able to just connect to our database and

play08:44

use drizzle to queri it so I'll just do

play08:47

that by doing const result is equal to a

play08:50

weit and we also have to make sure that

play08:51

we convert this to async so I'll do O8

play08:54

db. select and we'll do from Posts we

play08:57

also want to import that from our schema

play08:59

and then all this should be returning

play09:01

all of our posts for us so if I do posts

play09:03

in here and then do a return c. Json

play09:07

with the value of the result this should

play09:09

be getting us all of the posts in our

play09:11

database so I can just do Bun Run Dev

play09:14

we'll get a foral for not found since we

play09:16

don't have the homepage anymore but if I

play09:18

go to SL posts oh and you'll see that we

play09:20

have an internal server error and if you

play09:22

look at it it says that no such table

play09:24

posts exist and this is because we never

play09:26

actually applied our migrations to the

play09:27

local database and to do that we can run

play09:30

bun X Wrangler D1 execute and then the

play09:33

name of the database which in our case

play09:34

is CFW dbn daso D drizzle dd1 and we

play09:39

want to use the local flag and this is

play09:41

for the local database and then-- file

play09:44

and the file that we want to use here is

play09:46

the migration right here so I'll just

play09:48

copy and paste this file name and go

play09:50

back to my terminal and do/ drizzle SL

play09:54

migrations slash the file name and

play09:57

running this it looks like it's success

play09:59

y r on our database and we should be

play10:01

able to just go back to our development

play10:03

environment Go to/ posts and then we'll

play10:05

get an empty array here if you're

play10:07

looking to connect to your local

play10:08

database you can just go to Wrangler and

play10:10

in here we'll have the state D1 and this

play10:13

file is actually your local SQL light

play10:15

database and all you have to do is just

play10:17

at least in my case I'll copy this path

play10:19

go to my database here my database

play10:22

connections I'll create a connection and

play10:24

if I select SQ light you'll see that

play10:26

it's asking for a path here I'll copy

play10:27

and paste my path and just just click

play10:29

connect and that's it I have my table

play10:31

here with my posts since this is working

play10:34

we're finally able to deploy this to

play10:35

production but we have one more step

play10:37

before we do that so I'll go back to

play10:39

this command which is running the

play10:41

migration file and instead of D- local

play10:44

we have to do dh- remote and what this

play10:46

does it basically just applies that same

play10:48

migration to our remote database which

play10:50

is living on cloudflare but once that

play10:52

executed we can actually go back to

play10:54

Cloud flare and under workers we have

play10:57

the D1 beta and in here our database

play10:59

should be showing up so if we click into

play11:01

it we now should be seeing the new table

play11:03

posts in here with the four columns we

play11:05

don't have any data so nothing's going

play11:07

to show up but we do have the ID the

play11:09

title the content and the timestamp as

play11:11

the columns but yeah now we're ready to

play11:12

just run Bun Run deploy the deploy is

play11:15

pretty fast you'll see that I forgot to

play11:17

delete my VAR from here but if we go to

play11:19

our URL now and we get the 404 not found

play11:22

since we don't have that page anymore

play11:24

and we' go to SL posts there's no errors

play11:26

and we just get an empty array I'll add

play11:28

one more route in here I'll do a post

play11:30

and this is also going to be SL posts an

play11:33

async with the context and in here we

play11:36

want to do the same thing so I'll do con

play11:38

DB is equal to drizzle and the

play11:40

cmdb but this time I want to get from

play11:43

the request payload the title and the

play11:46

content so by doing that we'll do a c.

play11:50

request. Json and for the result coming

play11:53

back from the database we'll do await

play11:55

db. insert into the post table with the

play11:59

the values that were passed in so we'll

play12:01

do title content and we also want to

play12:03

make sure that we specify here returning

play12:05

just so we get the values that were

play12:06

inserted as our result all that's left

play12:08

now is just to do return c. Json and

play12:11

then pass in the result with this we

play12:12

should also be able to now create posts

play12:14

so I'll just quickly without testing

play12:17

just run Bun Run deploy never actually

play12:19

do this in a production environment but

play12:21

since our application is now deployed

play12:23

opening up insomnia I can paste in the

play12:25

URL in here and I'll do a post and for

play12:27

the Json I'll do title and for the title

play12:30

I'll just say subscribe and for the

play12:32

content I'll do to Cod Brew oh and I

play12:35

actually forgot for the URL you want to

play12:37

do SL poost and sending this to the back

play12:40

end we'll get back the post that we just

play12:42

created and I can even do a get request

play12:44

now for the posts and we'll get back the

play12:47

same list of posts you can also validate

play12:49

this on the cloud flare side so I'll

play12:50

just refresh this and the new value is

play12:52

right here let me know if you'd be

play12:54

interested in seeing this exact same

play12:55

video but instead of using a D1 database

play12:57

using something like turo to deploy our

play12:59

database but yeah it's basically it if

play13:01

you enjoy this video make sure to drop a

play13:03

like And subscribe and check out the

play13:05

other videos

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Cloudflare WorkersAPI DeploymentD1 DatabaseServerless SQLDevOpsHano FrameworkDrizzle ORMWeb DevelopmentDatabase ManagementTech Tutorial