Itty is arguably the smallest (~450 bytes) feature-rich JavaScript router available, while enabling dead-simple API code.
Designed originally for Cloudflare Workers, itty can be used in browsers, service workers, edge functions, or runtimes like Node, Bun, etc.!
Features
Complete API documentation is available at itty.dev/itty-router, or join our Discord channel to chat with community members for quick help!
Installation
npm install itty-router
Example
import {
error,
json,
Router,
withParams,
} from 'itty-router'
import { todos } from './external/todos'
const router = Router()
router
.all('*', withParams)
.get('/todos', () => todos)
.get(
'/todos/:id',
({ id }) => todos.getById(id) || error(404, 'That todo was not found')
)
.all('*', () => error(404))
export default {
fetch: (request, ...args) =>
router
.handle(request, ...args)
.then(json)
.catch(error),
}
What's different about itty?
Itty does a few things very differently from other routers. This allows itty route code to be shorter and more intuitive than most!
1. Simpler handler/middleware flow.
In itty, you simply return (anything) to exit the flow. If any handler ever returns a thing, that's what the router.handle
returns. If it doesn't, it's considered middleware, and the next handler is called.
That's it!
(request) => [1, 4, 5, 1]
const withUser = (request) => {
request.user = 'Halsey'
}
const onlyHalsey = (request) => {
if (request.user !== 'Halsey') {
return error(403, 'Only Halsey is allowed to see this!')
}
}
route.get('/secure', withUser, onlyHalsey,
({ user }) => `Hey, ${user} - welcome back!`
)
2. You don't have to build a response in each route handler.
We've been stuck in this pattern for over a decade. Almost every router still expects you to build and return a Response... in every single route.
We think you should be able to do that once, at the end. In most modern APIs for instance, we're serving JSON in the majority of our routes. So why handle that more than once?
router
.get('/traditional', (request) => json([1, 2, 3]))
.get('/easy-mode', (request) => [1, 2, 3])
router
.handle(request)
.then(json)
3. It's all Promises.
itty await
s every handler, looking for a return value. If it gets one, it breaks the flow and returns the value. If it doesn't, it continues processing handlers/routes until it does. This means that every handler can either be synchronous or async - it's all the same.
When paired with the fact that we can simply return raw data and transform it later, this is AWESOME for working with async APIs, database layers, etc. We don't need to transform anything at the route, we can simply return the Promise (to data) itself!
Check this out:
import { myDatabase } from './somewhere'
router
.get('/items', () => myDatabase.getItems())
router
.handle(request)
.then(json)
4. Only one required argument. The rest is up to you.
itty only requires one argument - a Request-like object with the following shape: { url, method }
(usually a native Request). Because itty is not opinionated about Response creation, there is not "response" argument built in. Every other argument you pass to route.handle
is given to each handler, in the same order.
This makes itty one of the most platform-agnostic routers, period, as it's able to match up to any platform's signature.
Here's an example using Cloudflare Worker arguments:
router
.get('/my-route', (request, environment, context) => {
})
export default {
fetch: (request, env, ctx) => router
.handle(request, env, ctx)
.then(json)
.catch(error)
}
Join the Discussion!
Have a question? Suggestion? Complaint? Want to send a gift basket?
Join us on Discord!
Testing and Contributing
- Fork repo
- Install dev dependencies via
yarn
- Start test runner/dev mode
yarn dev
- Add your code and tests if needed - do NOT remove/alter existing tests
- Commit files
- Submit PR (and fill out the template)
- I'll add you to the credits! :)
Special Thanks: Contributors
These folks are the real heroes, making open source the powerhouse that it is! Help out and get your name added to this list! <3
Core Concepts
- @mvasigh - proxy hack wizard behind itty, coding partner in crime, maker of the entire doc site, etc, etc.
- @hunterloftis - router.handle() method now accepts extra arguments and passed them to route functions
- @SupremeTechnopriest - improved TypeScript support and documentation! :D
Code Golfing
- @taralx - router internal code-golfing refactor for performance and character savings
- @DrLoopFall - v4.x re-minification
Fixes & Build
- @taralx - QOL fixes for contributing (dev dep fix and test file consistency) <3
- @technoyes - three kind-of-a-big-deal errors fixed. Imagine the look on my face... thanks man!! :)
- @roojay520 - TS interface fixes
- @jahands - v4.x TS fixes
Documentation