PHPackages                             amphp/http-server-router - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. amphp/http-server-router

ActiveLibrary[HTTP &amp; Networking](/categories/http)

amphp/http-server-router
========================

Routes to request handlers based on HTTP method and path for amphp/http-server.

v2.0.0(2y ago)39496.2k—5.8%6[1 issues](https://github.com/amphp/http-server-router/issues)20MITPHPPHP &gt;=8.1

Since Mar 26Pushed 1y ago7 watchersCompare

[ Source](https://github.com/amphp/http-server-router)[ Packagist](https://packagist.org/packages/amphp/http-server-router)[ Docs](https://github.com/amphp/http-server-router)[ GitHub Sponsors](https://github.com/amphp)[ RSS](/packages/amphp-http-server-router/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (8)Dependencies (14)Versions (12)Used By (20)

http-server-router
==================

[](#http-server-router)

AMPHP is a collection of event-driven libraries for PHP designed with fibers and concurrency in mind. This package provides a routing `RequestHandler` for [`amphp/http-server`](https://github.com/amphp/http-server) based on the request path and method using [FastRoute](https://github.com/nikic/FastRoute).

Installation
------------

[](#installation)

This package can be installed as a [Composer](https://getcomposer.org/) dependency. You should specify `amphp/http-server` as a separate dependency.

```
composer require amphp/http-server-router
```

Usage
-----

[](#usage)

**`Router`** implements `RequestHandler`, which is used by an [`HttpServer`](https://github.com/amphp/http-server#creating-an-http-server) to handle incoming requests. Incoming requests are routed by `Router` to other `RequestHandler`s based on the request path.

Routes can be defined using the `addRoute($method, $uri, $requestHandler)` method.

```
public function addRoute(
    string $method,
    string $uri,
    RequestHandler $requestHandler
): void
```

Matched route arguments are available in the request attributes under the `Amp\Http\Server\Router` key as an associative array. Please read the [FastRoute documentation on how to define placeholders](https://github.com/nikic/FastRoute#defining-routes).

### Middleware

[](#middleware)

You can stack all routes with a common set of middleware using `addMiddleware($middleware)`. Each middleware is called in the order of the `addMiddleware()` calls. The router will not invoke any middleware for the fallback handler.

```
public function addMiddleware(Middleware $middleware): void
```

> **Note**Per-route middleware can be added by using `Amp\Http\Server\Middleware\stackMiddleware()` before passing the `RequestHandler` to `addRoute()`.

### Fallback

[](#fallback)

If no routes match a request path, you can specify another instance of `RequestHandler` which will handle any unmatched routes. If no fallback handler is provided, a 404 response will be returned using the instance of `ErrorHandler` provided to the `Router` constructor.

```
public function setFallback(RequestHandler $requestHandler): void
```

> **Note**Middleware defined by `Router::addMiddleware()` will *not* be invoked when a request is forwarded to fallback handler. Use `Amp\Http\Server\Middleware\stackMiddleware()` to wrap the fallback request handler with any middlewares needed first.

Example
-------

[](#example)

```
use Amp\Http\HttpStatus;
use Amp\Http\Server\DefaultErrorHandler;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Router;
use Amp\Http\Server\SocketHttpServer;

// $logger is an instance of a PSR-3 logger.
$server = SocketHttpServer::createForDirectAccess($logger);
$errorHandler = new DefaultErrorHandler();

$router = new Router($server, $logger, $errorHandler);

$router->addRoute('GET', '/', new ClosureRequestHandler(
    function () {
        return new Response(
            status: HttpStatus::OK,
            headers: ['content-type' => 'text/plain'],
            body: 'Hello, world!',
        );
    },
));

$router->addRoute('GET', '/{name}', new ClosureRequestHandler(
    function (Request $request) {
        $args = $request->getAttribute(Router::class);
        return new Response(
            status: HttpStatus::OK,
            headers: ['content-type' => 'text/plain'],
            body: "Hello, {$args['name']}!",
        );
    },
));

$server->expose('0.0.0.0:1337');

$server->start($router, $errorHandler);

// Serve requests until SIGINT or SIGTERM is received by the process.
Amp\trapSignal([SIGINT, SIGTERM]);

$server->stop();
```

A full example is found in [`examples/hello-world.php`](https://github.com/amphp/http-server-router/blob/2.x/examples/hello-world.php).

```
php examples/hello-world.php
```

Limitations
-----------

[](#limitations)

The `Router` will decode the URI path before matching. This will also decode any forward slashes (`/`), which might result in unexpected matching for URIs with encoded slashes. FastRoute placeholders match path segments by default, which are separated by slashes. That means a route like `/token/{token}` won't match if the token contains an encoded slash. You can work around this limitation by using a custom regular expression for the placeholder like `/token/{token:.+}`.

Security
--------

[](#security)

If you discover any security related issues, please use the private security issue reporter instead of using the public issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [LICENSE](./LICENSE) for more information.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity48

Moderate usage in the ecosystem

Community31

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 50.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~230 days

Recently: every ~74 days

Total

10

Last Release

904d ago

Major Versions

1.x-dev → v2.0.0-beta.12022-04-08

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1628287?v=4)[Aaron Piotrowski](/maintainers/Trowski)[@trowski](https://github.com/trowski)

![](https://www.gravatar.com/avatar/12852217f3369e8144bc9ce6ac2a2341c28c5512c5b3df5749bfbbd45b6877ff?d=identicon)[kelunik](/maintainers/kelunik)

![](https://www.gravatar.com/avatar/f6db63ad594446f67d79532b75c69439fd0df779cc90868b43c187c02a4221ef?d=identicon)[bwoebi](/maintainers/bwoebi)

---

Top Contributors

[![trowski](https://avatars.githubusercontent.com/u/1628287?v=4)](https://github.com/trowski "trowski (33 commits)")[![kelunik](https://avatars.githubusercontent.com/u/2743004?v=4)](https://github.com/kelunik "kelunik (30 commits)")[![bosunski](https://avatars.githubusercontent.com/u/15146515?v=4)](https://github.com/bosunski "bosunski (1 commits)")[![thgs](https://avatars.githubusercontent.com/u/8940963?v=4)](https://github.com/thgs "thgs (1 commits)")

---

Tags

amphpfast-routehttpphprouterhttprouterserver

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/amphp-http-server-router/health.svg)

```
[![Health](https://phpackages.com/badges/amphp-http-server-router/health.svg)](https://phpackages.com/packages/amphp-http-server-router)
```

###  Alternatives

[amphp/http-server

A non-blocking HTTP application server for PHP based on Amp.

1.3k4.5M81](/packages/amphp-http-server)[danog/madelineproto

Async PHP client API for the telegram MTProto protocol.

3.4k855.0k18](/packages/danog-madelineproto)[amphp/websocket-server

Websocket server for Amp's HTTP server.

124265.1k20](/packages/amphp-websocket-server)[amphp/http-client

An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.

7296.8M137](/packages/amphp-http-client)[middlewares/fast-route

Middleware to use FastRoute

96191.1k15](/packages/middlewares-fast-route)[amphp/http-server-static-content

Static content request handler for Amp's HTTP server.

2167.2k12](/packages/amphp-http-server-static-content)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
