A Better Way to Write APIs?

  Рет қаралды 82,761

Josh tried coding

Josh tried coding

2 ай бұрын

Turns out a method i found out that seemed pretty hacky to me at first because it messes with framework defaults actually works quite well. It's pretty fast, cheap, and easy to set up. Honestly there might be bugs that I haven't found yet, so please dont use this in production yet lol
-- sources for this video
hono: hono.dev/
cloudflare workers: workers.cloudflare.com/
-- my links
saas: www.animate-code.com/
newletter: www.joshtriedcoding.com/
discord: / discord
github: github.com/joschan21

Пікірлер: 131
@ajaymandal2560
@ajaymandal2560 2 ай бұрын
This is amazing guide, watch step by step while integrating hono in my nextjs app. Thanks alot
@vigneshm5044
@vigneshm5044 2 ай бұрын
Nice insight. For real world apps with database, the latency can be worse twice as much. If the database is located at the same location of cloudflare, fetch from Database will be fast, but that won't be the case since cloudflare workers are global. So once the request reaches cloudflare, another request has to go to the database. And if the request issues multiple DB queries, there will multiple requests to DB. Eg find user and then find orders. So in case of requests requiring data from DB, better to colocate the server and DB in same region
@FabuBrik
@FabuBrik 2 ай бұрын
FAST_MODE: true is hilarious.
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
hahaha cheers man
@mendylanda125
@mendylanda125 2 ай бұрын
Saying it’s double the performance is a bit of a stretch, in a basic example such as yours you’re saving the 10ms overhead that Vercel requires (understandably- Logging, Billing, Auth, etc etc). The real question is how does it compare in a real world use case, my bet is it will remain in the 10ms range, and definitely not “double”. Great vid though ❤
@aryan.prince
@aryan.prince 2 ай бұрын
yeah just like you mention, i also wonder if hono/CF workers will actually take half as long, or just within ±10ms compared to Vercel Edge network i haven't tested this on a large scale with more complex API calls, curious what y'all think about this
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
in my tests (production environment) I got about a ~30% consistent speed difference for db interactions in both API routes. Decided to leave it out cause that part was just boring, probably wouldve been a good idea to at least include the results. Fair point, appreciate ya
@anasouardini
@anasouardini 2 ай бұрын
Another awesome video 🔥
@jitx2797
@jitx2797 2 ай бұрын
I really like Hono + Clouflare Workers. Also D1 works fine too. I sometimes use Turso or D1
@yourlinuxguy
@yourlinuxguy Ай бұрын
Can you tell how to access env vars in hono? Outside ant .get methods?
@deo_kumar
@deo_kumar Ай бұрын
​​@@yourlinuxguyyou can't access env variables in top level of your module. If you want to use any library that requires env variables. You should use hono's vars middleware if you are using hono. Like this: const app = new Hono(); app.use(async (c, next) => { c.set("myDb", new DB(c.env.MY_ENV)); await next(); }); app.get("/", (c) => { const db = c.get("myDb"); return c.json({...}); });
@rishabhpandey6335
@rishabhpandey6335 26 күн бұрын
​@@yourlinuxguyif you find out ,let me know
@yourlinuxguy
@yourlinuxguy 25 күн бұрын
@@rishabhpandey6335 you can't access .env outside the .get methods
@KrishnaJha25
@KrishnaJha25 2 ай бұрын
I’m working on a project with a client using CF worker, CF worker for platform, hono and solid js and trust me things are super fast. We are talking about single digit millisecond performance. So yeah this works
@Goshified
@Goshified 2 ай бұрын
"yeet" as a dummy commit message. I feel so seen right now.
@MaximeDehaye
@MaximeDehaye 2 ай бұрын
From where the difference in speed is coming from then ? If both are hosted on CF anyway
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
honestly no idea, I'd like to know as well
@sanampakuwal
@sanampakuwal 2 ай бұрын
I guess that might be vercel overhead like: logging, analytics, routing, reading config, etc. But I'm not totally sure.
@MagerX1794
@MagerX1794 2 ай бұрын
@@joshtriedcoding vercel has a ton of logging and middleware and other built in utilities that it needs to step through is my presumption.
@thatpenguin965
@thatpenguin965 2 ай бұрын
youre channel is a dream come true. Where do you even find these lol
@st-jn2gk
@st-jn2gk 2 ай бұрын
Vercel has something called “regional edge” where they deploy your backend to a cloud flare worker localized to a region like east US or whatever. Normal cloudflare does not do that. I don’t know if your vercel deployment was using regional edge, but if it was, that would explain the speed difference. Regional edge allows you to make multiple DB queries without the downside of the distance cost from a distributed edge to a centralized db. I think you can test it by having the backend do like 3 queries to a database. If Vercel is still slow in that test, then this is an easy cloud flare W. Cool video king, I love high effort stuff like this.
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
interesting, I wonder if the regional edge thing could be the reason for the difference or if its also the vercel tracking, logging etc. Cheers man!
@st-jn2gk
@st-jn2gk 2 ай бұрын
true. it might be the deployment region or the proprietary layers of logging and tracking. Cheers back!@@joshtriedcoding
@avid459
@avid459 2 ай бұрын
I am waiting for their latest offering, the ultra pro edge, where the code to be executed will be even closer than the edge, it will be on the users device.😎
@adamconrad5249
@adamconrad5249 2 ай бұрын
standard AWS feature
@st-jn2gk
@st-jn2gk 2 ай бұрын
? not its not wdym@@adamconrad5249
@diegoquiroz1059
@diegoquiroz1059 2 ай бұрын
Great! But the problem with edge or regional runtimes like CF Workers is when the distance between the worker (backend) and its other sources matters. If the regional backend needs to fetch multiple times from a far away source (e.g. database on US-East), it will be worst. If it's one call, it will be the same time overall. client backend database [backend is near the client] client backend database [backend is near database] This shines when the database read replica is regional too, like Turso
@carlosricardoziegler2650
@carlosricardoziegler2650 2 ай бұрын
Nice, I am using it and is amazing, fast and so simple :)
@MyCodingDiarie
@MyCodingDiarie 2 ай бұрын
I've watched this video multiple times. Never gets old!
@tvnishq
@tvnishq 2 ай бұрын
This was released yesterday bruh
@FeneelAPatel
@FeneelAPatel 12 күн бұрын
@@tvnishq lol
@sathishkannan6600
@sathishkannan6600 2 ай бұрын
I think you can just add FastMode during built time. but conditionally exporting "edge". Adding the hono, only helps in treating the backend code just like a separate server.
@frackinfamous6126
@frackinfamous6126 2 ай бұрын
Do a video building out backend in bun. My curl responses always smoke my command prompt and break the screen 😂. Elysia and Hono both great frameworks but I’m leaning towards Elysia.
@kasper369
@kasper369 2 ай бұрын
Discovered Hono while back, So excited that i could not sleep. Tell me Hono.js vs Elysia.JS which
@tamicktom
@tamicktom 2 ай бұрын
Elysia ❤
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
both are kinda goated
@nvsWhocares
@nvsWhocares 2 ай бұрын
What about nextjs middleware on CF workers? Should work too, no? Maybe a test with typical middleware like clerk or next-intil. If that stuff runs on CF might be some serious Speed gains 🔥
@yousofscodingadventures
@yousofscodingadventures 2 ай бұрын
Banger
@patrickbranchaud7711
@patrickbranchaud7711 Ай бұрын
Do you think cloudflare/next-on-pages gives a similar configuration and speed result? might be another comparison to do?
@xaviertromp2359
@xaviertromp2359 2 ай бұрын
Can it replace tRPC or it does not provide the same e2e typesafe story? How about validation/error handling? Thanks for pointing the Vercel overhead.
@daphenomenalz4100
@daphenomenalz4100 2 ай бұрын
How to deploy the frontend seperately too? I just got to know about this 😅, searched it up couldn't find it. Could you pls tell
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
if its static you can port it to pretty much anywere, even if not most places support next builds out of the box like railway, amplify or netlify
@robindeguzman8741
@robindeguzman8741 2 ай бұрын
How to fix the build error, wherein the error shows if the APIs that are being fetch are from the NextJS API instead of external API?
@mr-skorpion
@mr-skorpion 2 ай бұрын
How big of a script, size wise, can you host on CF workers anyway?
@nro337
@nro337 2 ай бұрын
super cool!
@FedericoGobea
@FedericoGobea 2 ай бұрын
Is this associated to the server? or to hono / next?
@naylord5
@naylord5 2 ай бұрын
Great timing Josh! Thank you for this useful video. Please I have a couple of rooky questions: - CF Workers can entirely replace backend part of a web app? because in the pricing panel I see "Up to 10ms CPU time per request" in free tier, so makes me wonder if is only for very light request / payload or if can handle PDF creations or batch database transactions.. - I'm just getting familiar using Next.js for the API / backend part, can I reuse the endpoints generated by Vercel or CF workers to write lets say a native mobile app? It generates a URL that can hit with headers auth or so? Thank you so much in advance!
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
hi! Technically you can reuse the APIs, practically you'd normally use a separate backend. At my last job we used fastify as the backend that our iOS, android and web apps could all access and it worked great
@naylord5
@naylord5 2 ай бұрын
@@joshtriedcoding Thank you for the insight 🙌
@twitchizle
@twitchizle 2 ай бұрын
10ms cpu time is not low. Its more than enough. But i dont think you can run pdf generations on cf workers.
@naylord5
@naylord5 2 ай бұрын
@@twitchizle thank you mate, definitely will give it a try and compare between workers and AWS lambdas
@randomname8217
@randomname8217 Ай бұрын
So the only difference is switching the backend host? Wow, that's really a valuable insight
@Argosh
@Argosh Ай бұрын
The channel is called Josh tried coding, not that he succeeded.
@peternicholas4750
@peternicholas4750 2 ай бұрын
Does this work with preview deployments?
@user-ik7rp8qz5g
@user-ik7rp8qz5g 2 ай бұрын
What about deploying it to normal vps? Cheap, performant and without cold starts ever
@Schisek
@Schisek 2 ай бұрын
I think with this approach you are calling the nextjs route from a server component using fetch which gives some overhead. But I guess the App Router was invented to avoid these unnecessary fetches. So maybe a client component would be a better comparison
@matthewbeardsley7004
@matthewbeardsley7004 Ай бұрын
It certainly seems like a nicer way than using route.ts files, even on small projects, that doesn't seem appropriate, yet alone something decent.
@PeterZhou-vi3ep
@PeterZhou-vi3ep 2 ай бұрын
🎉🎉🎉
@kewin1855
@kewin1855 2 ай бұрын
Does this work with nextAuth v4?
@aurindo15
@aurindo15 2 ай бұрын
Is it possible with trpc?
@MikaelXJohansson
@MikaelXJohansson 2 ай бұрын
Try K6 performance testing for better statistics
@mdsalahuddin2841
@mdsalahuddin2841 2 ай бұрын
how did you managed avoiding ; (semi-colon) at the end code?
@exciting-burp6613
@exciting-burp6613 2 ай бұрын
It's called automatic semicolon insertion. Very few people learn about it, so it ends up being confusing. It is nothing more than a toxic flex, don't use it.
@MikeBooger
@MikeBooger Ай бұрын
Because what for?
@dabbopabblo
@dabbopabblo 2 ай бұрын
3 years into a project and I wish I didn't use this paradigm. Over time Ive been forced to start defining groups of related routes in their own files as the main.go file serving the main web server has grown to be over 23 thousand lines of code. Its not nearly as practical to edit or make changes to something so large with the latency the language server takes alone, compared to defining routes in their own files. Plus with golang there is no performance penalty for spreading the same module/package/app across multiple files because they are all compiled into one binary before the servers executed.
@wanarchives
@wanarchives 2 ай бұрын
why im getting Error: You cannot define a route with the same specificity as a optional catch-all route ("/" and "/[[...route]]"). ? i follow ur video instructions :(
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
might be a problem with the pages vs app router, if you have both at the same time (hono initialized with pages by default, I switched to app manually), this can happen
@wanarchives
@wanarchives 2 ай бұрын
@@joshtriedcodingi use app router only and never done pages router
@KellenProctor
@KellenProctor 2 ай бұрын
Per the hono docs, move /app/[[...route]] to /app/api/[[...route]]. That fixed it for me
@3ladeZ
@3ladeZ 2 ай бұрын
Wondering about hono vs elysia aswell
@PaulVarna
@PaulVarna 2 ай бұрын
I prefer Elysia, but Elysia has some "Bun only" stuff, that doesn't work on Workers.
@heyitsfemzy
@heyitsfemzy 2 ай бұрын
Can I not just host my NextJs app on Cloudflare pages? As far as I know, all your serverless functions are deployed as workers this way
@calebcook96
@calebcook96 2 ай бұрын
That was my first thought because thats where Ive been hosting mine.
@r3plican
@r3plican 2 ай бұрын
are u not censorring env vars? in the minute 4:27 i can see the user and pass of ur database is
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
i just rotate passwords or delete databases before uploading
@herzog0
@herzog0 2 ай бұрын
Wtf is export default as never??
@samsupplee-niederman1752
@samsupplee-niederman1752 2 ай бұрын
From my understanding, it’s telling typescript “I need to export this file, but I should never use/import it anywhere else”
@AbegazNap
@AbegazNap 2 ай бұрын
what was I saw, a new tcp connection being established to the database on every request, it is PHP all over again lmao
@farjulmallik4135
@farjulmallik4135 2 ай бұрын
bro can you elaborate more on this !!!!....
@AbegazNap
@AbegazNap 2 ай бұрын
@@farjulmallik4135 He is calling the function that establishes the connection inside the route handler which means a connection is being established on every request made to the route handler, this was mainly due to not being able to access the environment variable and not a runtime limitation, but this emulates what PHP does where it is completely stateless and the concept of database connection pooling or long lived connections do not exist because on every request php restarts its process. Most backends nowadays have connection pools to alleviate the issue of connection reestablishment. Not having pools or not having a long lived connection may not be the main concern of users of such a system, but there is a stark difference in terms of database IO performance between backends using a connection pool/long lived connection and those which do not.
@zoladkow
@zoladkow 2 ай бұрын
yep, so now it's JS turn to solve those issues again :)
@twitchizle
@twitchizle 2 ай бұрын
Pgbouncer
@grinsk3ks
@grinsk3ks 2 ай бұрын
I don't understand why I see so much hono, while nobody mentions h3. H3 works everywhere with everything, while having 10 times the usage.
@khazixfangirl6087
@khazixfangirl6087 2 ай бұрын
My guess would be more familiar API (feels like express)+ they add some interesting features
@wolfphantom
@wolfphantom 2 ай бұрын
h3 and nitro are both great to work with
@CoryTheSimmons
@CoryTheSimmons 2 ай бұрын
Immediately noticed "eventHandler" bloat. Otherwise looks identical.
@daphenomenalz4100
@daphenomenalz4100 2 ай бұрын
Looks like express
@sanampakuwal
@sanampakuwal 2 ай бұрын
nextjs backend? emm.. dotnet backend, yes!!!
@JakobTheCoder
@JakobTheCoder 2 ай бұрын
What is wrong with using Next.js as a backend framework? Isn't it nice that you can stay in the same language and framework and have it deployed the same way?
@spooky4655
@spooky4655 2 ай бұрын
​@@JakobTheCoder i think op is joking
@PieterWigboldus
@PieterWigboldus 2 ай бұрын
@@JakobTheCoder If you are frontend developer, and only use it to connect to a single frontend. If you want to do more with your backend, Next.js is not a good choice. It is a backend for frontend, not a backend to create a generic API. Also if you want to build more workers / microservices, or want more freedom and not have vendor locking, Next.js is not what you want. So Next.js is great as frontend developer, and only for a single frontend with a single backend.
@sanampakuwal
@sanampakuwal 2 ай бұрын
​@@JakobTheCoder yes, great for small-medium size applications, but JavaScript's performance is not enough for large/perf centric applications. This is where C#, Java, Rust, and other languages shines!!
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
@@sanampakuwal There are good points to make for and against using JS / C# etc. on the backend, this is a great discussion
@daphenomenalz4100
@daphenomenalz4100 2 ай бұрын
I'll still prolly use express or rust for backend, but knowing this is pretty good for small scale applications that I don't want to spend much time on 👀
@genechristiansomoza4931
@genechristiansomoza4931 2 ай бұрын
The fastest api is a "no code" api.
@iury664
@iury664 2 ай бұрын
what it means "run at the edge" i'm not english natural, so i didn't get it.
@tubero911
@tubero911 2 ай бұрын
Hosted at a CDN edge location. Closer to the user, so lower latency.
@sanyamjain7229
@sanyamjain7229 Ай бұрын
hey. You have 120K subscribers. you need to work up the game. (we all know this video was not up to the mark .) btw, vercel also supports edge functions.
@AkashLayal
@AkashLayal 2 ай бұрын
hi josh i wanted to know how can we use prisma on cloudflare worker.
@Malix_off
@Malix_off Ай бұрын
Use Drizzle instead
@AmodeusR
@AmodeusR 18 күн бұрын
It seems Vercel just gave up on Edge, this won't be an option anymore. At least not with Vercel. kzfaq.info/get/bejne/oqd3eJCclsDKops.html
@coocasualvibes9901
@coocasualvibes9901 2 ай бұрын
Even backend from Node Js is too vast and heavy for any software services
@venkatesheraser
@venkatesheraser 2 ай бұрын
what is the name of the font?
@noext7001
@noext7001 2 ай бұрын
can you make it work with trcp ?
@ephorUA
@ephorUA 2 ай бұрын
yes, there is trpc middleware for Hono
@austincodes
@austincodes 2 ай бұрын
You can make anything with with trpc
@user-gs3lm7gt5e
@user-gs3lm7gt5e 2 ай бұрын
Using Edge is not fundamentally writing faster api....
@k0in640
@k0in640 2 ай бұрын
"how to make your api faster" use a faster service! - duh
@gustavo-oi1dd
@gustavo-oi1dd 2 ай бұрын
or just, saying, pick another language
@iogilarb
@iogilarb 12 күн бұрын
what is this? 😅
@editxswajal
@editxswajal 2 ай бұрын
Please heart ❤
@joshtriedcoding
@joshtriedcoding 2 ай бұрын
for sure man
@editxswajal
@editxswajal 2 ай бұрын
Last
@indrakhatiwada9860
@indrakhatiwada9860 2 ай бұрын
First
@FranFiori94
@FranFiori94 2 ай бұрын
Nah thanks
@PeterZhou-vi3ep
@PeterZhou-vi3ep 2 ай бұрын
prisma do not work
@Malix_off
@Malix_off Ай бұрын
That's because you don't use Drizzle
@nnz13
@nnz13 25 күн бұрын
15ms vs 30ms nobody cares
@eliassmith7949
@eliassmith7949 2 ай бұрын
stop making from nextjs freaking backend -_-
@user-so4ug5rw3g
@user-so4ug5rw3g 2 ай бұрын
What ur doing is not programming. Children Playing coders 🤷‍♂️
@joloppo
@joloppo 2 ай бұрын
Stop deploying js backends 😂
@gofudgeyourselves9024
@gofudgeyourselves9024 2 ай бұрын
virat kohli had a baby boy
Oh, Auth Doesn't Have to Suck?
7:16
Josh tried coding
Рет қаралды 49 М.
The Problem With UUIDs
6:36
Josh tried coding
Рет қаралды 64 М.
когда одна дома // EVA mash
00:51
EVA mash
Рет қаралды 9 МЛН
Зу-зу Күлпәш. Стоп. (1-бөлім)
52:33
ASTANATV Movie
Рет қаралды 191 М.
4 UI Design Tools I Can't Live Without
5:08
Josh tried coding
Рет қаралды 63 М.
Has Generative AI Already Peaked? - Computerphile
12:48
Computerphile
Рет қаралды 108 М.
I Made This Open-Source Project
7:22
Josh tried coding
Рет қаралды 58 М.
This UI component library is mind-blowing
8:23
Beyond Fireship
Рет қаралды 526 М.
So You Think You Know Git - FOSDEM 2024
47:00
GitButler
Рет қаралды 901 М.
Is "edge" computing really faster?
8:14
Fireship
Рет қаралды 553 М.
If this ships, it will change javascript forever
25:54
Theo - t3․gg
Рет қаралды 181 М.
Why We Switched From Svelte Kit To Golang + HTMX
9:54
Anthony GG
Рет қаралды 71 М.
40 APIs Every Developer Should Use (in 12 minutes)
12:23
Coding with Lewis
Рет қаралды 225 М.
КУПИЛ SAMSUNG GALAXY S24 ULTRA ЗА 88000 РУБЛЕЙ!
27:29
Result of the portable iPhone electrical machine #hacks
1:01
KevKevKiwi
Рет қаралды 8 МЛН
How much charging is in your phone right now? 📱➡️ 🔋VS 🪫
0:11
Vortex Cannon vs Drone
20:44
Mark Rober
Рет қаралды 13 МЛН