Workers with itty-router throws an error
Hello! I'm trying to use itty-router in a worker. However, an error is showing when I try to get a path.
This is my index.ts
Does anyone know why this might be happening?
9 Replies
My code is based on this one https://github.com/cloudflare/workers-sdk/blob/main/templates/worker-router/index.js
GitHub
workers-sdk/templates/worker-router/index.js at main · cloudflare/w...
⛅️ Home to Wrangler, the CLI for Cloudflare Workers® - cloudflare/workers-sdk
Thanks
Solved! It was my version of
itty-router
. Apparently it only works on ^3.0.12Hey @itaquito! Your issue lays in the fact that during v4, we phased in
router.fetch
to replace router.handle
(to perfectly match up with the export signature of Workers/Bun/etc). During v4, both worked... but with v5, we finally made the breaking change to fully deprecate router.handle
.
With v5, I'd recommend using AutoRouter
to further simplify your code! 🙂 Here's the conversion:
Migration Guides > v4 to v5 - itty-router - itty.dev
Ultra-small, powerful helpers for modern serverless APIs.
We need to add a troubleshooting guide on itty.dev, as this issue comes up often when someone follows an old guide online 🙂
it's the #1 issue by a long shot, so you're in good company! 😄
AutoRouter adds some powerful default effects (with overrides) to Router, namely:
- default json formatter for unformatted responses
- default error catching
- default 404 for missed routes
- adds the
before
and finally
middleware/handle stages to clean up global middleware and downstream effects without having to do a .then()
chain on the fetch call.Oh! Thanks for your reply!
I actually did try
AutoRouter
, but I only tried exporting it with export default router;
and it indeed showed an error.Yeah... Also, when you create an app with
npm create cloudflare@latest
and select Example router and proxy worker
, it just uses an old version of itty-router
. Thats why I thought it was the fix
But well.. Thanks again!
AutoRouter
does work if you export it that way!Oh good to know! I’ll see what it takes to get them to update that… maybe I can help!
There’s hope on the horizon for the wrangler bug… I saw a PR update on the issue today 🙂