#Workers with itty-router throws an error

14 messages · Page 1 of 1 (latest)

rigid star
#

Hello! I'm trying to use itty-router in a worker. However, an error is showing when I try to get a path.

X [ERROR] A hanging Promise was canceled. This happens when the worker runtime is waiting for a Promise from JavaScript to resolve, but has detected that the Promise cannot possibly ever resolve because all code and events related to the Promise's I/O context have already finished.


X [ERROR] Uncaught (in response) Error: The script will never generate a response.

This is my index.ts

import { Router } from 'itty-router';

const router = Router();

router.get('/', () => {
    return new Response('Hello, world!');
});

router.all('*', () => new Response('404, not found!', { status: 404 }));

export default {
    fetch: router.handle,
};

Does anyone know why this might be happening?

#

Thanks

rigid star
#

Solved! It was my version of itty-router. Apparently it only works on ^3.0.12

astral field
#

Hey @rigid star! 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:

import { AutoRouter } from 'itty-router';

const router = AutoRouter();

router.get('/', () => 'Hello, world!'); // this will turn into a Request

// 404 is automatically handled by AutoRouter

// this is all you need with v5
export default router;

// wrangler currently has a bug requiring this in local dev though...
export default { ...router }
#

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.
rigid star
#

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.

rigid star
#

But well.. Thanks again! AutoRouter does work if you export it that way!

astral field
#

Oh good to know! I’ll see what it takes to get them to update that… maybe I can help!