Skip to content

Routing

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

server.js
import { router, route, send } from '@mapl/web';
import { compiler } from '@mapl/web/generic';
const app = router([], [
route.get('/', send.raw(() => 'Hi'))
]);
export default {
fetch: compiler.buildSync(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([], [
route.get(
'/',
send.raw(() => 'Hi')
), // '/' => 'Hi'
handle.get(
'/user/*',
send.raw((id) => 'User: ' + id)
), // '/user/reve' => 'User: reve'
handle.get(
'/search/**',
send.raw((rest) => 'Search results for: ' + rest)
) // '/search/a/b' => 'Search results for: a/b'
]);

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

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