r/node • u/stackchief • Feb 21 '20
Koa vs Express WITHOUT the BS
https://www.stackchief.com/blog/Koa%20vs%20Express%2027
u/evert Feb 21 '20
One thing I like about Koa vs Express is that it's way easier to change the response body in a middleware. In express this is very clumsy because everything directly operates on the socket.
We use this to create a pretty HTML interface on our JSON-based API. It only kicks in if the Accept header includes text/html.
9
u/Lumpy_Idle Feb 21 '20
I’ve been using koa for my latest project and haven’t touched express in quite a while. Could you expand on this a bit? Genuinely curious.
10
u/evert Feb 22 '20 edited Feb 22 '20
Basically, the primitive in express for writing the response body is node's socket.write. Once something has written to the socket, it's gone. With koa, you set
ctx.response.bodyand it's buffered until all middlewares are done.So if you look at the Koa vs. Express middleware for gzip (which also needs access to the response body), the express middleware actually needs to 'mock' part of the response. The amount of code needed for each is a massive difference. So if you want a real example, look at those.
Fwiw I ended up also having some issues how koa abstracts http messages, and ended up writing my own framework: https://github.com/curveball. It's not popular but a few dozen people use it and seem to like it. 100% typescript, better HTTP/2 support and loosely coupled to Node's http library, which made AWS Lambda support super easy and not a crazy hack.
2
Feb 22 '20
Damn that framework sounds right up my street. Commenting to remind myself to try it sometime
1
u/Lumpy_Idle Feb 22 '20
Ah thanks, will look into the gzip example. Very impressive to put out a framework. How do you even get started on a project like that?
4
u/evert Feb 22 '20
Frankly, it's easier than you think! You need to represent a request, something to represent a response and something that can chain middlewares. That's really the basic recipe for both mine and koa's, and every other package just uses those primitives. If you are interested, I would highly recommend giving it a whirl!
1
u/nothingbutt Feb 22 '20
That's a nice example and a cool idea.
2
u/evert Feb 22 '20 edited Feb 23 '20
If you're interested, the project page has a few screenshots:
https://github.com/curveball/hal-browser
We've since gotten a new main theme, but the screenshots still need to be updated. Works great if you use links in your JSON, as you can make a fully user-traversable auto-generated interface. We've deployed this for a few clients, and it ends up being a useful tool for non-developers to explore the graph of data too.
38
u/Funwithloops Feb 21 '20
I've been using Koa in projects for a few years now without any major complaints. It amazes me that the majority Node community decided 10 years ago to stop looking for better solutions than Express (and that in 2020 you still have to use wrappers and magic global hacks to use async/await in Express).
32
u/colnarco Feb 21 '20
Well if it ain’t broken don’t fix it. Express works really well. There is good documentation, easy extendability, good performance, lots of answered stack overflow questions and many tutorials both free and paid. I am not bashing Koa, and I am sure it will take over at some point but I honestly don’t think there are big wins for rewriting existing applications. If I started out on a fresh project now I would consider Koa, but I honestly really like express and have never had any problems with it - which i think is quite rare in programming!
15
u/leeharris100 Feb 21 '20
I honestly really like express and have never had any problems with it
I would say that's partially because Express does so little.
I come from .NET, Laravel, Java Spring, etc. These frameworks do an unbelievable amount of stuff for you. You obviously trade off performance for features, but dev time is far more expensive than server time for 99.99% of projects.
I'm with OP in that it's crazy to me that something like AdonisJS has 6k weekly downloads on the CLI and Express has 11 million. Is nobody looking for something more powerful? I guess people who are looking for more features just stick with stuff like C#/PHP/Python/Java where it's much more mature with many more options.
20
u/ewouldblock Feb 22 '20
I think you're discounting the market for microframeworks. The reason people like express is precisely because it does so little. It's the whole point. Koa is also a micro framework so it doesn't explain koa vs express popularity.
3
u/ScientificBeastMode Feb 22 '20
Tech leads and managers are super risk-averse. They’d rather have a shitty time with something that doesn’t live up to expectations and still deliver some kind of product, rather than choose something untested and hit a wall that risks grinding the project to a complete halt.
2
2
u/Funwithloops Feb 21 '20
Definitely. We've got old projects running on express. I just wouldn't recommend it for new projects, but it's still really common for people to treat express like a fixture (I mean just look at all the acronyms that refer to express like "MERN").
Though I'd say express is broken because it doesn't doesn't support async/await out of the box.
10
u/colnarco Feb 21 '20
I am genuinely curious about how express doesn’t support async await. Am I missing something? I am using express with async await out of the box on a daily basis. I am wrapping my route handlers in try catches which is a bit clumsy, but not a major deal breaker for me. Plus it allows me to handle errors on a per route basis (determining proper status codes for error response, logging relevant data and setting the importance of the error etc.)
4
u/blood_bender Feb 21 '20
express-promise-router handles a lot of that for you, so you can go back to one global catch handler if you want.
If I need specific errors per route I do that, otherwise I usually just extend the error class (UserError, AuthError, ServerError, etc) and the global handler
instanceof's the caught error and formats the response (400, 401, 500, etc) respectively.2
u/colnarco Feb 21 '20
Looks good! Will definitely check that out! Can you show an example of how you extend the error class? Not quite sure about how that is done and it sounds very interesting.
5
u/blood_bender Feb 21 '20
basically I have an
errors.jsclass with like:class UserError extends Error {} class ServerError extends Error {}then in the route I'll throw a UserError("message"). Then in my final express error handler I have something like:
function errorHandler(req, res, next, err) { if (err instanceof UserError) { res.status(400).json(err); } else if (.... }1
u/colnarco Feb 22 '20
Wow okay TIL. Just read up on error handling with express. I honestly didn’t know this was possible. Thanks for the details! Helped me a lot.
I have never used express for anything other than api servers, so the win isn’t very big for me as my error handling is usually quite simple like res.sendStatus(500) or similar but will definitely remember this for future reference.
3
u/Funwithloops Feb 21 '20
Having to wrap every handler in try/catch is a deal breaker for me. I usually just attach status codes directly to errors and 500 for unexpected errors.
The
nextfunction in express also doesn't return a promise, so it's not as easy for a middleware to run something, wait for all downstream handlers to run, then run something else.You can use async/await with express. It just takes extra steps and you'll get unexpected results if you forget those steps.
3
u/blood_bender Feb 21 '20 edited Feb 21 '20
express-promise-router handles most of that for you at the route level. middleware you still need to handle those situations though.
6
u/Funwithloops Feb 21 '20 edited Feb 21 '20
Yeah. There's lots of ways around these inconveniences. Express could even merge them in, but that involves breaking changes. This kinda highlights the major differences and the reason express was effectively forked into Koa:
No breaking changes (it's a new package)
Promises are first class citizens (throwing an async error shouldn't have different behavior than throw a sync error by default)
More modular (less built-in middleware and random functionality like template rendering)
I'm not completely sure why the Koa devs (who were apparently also the Express devs though I'm guessing this isn't the case anymore) didn't just create a major release with breaking changes. I'm guessing they saw what happened when the Angular folks tried that and decided a new package would be less offensive.
This is all speculation. I haven't actually spoken with any of the express/koa devs. Though I'd love to hear them chime in.
2
u/blood_bender Feb 21 '20
I think koa was released before Angular2, but I might be mistaken on that. It was my impression that those devs had already left the express team to develop koa from the ground up. But again, I don't know.
I like the concept behind koa for the most part. The only reason I haven't made the switch is because I have a lot of utility/boilerplate written in express, the two or three times I researched it I couldn't find similar libraries as to the one's I rely on, and with the workarounds I have in express, I really have no reason to switch. So while I agree that in general, it actually is objectively better, it's not better enough in my mind to justify the switch.
The next personal project I have I'll probably look into it again, but for every professional project it just makes sense to continue cloning what I have that works.
1
u/colnarco Feb 21 '20
Yeah that sound nice with just attaching a status code and letting the error be forwarding to a shared error boundary which sends a response. I tried to do this but couldn’t make it work. I tend to keep my route handlers fairly simple so the one extra level of indentation doesn’t bother me too much.
Well sounds like it’s small developer ergonomics that really is the upper hand of Koa. If it’s as good as express but with a little extra niceness for promises I’ll probably give it a try next time I’m starting a new project.
1
u/blood_bender Feb 21 '20
I mean you can't even pronounce MKRN so why would anyone use it? 🙄
2
Aug 13 '23
Or they could go the route of Cassandra and say the M stands for MySQL-Compatible databases which includes Cassandra.
3
u/msg45f Feb 22 '20
Its amazing how entrenched people get about their choice among two options made by the same people
1
u/SocialAnxietyFighter Feb 22 '20
Extreme hyperbole! I've been using async await without hacks or any issues, I just wrap my route is a try catch
1
u/misdreavus79 Feb 22 '20
Likewise, it always amazes me that the JS community has embraced the “reinvent the wheel” mentality over improving what exists. Thus we end with several frameworks that all do effectively the same thing.
4
u/Funwithloops Feb 22 '20
How do you define "improving what exists"? Is forking with a different name really all that different than a major release with breaking changes?
Both of them piss off developers.
1
u/misdreavus79 Feb 23 '20
I draw the line in the sand at "[re]learning a framework." A lot of forks end up being completely different than what they forked form after a few iterations, while breaking changes, depending on the change, can be worked around.
I like how the React team handles breaking changes, by deprecating features well in advance of an upcoming breaking change, giving people the option of working on the deprecated feature or adopting the new change.
In the context of a team that doesn't have infinite time to learn every new framework that comes around, being able to stay within one framework for longer than a few years is really valuable. And, not to mention, you don't always need every single new feature in order to be productive. I reckon you rarely need every new feature to be productive.
7
u/30thnight Feb 21 '20
I wonder what thoughts on Fastify vs Koa vs Express look like
1
u/bompus1 Feb 24 '20
After using Express in a previous project, then testing various others, I'm in love with Fastify. It helps that the main maintainer is also on the Node.js dev team and specializes in performance.
0
Feb 22 '20
[deleted]
2
u/thepotatochronicles Feb 23 '20
I just don't like that it has zero support for express middlewares, even things like passport... yes, I know fastify-passport repo exists but it's WIP and very long way from being production-ready.
7
Feb 22 '20
Koa.js was made by the same guys that made express and agree is way better but I am still using express for now
4
u/nothingbutt Feb 22 '20 edited Feb 23 '20
I use Koa on a side projects and I ran into issues in three areas:
Piping binary content through a response (generated PDF created by an external process, got it working just was a bit complicated and way more examples for Express).
Using existing admin modules that plug into Express but are not easy or but possible to get working on Koa. Example is say Arena queue admin UI (**). Ended up spinning up a separate admin Express instance on another port as a quick workaround.
Not really Koa but made a choice on one of the router modules for it and got burned for a while (had to lock version) when that project changed their implantation breaking the way many had been hooking up routes. And that change was not on a major version bump :(.
I love async await and can't imagine not using it but some struggles like above can be annoying. And #1 actually had to be solved twice as there first method broke months/years later with some dependency upgrades (on the Koa/node side).
Also it felt like the Koa project kind of lost steam in the past. I'm not going to complain. I'm an open source maintainer too but I was worried I might have made the thing choice. But things seemed good last time I checked.
I was starting to get 'the grass is greener on the other side' for Express but reading these responses kind of makes me think it's not!
** Haven't checked in a while, maybe easier today. Would be nice to fix within the admin project although I'm switching to bull queue (from bee queue) and it's most popular queue admin tool so...
3
0
5
u/NelsonShepherd Feb 25 '20 edited Feb 25 '20
Why does this article keep saying Express doesn’t support async/await? And what on earth is an “async wrapper” ? I use async/await in Express all the time, on pretty much all of my routes, and never have to create any sort of wrapper. And for error handling async/await, what’s wrong with try/catch?