Serverless API with Cloudflare Workers (Hono, D1 & Drizzle ORM)
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
đ 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.
đ§ 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.
đ 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
đĄHano
đĄDrizzle ORM
đĄD1
đĄKV
đĄWrangler CLI
đĄJSON
đĄRouting
đĄEnvironment Variables
đĄDatabase Migrations
đĄAPI Deployment
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
Cloud flare has been killing it in the
past year and from a Dev perspective
even though Cloud flare workers have
been around since 2017 the hype has
definitely gained momentum so what
better way than to put it all together
in this video with things that I've been
working with lately like bun Hano and
drizzle RM the goal of the video is just
to deploy a full-fledged API to it which
has access to a database if you're
looking for other ways to deploy a bun
rust API check out the full video I made
on this exact Topic in the description
the one thing that surprised me is the
amount of other products that they offer
like D1 which is a serverless SQL
database and we'll actually use this in
this video message cues KV which is a
low latency key value storage perfect
for caching things and a lot more let me
know if you want me to cover any of
these things in a different video but
for now we'll just focus on cloud FL
workers and D1 they actually have a lot
of different examples on the website
here they have a way to return Json they
even have ways to alter headers cookie
parsing and a lot of different things
that you can do just using Cloud flare
workers if I take a look at the return
Json EX example you'll see here that
this is all you need you can actually
take this piece of code and deploy it to
your Cloud FL worker and whenever it
receives a request it'll just return
some Json with the data which is just
hello world so for this purpose
returning Json is actually very
straightforward where we need help is
things like routing and this is where
Hano comes in since Hano is very
lightweight and fast we can just use it
for our project and to get started I'll
just go to my terminal and do bun create
Hana and then the name of the project so
in this case I'll just call it CFW for
Cloud flare workers bun Hano and drizzle
since this is our full stack now it's
going to ask us what template we want to
use I'll use cloudflare workers next
it's going to ask if we want to install
the project dependencies to which I'll
say yes and for the package manager I'll
use bun all the source code for this
project can be found in my GitHub you
can see that it starts off with just the
empty blank project for you to follow
along but if you go to my branches
there's another branch called routing
and drizzle RM this is actually the
finished product I also updated the read
me if you want to just run through the
commands and get up and running so now
that everything was installed I can just
CD into the folder so I'll do CFW and
then I'll just open this in my terminal
and in my case I'll use vs code so I'll
do code Dot and to quickly run you guys
through the project structure we have
the node modules this comes with pretty
much any standard bun or node project so
I don't need to go over that we have our
get ignore our bun lock file the package
Json we'll go into that in a second the
read me which just has some simple
instructions like M install but these
don't apply to us since we're using bun
RTS config and a
[Music]
wrangler.tj you'll see that for the dev
command and for the deploy command we're
using the Wrangler CLI this is just a
CLI tool used for cloud flare but then
in our source folder we have the
index.ts file and this simply just
starts a basic API for us you'll see
that it's just creating a Hano app and
then from here creating an endpoint
which just returns hello Hano Wrangler
provides a way for us to test this
locally so all we have to do is just
open up our terminal and do bun runev
and you'll see that it started it on
Port 8787 so if we open this up all we
have here is just hello Hano going back
to the project if I cancel out of this
we can actually do Bun Run deploy this
will push it out to Cloud flare and
provide us with a UR all that we can use
to hit our API in my case since I've
already had Wrangler set up it just
pushed it out for me but in your case
you might have to go through the
permission step which is it'll open up
the browser for you and you just have to
accept their uh terms and conditions or
whatever but this was it as you can see
I have the URL here and if I go to it I
am getting hello Hano again and this is
coming directly from my cloud flare
worker if I actually go to my dashboard
on Cloud flare and I go down to workers
you'll see that the project that we just
deployed is right here and if I go into
it it has a lot of different metrics and
logs but if I go to deployments the
deploy that we just did which is a
minute ago and using Wrangler is right
here next going back to our terminal I
want to install the dependencies that
we'll need in this project so I'll start
with the drizzle RM by doing bun install
drizzle RM and also the uh lib SQL
client then I also want to do bun
install DD for development M and the
drizzle kit we'll quickly check this in
the package Json that everything was
installed correctly and we see the
drizzle kit under Dev dependencies and
drizz orm and the lib SQL client under
dependencies so now that that's done we
can actually create our first database
by doing Bon X Wrangler D1 since we're
creating a D1 database create CFW this
is the name I'll just call it the same
as the project- D so I'll do CFW bun
Hano drizzle D1 I'll go through the
process of of creating the database for
us and once that's done you'll see here
that it provides us with the values that
we want to put in our Wrangler dotl so
I'll just copy and paste this inside of
here like that but once we have our
database we can start focusing on the
routes and everything else that we want
to do one of the first things I want to
show you is how to get your n variables
into your routes so we'll do that by
exporting a type so we'll do export Type
n and in here we can start off with a
first value so if I go to variables and
I un comment this if I have my VAR my
variable I save this go back in here so
I'll have my VAR which is just a string
then in order to use this value within
my API and get some type safety working
I have to go to my Hano app and do
bindings and then pass in that type so
I'll do EnV and that should be all I
have to do so now if I go in here and I
do c. EnV you'll see that I have my VAR
here so if I select that actually I
messed up here I'll put it inside of a
template string so I'll do that and now
that shouldn't complain anymore but if I
now do Bun Run Dev and I go back to my
API you'll see that I get my variable
showing up on the UI this is perfect if
you have URLs for other services and
things that you want to use you can just
add another variable in here and it'll
just use it in your application the
problem comes if you want to have
variables that are a bit more private
you don't want to put them in here which
you're going to end up having to commit
to your repo in that case what you want
to do is you want to create a new file
and call itev dovar any variables that
you put in here are exactly the same way
they get imported into your M right here
but these will be hidden so if you take
a look at your get ignored this already
comes in here asev dovar and if I was to
do private and just say this is this is
private putting this in here and just
giving it string private I'll restart my
server and in this case you'll see
private showing up here with the value
of hidden which is exactly what we want
we don't want people seeing this value
going to our URL you'll see that now
this is private we won't be using this
in this video but it's just still good
to know about the one value that we are
going to want in here is our DB value
and we can give this the type of D1
database this is going to be the way
that we access our database by passing
this to drizzle I'll start off with the
drizzle config this is pretty
straightforward so drizzle. config.js
I'll copy and paste the config in here
it's basically just creating the drizzle
folder and putting our migrations in the
migrations folder and then using the
schema from our source DB schema let's
next set up our package Json in here
I'll have two commands we'll have the DB
generate which just generates a new
migration for us in this case since
we're using SQ light we'll use that and
then we also have DB up which just
brings our database up to date next I'll
just create the DB folder in here and
then my schema file in here so I'll call
it schema. TS the schema is pretty
straightforward it's a post table that
has an ID a title content and a Tim
stamp for when this was created if
you're curious about drizzle and seeing
more of its features in action make sure
to check out my drizzle video in the
description but for now this should do
and then we can go back to our index we
don't have this anymore I'll just delete
this and we can start by generating our
migrations so I'll just open up my
terminal and run Bun Run DB generate
you'll see that in our drizzle folder we
now have our new migration which just
creates the table for the posts but yeah
with that out of the way we can actually
start using our database so I'll just
delete this for now and and call this
Con DB and this is where we end up using
drizzle so I'll call it drizzle and we
want to import this from drizzle rmd1 so
I'll do that and then we can just do
c.m. DB with this in place we should be
able to just connect to our database and
use drizzle to queri it so I'll just do
that by doing const result is equal to a
weit and we also have to make sure that
we convert this to async so I'll do O8
db. select and we'll do from Posts we
also want to import that from our schema
and then all this should be returning
all of our posts for us so if I do posts
in here and then do a return c. Json
with the value of the result this should
be getting us all of the posts in our
database so I can just do Bun Run Dev
we'll get a foral for not found since we
don't have the homepage anymore but if I
go to SL posts oh and you'll see that we
have an internal server error and if you
look at it it says that no such table
posts exist and this is because we never
actually applied our migrations to the
local database and to do that we can run
bun X Wrangler D1 execute and then the
name of the database which in our case
is CFW dbn daso D drizzle dd1 and we
want to use the local flag and this is
for the local database and then-- file
and the file that we want to use here is
the migration right here so I'll just
copy and paste this file name and go
back to my terminal and do/ drizzle SL
migrations slash the file name and
running this it looks like it's success
y r on our database and we should be
able to just go back to our development
environment Go to/ posts and then we'll
get an empty array here if you're
looking to connect to your local
database you can just go to Wrangler and
in here we'll have the state D1 and this
file is actually your local SQL light
database and all you have to do is just
at least in my case I'll copy this path
go to my database here my database
connections I'll create a connection and
if I select SQ light you'll see that
it's asking for a path here I'll copy
and paste my path and just just click
connect and that's it I have my table
here with my posts since this is working
we're finally able to deploy this to
production but we have one more step
before we do that so I'll go back to
this command which is running the
migration file and instead of D- local
we have to do dh- remote and what this
does it basically just applies that same
migration to our remote database which
is living on cloudflare but once that
executed we can actually go back to
Cloud flare and under workers we have
the D1 beta and in here our database
should be showing up so if we click into
it we now should be seeing the new table
posts in here with the four columns we
don't have any data so nothing's going
to show up but we do have the ID the
title the content and the timestamp as
the columns but yeah now we're ready to
just run Bun Run deploy the deploy is
pretty fast you'll see that I forgot to
delete my VAR from here but if we go to
our URL now and we get the 404 not found
since we don't have that page anymore
and we' go to SL posts there's no errors
and we just get an empty array I'll add
one more route in here I'll do a post
and this is also going to be SL posts an
async with the context and in here we
want to do the same thing so I'll do con
DB is equal to drizzle and the
cmdb but this time I want to get from
the request payload the title and the
content so by doing that we'll do a c.
request. Json and for the result coming
back from the database we'll do await
db. insert into the post table with the
the values that were passed in so we'll
do title content and we also want to
make sure that we specify here returning
just so we get the values that were
inserted as our result all that's left
now is just to do return c. Json and
then pass in the result with this we
should also be able to now create posts
so I'll just quickly without testing
just run Bun Run deploy never actually
do this in a production environment but
since our application is now deployed
opening up insomnia I can paste in the
URL in here and I'll do a post and for
the Json I'll do title and for the title
I'll just say subscribe and for the
content I'll do to Cod Brew oh and I
actually forgot for the URL you want to
do SL poost and sending this to the back
end we'll get back the post that we just
created and I can even do a get request
now for the posts and we'll get back the
same list of posts you can also validate
this on the cloud flare side so I'll
just refresh this and the new value is
right here let me know if you'd be
interested in seeing this exact same
video but instead of using a D1 database
using something like turo to deploy our
database but yeah it's basically it if
you enjoy this video make sure to drop a
like And subscribe and check out the
other videos
Voir Plus de Vidéos Connexes
Serverless Auth with Lucia Auth V3
How to Build Custom AI Chatbots đ„(No Code)
Build a Perplexity Style RAG App with Langchain in Next.JS and Supabase Realtime
How to host your Webflow/Framer site with CMS for FREE on Cloudflare. No code required
OpenAI Embeddings and Vector Databases Crash Course
Serverless might bankrupt you (and how to deploy to a VPS instead)
5.0 / 5 (0 votes)