Skip to main content
View on YouTube to comment and like!

Syntax Video

Deploy A Hono API to Render, fly.io, Vercel and Cloudflare Workers

Chapter 1 00:00

Transcript

hono is a web application framework that allows us to build apis and in a recent video here on the channel I did a deep dive into how to set this up to get a nice fully documented API and in this video I'm going to show you how to deploy it so one of the great things about hono is they actually support a lot of different runtimes and platforms and in this video I'm going to show you how to deploy to a few different platforms that are node.js based or have a node.js compatibility layer so I'll show you how to deploy to both the edge runtime and the node.js runtime and of course Cloud flare workers now in this video I am going to be using the hono open API starter repo that I created as a base to deploy to all of these platforms but if you have your own hono applications that you'd like to deploy to these places you'll be able to follow along as well now all of these examples are available over on GitHub I have this repo hono node deployment examples and so for any one of the deployments that you'd like to deploy to head into that folder you can see all the files that I configured and

specifically if you want to use the cloudflare template I actually just have that as another branch on the main starter repo so if you look on here check the branches there is a branch called Cloud flare so if you just want to start from that cloud flare base template you can actually just clone that specific Branch so let's dive in my name is CJ welcome to syntax now first up we need to make sure that we can actually run our hono application directly with node.js so so far we've only been using this in development and you can see we're using this TSX command so TSX stands for typescript execute and essentially what it does is it transpiles your code just in time and then runs it through nodejs but when we're running in production we want to run the fully built code we don't want to use something like TSX uh so what we can first do is build our code and see what happens and so right now you can see we have a build command of TSC so this uses the typescript compiler and it looks at our TS config uses all of these settings and then it's going to Output the code into dist so

Chapter 2 1:21

typescript build output

the code that gets generated and built here is the code that we're going to want to run with nodejs so let's see what happens if we build it first of all you can see we have a disc directory and you can see that git is tracking it we want to make sure we don't commit this built code because any system we deploy it to is going to run the build itself so if we head over to our G ignore make sure that we throw disc inside of there and that way git is not tracking the changes for that disc directory aside from that if we look in here we have actual JavaScript files right so you can see there's our entry point there's our app.js uh and so we should be able to run this with nodejs so let's give it a try if we do node and then disc Source index JS we hit our first issue so you can see it says cannot find module app imported from index.js so if we look in the source code we look in the built code we look at index.js we can see that it's trying to import app here but this import actually needs an import extension it needs ajs on there because that is the ecmascript module standard and so since we're running the latest version of node.js we have our type set

Chapter 3 2:33

import extensions / aliases issue

to module it expects to see file extensions so what we need to do is whenever we build our project with typescript we need to make sure that those extensions get added and for this we can use a project called TSC Alias now one of the main purposes of TSC Alias is to actually replace all of our import aliases so that's actually another issue so right now we don't have file extensions but if we look at one of our other built files like in source and let's just say app.js you can see that we have these import aliases here this type of import Alias is only supported by typescript so this also needs to be converted into like a relative file path so that's one thing that TSC Alias can do but on top of that it can also add the extensions to all of the Imports for us so what we're going to do is install TSC Alias as a Dev dependency so if I do mpmi DD TSD Alias we'll grab that and then in our package.json we need to update our build script so right here we'll run typescript and then immediately after that we'll run TSC Alias and this will essentially go through all of the built and bundled code and convert all of those import

Chapter 4 3:35

tsc-alias setup

aliases and we can add a setting to add file extensions so let's do that now if you head to your TS config.js you can actually add a section here specifically for TSC Alias so we're going to add TSC Dalias here and then we can specify all of our options if you look in their docs they have a lot of options but the one that we care about is resolve full paths and we're going to set this to true and this is what's going to add those import extensions so we'll set that to true and now let's run a build now before we run it let's go ahead and add a script to our package.json so most platforms that support node.js expect there to be a start script and that start script says how to run the app and we can basically just use node so we can say node go to the disc directory into the source directory grab that index.js and so now any platform that expects that to exist will be able to run it and a lot of platforms will actually run our build for us so they're going to run build and then whenever they need to start it they can point at that built code and so now if we do mpm start it'll see that command and our app actually starts up and so now we have built our code in a

Chapter 5 4:22

add start script to package.json

way that is compatible with the latest version of nodejs and if we take a look in that disc directory we can see see that any Imports added the import extension there and then anything that had a import Alias now uses that relative file pad so our code is built and it's now in a format that the latest version node.js can actually run now if you decide to use the template that I have on GitHub I went ahead and added those build settings so you won't have to add that manually they're in the repo already they're ready to go you've got this build script and you've also got the start script so if you start from the template directly you should be ready to start deploying now before we deploy we need to make sure that we have a database in the cloud that are can connect to and we are using sqlite as our database but there are various platforms out there that allow you to use sqlite in production in a scaled way and so turo is one of those projects so essentially what we can do is add our database here and it's actually going to give us a remote URL that we can connect to and that lib SQL database client that we set up in the last tutorial is ready to go to actually connect to that remote sqlite instance so here in turo I'm going to create a group I'm just going

Chapter 6 5:12

template with build settings

Chapter 7 5:25

create turso db

to call this my tasks group I'll put it in Denver because that's where I am and then we'll create the group now from here I can create a database so I'll do just that I'll give it a name we're going to call this the tasks DB and we'll create now I can create a secret and connection URL so if I click here and then click create token you can choose if you want it to expire in this case I don't because it's going to be for our Long Live deployments and then you can give it access in this case we want read write access because it needs to be able to read and write to the database and then click create token now this token should be kept secret this is essentially like a password to write to your database if anybody has this token they can literally connect a direct ly to your database create tables delete things you want to protect this secret but essentially what we're going to do is use this URL and token to push our schema to the remote database and make sure that when we're running our app locally we can actually connect to that remote instance because if we can then we know that whenever we create our deployments they'll be able to connect to the instance as well so locally I'm going to update my EnV to use these as the database URL and database off token

Chapter 8 6:53

add database env variables

so I'll grab this URL and then instead of a local file now we're pointing at something in the cloud and then if you look at our EnV file we also are expecting another variable called database off token and this is how we will authenticate to that database so here I can grab this token throw it in there make sure to delete it after I publish this video and uh now we should be able to connect to that remote instance and so if we just start up our app locally I'll just do mpm run Dev let's try connecting to it and see what happens so if I for instance try to hit that tasks inpoint boom we get a SQL error that says no table exists task so first of all this is good this actually lets us know that we're connecting to that remote instance but that remote instance needs the schema so we need to push it since my EnV has the connection information for that remote database when I run drizzle kit push it's going to push the schema to that remote database so if I do pnpm drizzle kit push that is going to attempt to push our schema now uh one thing I forgot to set up is in our connection settings we

Chapter 9 7:49

drizzle-kit config / turso update

do need to tell it that it's using the turo driver now I will mention there's a newer version of drizzle that uses a slightly different conf big uh for this project we are still on drizzle version 0.33 and so for version 0.33 you can also add a driver setting here that is set to turo now if you look at the latest drizzle docks they actually have a dialect called terso that you would use instead but since we're on version.

33 these are the settings that we need and I will be creating a video pretty soon that talks about the latest changes in drizzle uh but they're pretty great but right now we're just going to stay on the older version so set the driver to turo and now let's try to push our schema there we go so that actually pushed the schema to the cloud to the uh sqlite database running there on turo and so now if we start it up and then try to visit the tasks inpo we get back an empty array sweet and let's actually head to our API docs and create a new task so let's just call this learn hono deployment and it is currently not done so if I send that that puts it in the database and this is in the cloud and so this is one way we'll test our connection to the database once we deploy we'll make sure that we can see this one task because that means we're we're connecting to that remote turo instance and so at this point we have a turo DB we're ready to go anywhere we deploy to we can use that off URL and off token and connect to that remote database instance now the first place we'll try to deploy this is

Chapter 10 8:26

push schema to turso db

Chapter 11 9:09

deploy to render.com

and then choose all of our settings so we are using nodejs we're on the main branch you can choose your region based on where you are in the world and then all of the other settings we can leave exactly the same so because we set up our start script our build script everything is ready to go for render so you can see here the build command is going to install dependencies and then run the build so that's going to generate that disc directory and then to actually start the app it's going to do pnpm Run start which runs that start script that we created so we shouldn't have to change anything here we'll just choose the free tier and then we can add all of our environment variables now one nicity is you can click add from EnV and then if you head to your project you can grab your settings and then just copy them directly in but we do want our node EnV to be production render is set up to use the port environment variable so we can set this to whatever we want and if we leave it blank they're going to generate a port for us we're going to set the log level to info and then lastly we'll update our database URL and off token and of course these are coming from turo so let's add those variables and deploy now we actually got a build error now I'm seeing that it says Dev

dependencies are skipped because no DMV is set to production um even though it's running the build so let's go ahead and just update that to make sure that we get our Dev dependencies because without the dev dependencies we don't have the type package so in our environment let's actually just set node EnV to development for now deploy and then after the deployment set it to production I'm curious if they have specifically build environment variables because our build environment variables need to be different than when we're actually running but let's let's see if this helps yeah so it looks like it's able to build with that no DMV I'll have to research to see how we can get the build working without that or maybe have different environment variables for build but for now we should be good and sweet so it looks like it's started up let's try visiting it we can hit the homepage awesome and if we go to the slash tasks endpoint we get back a task and so it's connecting to that remote turo instance sweet so we deployed on

Chapter 12 11:24

deploy to fly.io

is going to create some various files in our directory so I'm actually going to clone this repo down and put it into a new directory so that way it's not going to be on on the main branch and I'll have a separate repo that has a folder for each of these different deployments that has all of the the files that got created specifically for those deployments so here I'm just going to clone this into uh fly IO example and then if I head in there let's just install dependencies and then copy our env. example file to to our EnV I just want to make sure we can run this thing locally before we deploy it uh and so from there if I do mpm run Dev looks good I can hit it locally I can do that yeah there's no local table this should be fine this should be fine because we're going to be connecting to the remote instance anyways okay so first off you will need to install the fly CTL CLI tool so if you head to this page install it for your operating system from there from the command line You'll either sign up or you can sign up on the web and then from the command line do fly off login once you're logged in you

are ready to deploy so from this directory I'm going to run fly launch it'll detect what kind of app it is and then we can change our settings and so in this case I just want to change the name so I'm going to say yes here that'll launch the browser and then we can update any of the settings that we'd like and so in this case I'm just going to call this the pho open API starter fly iio so I'll call it that from here you can customize everything else and you can add the Sentry in integration so I'm going to go ahead and do that and then click confirm settings sweet and with those settings it's going to start to launch and this is a perfect time to talk about Century so if you head to sentry.io syntax you can get a code for trying sentury for free using Code tasty treat and so centry is an error monitoring platform essentially you add it to your app running in production and then any errors that happen it logs them in the dashboard and you can get some insight into the types of errors that your users are running into and so since we're deploying we absolutely should have cry enabled for our deployments so if you want to try it for free head over to sentry.io syntax awesome and so what

this has done is it has actually created a docker container for us it's building it it set up all of the settings and if we look in our source codes we can see that it added that Docker file it added some configurations files looks like it also added some dependencies for us but specifically when you're deploying to fly you're going to get all of these files created within your repo so at this point it says it's deployed but we do need to go set up environment variables so if we head to the fly dashboard refresh we should see our app now and then we can go specify our environment variables so if we head to Secrets then we can add each of the secrets that we need and so we're going to need to add all of them I'm going to add my node EnV set that to production I'll add my log level set that to info I'll add port and they set that to 3,000 and then I'll add my database URL and lastly We'll add our database off token we'll set that and now here in your secrets if you see a yellow dot then that means these aren't going to take

effect until you actually deploy so from here we can now just say fly deploy it'll pick up all those latest environment variables and we should have a deployed app sweet so we should be able to give it a try if we head here the index page loads that's awesome and can we head to/ tasks we can sweet so we deployed to fly.io next up we're going to deploy our app to versel now versel has two different runtimes it has the node.js runtime and it has the edge runtime which is a lightweight JavaScript runtime based on web standards now it's possible to run on both of these but they both will require something slightly different so first we'll deploy to to the edge runtime now I'll start with the hono API starter base template let's just grab this URL and then I'm going to clone this into the vercel edge example we'll head in there and then I'll set this up install dependencies create my EnV file push my database schema just make sure that I can run it locally because we're going to want to test that before we deploy it okay so I tested locally everything looks good now let's set up the deployment so if you look in the hono docs they have a section for versel this

Chapter 13 14:41

deploy to vercel edge runtime

document specifically talks about deploying it with nextjs but we can still use it as an example and so you can see right here that this exports get and post and so essentially we need to create an entry point that does this same thing it exports all of the HTTP methods that we support and it's going to use handle from hono verel now we don't have to install anything separate for this uh this is just built into the base hono dependency so we should be good to go there and if you click this link you can see all of the supported methods and so essentially what I want to do is I want to make sure that my API supports all of the supported methods so we're going to create an entry point that exports all of these specific methods now the way that cell works is it expects your server list functions to live in a folder called API so I'm going to create a folder at the root here and call it API inside of there I'll create my function and that's just going to go in an index.ts now if you watched the original tutorial you saw that I talked about how app. TS is just a regular plain old hono app but if you look at index.ts that Imports the app and then runs it with this node server package

and so we kind of need to do a similar thing but for versell and so over here in our API index.ts file is is where we're actually going to write that handle code so we will pull in handle from hover sell we'll make sure to export const runtime as Edge and so this makes sure that we're deploying to the edge runtime not the node.js runtime and then from here we need to import our app and then export all of our handle functions now the code that we have written with typescript is not directly supported on the edge run time so if we were to try to import this app directly it can't resolve these import aliases there's some other various issues so basically what we need to do is whenever we are running our app on verell this file needs to actually import our built code so let's run the build command that'll generate the disc folder and then we're actually going to import that app from the disc folder so now that we've run the build we should have a disc and then there we have Source then the app.js this is the file that we want to import into our server list function

here so I'm going to say import app from we'll go up a directory into the disc directory into the source directory and then grab that app. JS file now I have some linter errors because typically you shouldn't import things from the disc folder but when our code is running on verell it will have built our code so that disc folder will exist so I'm going to go ahead and ignore no import from disc the other thing is this is bundled JavaScript code that doesn't have any type declarations so typescript complains and it's like hey I don't have the the Declaration file here and so I'm actually just going to do a TS expect error so that way it doesn't complain about the missing declarations and then I have to es lint ignore using TS expect error and they have to to be in this order but ultimately I'm just trying to make sure that my linter is happy and also that the typescript compiler is happy but now that I have our built app we can pass it into handle and so you can see in their docs they are exporting get and post like this and so I want to do the same thing but I want to make sure I include all of the methods cuz our API also has in points force uh

Delete requests and Patch requests we might even get options requests if we ever enable cores so I need to make sure that I support all of these as well so I'm just going to export all of these and I'm I'm going to use some command line food to say this and then this and then this and then this um like that I'll make sure I update this one too okay so at this point we have an entry point that will run our hono application and handle all the possible incoming requests and essentially what we're doing is we're taking all of our code and turning it into a single serverless function so whenever a request comes into our app running on verel it's going to hit this file first which in turn loads our entire hono app and then it can respond to any of the incoming requests but essentially what we want to do is we want to reroute all incoming requests to that specific serverless function living there so for this we can add a versel Json file so I'm going to add a versel Json and inside of here we need to have

a rewrites section and the source of the rewrites is coming from anywhere so this is a regular expression that says slash anything and then we want to send that to our API function so any request that that comes into our application we are then going to send it to the destination of/ API so if someone requests SL tasks it's going to hit this regular expression that'll then redirect it to/ API that will then go into this folder see this and then run it against our hono app here now one more thing we should do is add a folder called public so we're doing a thing that they didn't really expect us to do on verell in terms of only deploying a serverless function not having any static files or anything like that and so what we need to do is create a public folder and then just make sure that this folder exists whenever we deploy so I'm going to add a file in here called get keep this is just a convention to make sure that this folder lives in our git repo but it's also going to stick around for whenever we deploy our application but now we are ready to try deploying so I'm

going to use the versel CLI you potentially could push this to a repo and then hook it up I haven't tried that yet but I am going to show you how to do this from the CI so here I'm just going to run versel and set this up so yes I want you to set up and deploy this we'll deploy it there this is not an existing project I'm going to call this the hono starter orell Edge the code lives in this directory and then you'll see that it's detecting these settings and so essentially what will happen is when we run our deploy it's going to run npm run build and we already set up that build command earlier it'll do a pnpm install and in this case it'll just have that blank public directory um but because it built it that serverless function can actually require in that app that lives in the dis folder and we should be good to go so I'm not going to modify these settings this should be everything that we need after this all we should have to do is add our environment variables awesome so if we head to the verse cell dashboard we should have a project and now we can go in and add our environment variables so if I head to settings and then environment variables scroll down and this is where we need to add them here and what's nice is if you have them

on your clipboard from a EnV file you can just paste it in it'll detect all of them and then we'll click save here and then now that I have these environment variables we want to run a redeploy so I'm going to go over to my deployments and then just say redeploy and if if we did everything right we should be good to go so if we visit our app it loads up sweet and if we head to/ tasks it's able to hit the API awesome now when you're using versell you typically want to be able to test this locally too because sometimes you might do some versel specific things like caching and stuff like that so in order to test things in a versel like way without having to deploy it every time we can run versel locally so in this directory I'm going to install versel as a Dev dependency and now we can add a specific task and so in my package.json on I'm going to add another script and I'm going to call this versel Dev and so here I can say versel Dev and essentially what this will do is when it runs locally it'll behave exactly like it would running on versel so it's going to see that versel do Json it'll see that API directory and

everything will run in a similar way and so now that I have that I'll need to make sure that my disc directory exists so one thing you might do is you could combine this and say well run the build and then do versel Dev just to make sure that disc directory exists but let's try it out so if I do mpm run versel Dev that'll build it and then spin up the versel CLI now maybe someone in the comments can help me out I don't know why but for whatever reason this requires me to use yarn maybe there's another setting I can specify but if you get an error that says yarn command not found you'll need to install yarn globally and then you'll be able to start it up but from here we should be able to visit our app and visit all of the endpoints but in this case it's running in a way as if it would if it were running on versel so this is a good way to test things out without needing to fully deploy to versel next up I'll show you how to deploy to versell but using the nodejs runtime and so this is different from the edge runtime because it's not as lightweight and you'll typically need this if you're doing anything that's really node specific and maybe aren't using web standards but hono has a built-in adapter for nodejs

Chapter 14 22:58

deploy to vercel node.js runtime

so we'll be able to use that and we'll set up our app in a similar way that we did for the edge functions so for this example all of the setup steps are exactly the same as for the edge runtime the only difference is going to be our entry point for running the application so if you want to to the node.js runtime go back in the tutorial follow what I did there essentially what I'm going to do is I'm just going to copy the folder that we created and show you what needs to change if we want to run on the node.js runtime versus The Edge runtime okay so I copied that folder over everything will be the same you'll still need your versel do Json you'll still have like your Dev script you'll still need that empty public folder but the one thing that we'll need to update is this index.ts and so instead of importing handle from hono versell we'll need to import handle from the node.js adapter that comes from hono and so if you look in the hono docs if you go to versell and then go all the way to the bottom you can see that they have an example here and so one of the first things is we're not exporting that variable that says we're in the edge runtime so over here we'll need to make sure that we remove this so without that

we are now running in the node.js runtime next you'll see that we're pulling in handle from node server instead of hono verell now because when I set this up locally we are using node server as well if you look at our index.ts which is what runs when we do mpm runev it's pulling in serve from hono node server but over here we need to pull in handle so I already have hono node server as a dependency if you're not using this starter template make sure that you install hono node server and then you can grab this handle function now we'll import that handle from here instead and then we just need a single export so instead of exporting all of these methods we're just going to export a single call to handle and pass in the app the other thing is we need to disable no. JS helpers so in our EnV we're going to set no JS helpers to zero and then we can try running this locally so in the last example when we set this up we have a versel Dev command that's going to build the code and then run versel Dev and so now locally we can test it in the node.js runtime so I'll do an mpm run of versel Dev it'll build

it and then start it up and should be able to visit it looks good I can visit the reference page awesome so it runs locally now let's try to deploy this now because I copied this folder I do need to remove that versell folder that got generated if you're starting from scratch you don't need to to do this but I'm going to deploy this one separately from the one that's the edge run time so I need to make sure that that versell folder doesn't exist but now I can run versell and create a new project I can give it a name and then everything else will be exactly the same we'll just keep all of these settings and we're deployed I'm going to have to go set up those environment variables just like we did for the other project so we'll head here go into settings environment variables but we'll need to make sure that we also set nodejs helpers to zero whenever we're adding these environment variables here so I'll just do that and then paste in the rest of my variables save redeploy and we should be good to go and now we'll go redeploy so if I head to deployments we will say redeploy okay so it redeployed we can at least see our home page that looks good uh we can see our reference page awesome but what

happens if we hit an endpoint let's try it oh no server returned HTTP status of 401 so uh our environment variables are set so this is something I would expect if maybe we have the wrong off token set for turo but if we go to our project and we go into set settings and then environment variables our database off token is set so I debugged this for days and ultimately it comes down to when you're running your code in the versel node.js runtime and doesn't work as well with included libraries that attempt to use the built-in Fetch and so there there's this issue from a few years ago that asks how it works but these people mentioned just using node Fetch and so that's what we're going to do so here we're going to install node Fetch and so this is a version of fetch that was essentially like a polyfill that existed before fetch officially got added to node.js so fet F does exist inside of node.js but for whatever reason when it's running here on the forell node.js runtime there are some issues that pop up so now that we have that node fetch dependency essentially what we need to do is change the fetch that's used by

our database adapter so if we look in Source DB and then index you can see here that we're using the lib SQL client and they actually allow you to pass in a custom Fetch and this is what we're going to have to do now it's not pretty um but this will ultimately get it working and so first what we'll do is we'll Import in not fetch like so and then we can use it now you might be tempted to just pass it in directly I tried it this does not work essentially we're going to get access to the request which is of type web standard request and then we need to do some work to actually use node fetch so one of the things about node fetch is the first argument is always a URL so we can pass in request. url and then from there we need to specify our headers cuz that's going to have the off header and the content type and so here I'm going to set headers equal to uh request headers entries but this is an iterator it's not an object of keys and values so we need to turn it into that so what I can use is object. from entries pass this in and then I do believe we need to

spread it into an array for this to work properly so this is going to give us all the headers from the request that create got created by the SQL client and then lastly we need to pass in the body of the request and so this is the part that is somewhat cumbersome because essentially this request object has a readable stream that is the body we need to convert that into a string so that way we can pass it into node fetch honestly maybe this is way too many steps if you've been able to figure out nodejs versell deployment without doing this I'd love to hear about it let me know down in the comments but this is what we're going to have to do so essentially we have to create a text decoder and then make sure that this is an asnc function so we can use a weight uh we're then pulling in the body there from that request reading it all putting it into a string and then we can actually pass it into our node fetch here okay it's not pretty but basically this is what I was able to do to get it working in the nodejs runtime another thing you can do is just install a different request Library instead of node Fetch and then potentially pass the request in there but uh this is one way to do it so now just to make sure that

this runs locally I'm going to run mpm run versel Dev and make sure that that that fetch function Works make sure that we can actually hit our endpoints so if I head to slash tasks database is empty but it still comes back so at this point we can attempt to redeploy it okay it's deployed let's try it out so if we head back over to the deployed instance and refresh we can still get to the reference page let's try listing out our tasks it didn't work I forgot to promote the deployment so um I'm I'm hitting the endpoint that is production I need to make sure I do versel d-r so that it promotes this instance to the production instance now let's give it a try if I try to get our tasks I forgot one thing we need to specify the method okay so over here uh by default it's a get request we need that method to be a post request so this is how the the lib SQL client Works essentially it's making a post request to that server that in turn is is working with a SQL ey database okay so la last thing we need and then

then we should be good to go first s prod okay Moment of Truth third times the charm sweet we can get the data so now we're deployed to versel and the node.js runtime and last but certainly not least I'll show you how to deploy to cloudflare now cloudflare is what hono was actually built to deploy to so it's fairly easy to get it going but the main caveat here is I have done some things in this starter template that are not compatible directly with cloudflare so in cloudflare whenever you're working with environment variables or Secrets those are only accessible inside of the request inside of the fetch event handler so you can see in their their example for like a simple worker it gets access to EnV here this is the only way you can get access to environment variables and in the code that I wrote in our starter template I have environment variables accessible from process.env right and so this is not going to work inside of cloudflare so what I'm going to show you is how we can set this up so that we have a runtime EnV so that way like our our local build tools that need to use the EnV can work

Chapter 15 30:17

deploy to cloudflare workers

in the same way but all of our request handlers are going to need to pull in those environment variables from the incoming request so first up I'm going to clone the repo down and I'll put this into a cloudflare example folder we'll install dependencies and then one thing we're going to need is Wrangler so Wrangler is cloudflare CLI tool that allows us to test locally and then also easily deploy so we're going to install this as a Dev dependency awesome so we have that as a Dev dependency now we're going to need a wrangler.tj s/ starter they have all of the templates that are used whenever you're using the hono CLI and we can look at the cloudflare workers example to get all of our setup code here so if you look at this wrangler.tj

you can see in their example uh that they're using like a template but I'm just going to call this the hono starter cloudflare awesome so this is our file and you can see that it has a main entry point of source source index.ts but that's not quite what we want so if you look in their example Source index.ts exports a hono app and if you remember we have an entry point for our hono app so if we take a look our index.ts is the one that uses node server we don't want that we want to pass it in this because this is just exporting a simple hono app so right here we'll need to make sure that this says appts from there if we take a look at their package.json they have two scripts a Dev script and a deploy script so we're actually going to replace our Dev script with this one and then we'll also add this deploy script so over in our package.json we'll replace our Dev script like so and that looks good and then one last thing is they do have the cloudflare worker types so we'll be sure to install this as a Dev dependency too so if we copy that we

can do an npmi capital D Cloud flare worker types awesome so we're set up but now come the code changes because like I said we cannot access this EnV at runtime it has to be within a request so we're going to have to refactor our codes so the first thing I'll do is I'm actually going to rename our EnV type so this is the type that we've defined here with our Zod schema I'm just going to rename this to environment and the reason I'm doing this is it'll work more easily with the built-in hono types okay so that's called environment next up I am not going to export this EnV from here so anywhere that was import in EnV that code is going to break and I'm going to have to fix it to import from somewhere else then I'm going to export a function called parse EnV and this is just going to accept anything so it's going to accept an object and then use our Zod parser to validate that incoming object and then instead of passing in process. EnV I'll pass in that data safe parse gives us back data so we're just going to rename that to EnV and then here I'm going to return that EnV so essentially whenever we want to validate

Chapter 16 33:01

environment variable access updates

the EnV and get access to those variables we're going to pass in the thing that should have those variables it'll validate it and then we'll get back the object that has those validated values now in this case we don't want to exit this the process we actually want to throw an error so I'm just going to create simple little error message here that kind of combines everything into one so we're going to grab this error.

flatten do field errors we'll turn this into a template string like technically you could just pass in the Json data but I want this to be nice and readable uh if I do get this as an error message so I'm going to throw this in here so field errors is an object where it has the specific environment variable and then the associated errors if there were some so what I will do is actually use object. entries and so this is going to give me an array of arrays so each array is going to have the key as the first value and then that array of errors as the second value and so for each of these I want to turn it into a single string so I'm going to map over this we're going to destructure it grab the key and then the errors and then I'll return another template string uh that says the environment variable name which is the key and then specifies those errors and so right here I'm going to say errors. jooin we'll just join them with a comma like that uh and so essentially this is going to give me an array where you have environment variable name and then a list of Errors for all of those and now I want to take

that entire thing and then join that all together into a single string so I'm actually going to join this with just like a pipe like this single pipe okay it's a lot you don't have to do this like I said you can just Json stringify it but uh if you want this code check the link in the description I'll have this uh deployment code you can just go copy this um okay but now that we have that error message I'm just going to throw a new error and pass that error message in so essentially anytime we try to par the EnV it's just going to throw an error and I can actually use this inside of a middleware so I can have a middleware that gets access to the current EnV tries to parse it and then if something is missing it'll throw an error our default error Handler will c will catch it and then we'll actually see that in our logs that says hey you're you're missing some environment variable so let's do just that I'm going to head over to where we create the application here inside of create app and basically what I want to do is have a middleware that's the first thing that runs before any other Handler before any other middleware and it's going to validate

that incoming EnV so right here I'll say app.use we get access to the context and next and then I can attempt to validate it so I'm going to call parse EnV and make sure that I import it from EnV that's the function that we just wrote and I'm going to pass in C.V C.V are all of the buil-in secrets and variables that get passed to your Handler and hono makes that available there on the context so we're going to pass that in right now you can see that it's the unknown type I'll show you how we can set the type on it in a second and then after this we just say next like so and so what's going to happen is a request comes into our hono app and then we're going to validate that EnV if any secrets are missing it's going to throw an error and then immediately just respond with that error otherwise it'll go on and then every other middleware or function that needs to use that EnV will get access to it now let's actually set up this type so you can see right here that the type is unknown but this type can be set inside of our app bindings type so if we head to app bindings now the type that we pass in here to when we're creating a hono instance or an open API hono instance can also have a

bindings property and so if you look in the hono docs you can see here under app and then generics we can pass in our bindings and then this has all of the available environment variables and so we can do just that I'll pass in bindings but we can use that type we created so I'll pull in our environment type from EnV and now we're good to go and so that type has all of the environment variables that we should have access to and now that's just flowing through to the bindings and so if we head back over to where we defined this middleware now when I hover over EnV you can see that it has that specific type and so anywhere else in my application where I need to use those environment variables I'll do C.V and I'll get good type completion now to make sure that whenever we're running our code not inside of cloud flare and we want to load those environment variables from process. EnV we need to do something extra here so basically what I want to do is I want to reassign C.V to be the pars EnV and the thing I passed in is going to be a combination of C.V and process. EnV if it exists so to combine these two things together I'm

going to use object. assign so you could use like the spread operator but essentially object. assign is going to take the properties of both and put them into a single object so from here I'm just going to disable this lintra error and now whenever our app is running whether the environment variables are coming from cloud flare or coming from process. EnV every other request Handler that accesses C.V is sure to have those values now EnV could actually be undefined when we're not running in a cloud flare worker so I'm just going to pass in the empty object here now if we look at all the middlewares in our stack Pino logger is the first place where we actually access that context so this is what we're going to need to update you can see right now it was trying to import from our EnV file but that file does not export anything anymore so we can't do that essentially we need to get access to the content text so we can access C.V inside of this logger here so to do that I'm going to return my own middleware that has the context and the next function and then it's going to

Chapter 17 38:39

logger middleware updates

return the creation of this middleware here so we do like this now because we're returning this function we also need to invoke it and pass the context and next into it so we can do this and this is the JavaScript code that we need but if we want it to be type safe we're going to have to do some extra stuff so first of all if we want to define the type of this function one that's returning Locker it is a middleware Handler so right here we can say satisfies and then pass in middleware Handler this is a type that comes from hono now I need to make sure that I wrap this in parentheses so that way it's happy but now we should get some typings on C so if we look at C it appears as the context and the next is the next function but if I want to be able to do C.V in a type safe way then I also need to pass in my app bindings right CU right now if I look at EnV it's the any type but we do have our app bindings type and you can see the middleware Handler type is a generic type that takes in an EnV and that's essentially our app bindings type so right here I can pass in app bindings and import that

in from my types and this is the thing that we're also passing in whenever we create our hono app and this is the thing that also defines what our bindings should be and so now with those typings when I hover over C.V it has the correct uh type inference and I'm getting access to those variables that I need now lastly the context type here doesn't align with the context type of the Pino logger so we can actually just Define that type directly so here we can just say context so context is a type that comes from hono and then here we can pass in the EnV that's provided by penino logger so they actually export a capital E EnV from hono Pino and this is the type that actually includes that Pino logger binding right so there's that that type there um and then this isn't happy because it can't convert this type to that type so we are going to use an unknown right here so we'll say as known as that and then typescript is happy so the next spot we need to take care of is whenever we're creating the database connection because if we

Chapter 18 41:00

database connection updates

take a look at that code that needs access to process. EnV so that it can pass in the database URL and database off token but essentially what we'll need to do is recreate this client and database connection on every incoming request so the request comes in we get access to that C.V and then we can use those variables there so of course we don't have access to EnV anymore cuz it's exported and so essentially what I'm going to do is create a function that returns client and returns DB and allows us to pass in our environment variables so I'm going to export a function called create DB and this takes in the EnV which is going to be of type environment so we'll pull that in from EnV and then inside of here we'll create our client we'll create our DB and then I'm just going to return both of those so return DB and client like that and so now anywhere that needs access to DB is going to have to call this function and pass the EnV in and if we run our type check command we should see all of our type errors now we're going to have a few more Beyond just importing DB but

let's see what happens so yeah we can see that in all of our request handlers that access DB it can't do that anymore because that file does not export DB and the main place that this is happening is our request handlers so if we head over to routes and then tasks and then handlers this is where we access the DB right but it's not exported anymore the only thing that we export is create DB and so what we'll need to do inside of each of these handlers is create that DB using the environment variables so here I can say DB is create DB and then pass in the EnV inside of here context has the correct type right so if I pass in C.V you'll notice that typescript doesn't complain because we told it that it's going to be of this specific type and essentially that app route Handler helper that we defined in the other video passes in the app bindings which has access to the bindings and the environment type so this is completely happy and so essentially when this request comes in we can create that DB instance and then use it to make the query and right now this isn't the

default export so I actually I don't want it to be the default export I want this to just be an export so I don't confuse the default export with it so this module should just export a function called create DB and then in this case we're going to have to destructure it right because we return the client and the DB so we're just going to pull off the DB there and the codes are happy so essentially what I'm going to do is do this inside of each of my handle that needs access to the DB and when you're deploying things to Cloud flare workers this is how you'll do things because each one of these requests is kind of like a serverless function right it it basically just spins up and that's when you'll need to create that that database connection so we're not really duplicating work here especially because this is going to be running inside of cloud flare so I'll also add this here so that looks good and we're getting a type error here for our query but I'm going to ignore that from now and if I fix it I'll I'll come back to it later in the video now at this point if we run a type check again the only spots that should complain are the ones that we're trying to access the EnV directly we take a look it's in our

Chapter 19 43:54

create runtime env

drizzle config it's inside of our main entry point which we don't need anymore because we're going to be using cloudflare workers and then it's inside of our tests so if we take a look for instance at the drizzle config this doesn't run in the context of cloud flare workers this is only running on my machine when I run like drizzle kit push or drizzle kit studio so I do somehow need access to the EnV here so what I'm going to do is create another file called runtime EnV and any file that basically needs the environment variables at runtime not inside of cloudflare can use that specific import so I'm going to create EnV D runtime and all I'm going to export from here is a call to parse EnV and pass in the process. EnV so I'm going to say export default parse EnV which is the function we defined there in our EnV module and then we're going to pass in process study andv right here and then I'll ignore my lter error and so any place that that does actually need access to this at runtime can import this file so

over here we're going to import this from en- runtime and then same thing inside of our tests so if we head over to routes and then test we'll import our EnV here from EnV - runtime okay if we run a type check again the only spot that is now complaining is our main entry point which we actually don't need anymore so if we look at this index.ts this is the one that was pulling the app in and then calling it with node server we don't need to do this anymore because we're we're running our app using Wrangler and then using Cloud flare so I'm actually just going to delete this file okay from here I'm going to try to run the test this is one of the nice things about having a comprehensive test Suite is I can make all of these refactors and if the test passed I know I did everything right and they do pass so at this point we can try running it locally with Wrangler because at least our tests are running and the tests are running in the context of node.js right it's running locally with vest which uses using node and then also compiling our typescript but when we run with

Wrangler it's going to run it in an environment that's similar to how it will be running when it's actually deployed to Cloud flare so let's give it a try if we do mpm run Dev that's going to run Wrangler now we do get one error where we're importing our package Json so if we take a look in where we're configuring open API we want to pull in that version number from the package.json so in this case I use this esm way of importing Json modules but we can actually just not include that and it should still be able to bring it in so to make sure this is a truly fresh install I'm just going to remove all of my node modules and then do a pnpm install now let's reload vs code I have a feeling that this npm install also fixed the drizzle error we were getting earlier so if we take a look in here and then take a look at our handlers yeah this doesn't throwing in a type error anymore okay for some reason our our node modules are out of date but now we can give it a try so if I do mpm run Dev okay so I was doing some digging and the CLI tool that clones that hono

Chapter 20 46:05

fixing wrangler specific errors

starter template for cloud Flor workers actually has some code that goes in and updates the compat date to be today's date so I'm going to try doing that if I set this to today's date and then save that and then try running Wrangler that at least doesn't error for us it says the latest compatibility date is this one so I'm going to grab that one update here all right hope for the best let's try running it now all right it looks like the app has spun up and now I can request 8787 sweet this is what we want to see so now our app is running with Wrangler and you can actually see that it tries to parse the EnV and I don't have a log level I don't have a database URL and so the way that you create secrets for cloudflare workers is by creating AEV dovar file so in order to actually read those variables in we need to make sure that we have a Dev vars file so what I'll do is just copy my EnV into a file called dodev dovar and then I'll need to make sure that I add this

Chapter 21 47:27

creating cloudflare .dev.vars

to to my G ignore as well so down here we'll add dodev do bars because this will potentially have secrets in it we want to make sure that we don't push those up and with that we'll start it back up we can see that it loaded in my environment variables so this is good now let's try making a request to our app again the root loads Sweet let's try out some of our endpoints so if we head to reference and then we try to load all of our tests this should fail because there is no database we haven't even done a migration let's see what happens we get a different error that I've already debugged for you so it says URL scheme not supported the client that uses web sted apis um supports only lib SQL https or HTTP and got file so when we're working with websql locally and cloudflare workers we actually can't use this file URL here now we could actually just put our turo URL directly but then we're actually like talking to the production database when working locally so one thing we can use is the turo dev command which will give us just a local host URL that we can pass in here so if

Chapter 22 48:25

local dev with turso

you head to the turo docs they have a section here on local development and we can use the turo CLI to spin up a database and you can actually pass in a database name and then it gives you just a local host URL that you can use to talk to that database and so if we want to combine turo with cloudflare workers essentially we'll need to do this when we're running locally so first let's install turo as a Dev dependency and then I'm going to add another script here called Dev DB and this will essentially run turo Dev but I always wanted to look at that same local database so I'm going to copy their run command here and then point it to dev.

DB and so now locally we can run this command in a separate terminal that starts up the turo server and then we can have our app connect to it over Local Host so that looks good one thing I'll do before that is to actually create the database and push the schema to it so that way this file exists whenever turo Dev spins up so here we'll just do pnpm drizzle kit push I should be able to read my EnV just just fine remember we updated it to use the Run time EnV and then it actually creates that database so if we look in our local folder we now have that dev. DB file but now if I run uh mpm run Dev DB that will start up the turo CLI and then use that specific database now when you spin up the terso dev instance it actually creates some files next to your database we're going to need to make sure that we ignore those as well so in our G ignore I'm just going to do dev. db. star so that way uh we don't commit that extra stuff to get and so now I can use this URL to connect to it so if I head back

over to my Dev vars I'm going to point it here and then restart my app and now it should use the turo HTTP Local Host API to connect to the database and we should be able to run our endpoints so in another terminal I'll run mpm run Dev this starts up cloudflare worker we can now visit it and if we head back over to our docs and try to list all of the tasks looks good we get back an empty array and so now we can even try creating like a local task let's do that the name is uh learn Cloud flare workers set this to false cuz we got lots of learning to do that puts it in the database and then I should be able to list them all and we can awesome so locally I've got Wrangler running that runs my app as a cloudflow worker on my local machine I've also got the turo dev CLI so that way I have a local DB but now we can try deploying and so earlier when we copied the into our project it added a deploy command and so we can

Chapter 23 51:25

deploy to cloudflare

just run npm run deploy from the CLI now for this you'll need to make sure that you have a cloudflare account and you've enabled workers and everything else but because I have we should be able to run it so if I do mpm run deploy sweet and if I try to visit it it needs some environment variables but this is good this is good it's in the cloud so let's head to our Cloud flare dashboard and then set up all of our secrets so here in my dashboard I can go into my app and then if I click on settings there is a section for variable and secrets and so I'll go in here add all of my variables I'll add my node EnV log level uh my database URL the one that points to turo and my database off secret so I'm going to go through and do all of that now and in this case I don't want to redeploy for every single variable so I'm just going to say save and then add all of them and then I'll redeploy now since we added those variables and deployed from the cloud flare dashboard if you attempt to deploy from your CLI you will see a warning that says edit that have been made via

the dashboard will be overridden by your local code and config so you don't want that so we're going to say no not continue but we'll just make sure that in our

wrangler.com SL reference it loads uh but if we make the request here it should load the data from our turo DB and it does so let's actually patch that task so we're going to patch the task with id1 and we're going to set done to True here we go sweet now done is set to true that's it for this video thank you so much for watching there's a lot more stuff I want to explore with hono but hopefully this got you started on deploying your node.js apps if there's anything I didn't cover or anything you're having issues with let me know down in the comments ments and uh I'll see you in the next one [Music]

Chapter 24 53:14

Thanks!

Quote it with credit and a link. Quoting Syntax