Skip to content

Routing

Here’s a @mapl/web API with a route that simply return Hi.

server.js
import { router, handle } from '@mapl/web';
import { compileToHandlerSync } from '@mapl/web/compiler/jit';
const app = router([], [
handle.get('/', () => new Response('Hi'))
]);
export default {
fetch: compileToHandlerSync(app)
};

Run the server with srvx CLI:

Terminal window
npx srvx --port=8080 server.js

Navigate to http://localhost:8080, you should see Hi as the result.

@mapl/web supports these patterns:

// From highest to lowest priority
'/static' // Static routes
'/user/*/dashboard' // Capture one path segment
'/search/**' // Capture all path segments after '/search'

Example usage:

const app = router([], [
handle.get(
'/',
() => new Response('Hi')
), // '/' => 'Hi'
handle.get(
'/user/*',
(id) => new Response('User: ' + id)
), // '/user/reve' => 'User: reve'
handle.get(
'/search/**',
(rest) => new Response('Search results for: ' + rest)
) // '/search/a/b' => 'Search results for: a/b'
]);

Response handler handles convert result type from route handler to a Response object.

const app = router([], [
handle.get('/', () => 'Hi', {
type: handle.text
}), // '/' => 'Hi'
]);

Built-in response handlers:

handle.text; // Accepts BodyInit
handle.json; // Accepts any type and serialize to JSON
handle.html; // Accepts BodyInit and automatically set HTML headers

Subroutes can be used to declare multiple routes with the same prefix.

const user = router([], [
handle.get('/profile', () => ...),
handle.get('/login', () => ...)
])
const app = router([], [
handle.get('/', () => ...)
], {
// register as /user/profile and /user/login
'/user': user
});