Module routes, middleware and API
How a module declares pages and actions with #[Route], which middleware the core has, how CSRF works and how a module adds its own endpoints to the REST API.
By the end your module has its own pages, a POST action protected against CSRF, and an endpoint under the /api/v1 REST API that a key with the right permission can call.
Minimal example
Routes are an attribute on a controller method. An attribute on the class sets a shared prefix for the address and the name.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Controllers;
use Flute\Core\Router\Annotations\Route;
use Flute\Core\Support\BaseController;
use Flute\Modules\Example\Services\Payouts;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;
#[Route(uri: '/example', name: 'example.')]
final class PayoutController extends BaseController
{
public function __construct(
private readonly Payouts $payouts,
) {
}
#[Route(uri: '/', methods: ['GET'], name: 'index')]
public function index(): View
{
return view('example::index', ['top' => $this->payouts->top(10)]);
}
#[Route(uri: '/claim', methods: ['POST'], name: 'claim', middleware: ['auth', 'throttle:user,5,60'])]
public function claim(): Response
{
$this->payouts->pay(user()->getCurrentUser(), 100);
$this->toast(__('example.claimed'), 'success');
return redirect(route('example.index'));
}
}This gives GET /example named example.index and POST /example/claim named example.claim. Names are joined as raw strings, so put the dot in the class attribute. Build links by name: route('example.claim').
Send the token in a form: <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">. htmx requests send the X-CSRF-Token header on their own: the standard theme puts it in hx-headers on <body> and reads a fresh token from meta[name="csrf-token"], and the core's flute-ui.js adds it to requests to /wire. From your own fetch() send the same header. How htmx and wire work in a module is covered in Live filters and forms without a reload.
How the core finds routes
bootstrapModule() calls loadRouterAttributes(), which scans the module's Controllers/ or Http/Controllers/ and Submodules/*/Controllers. The namespace has to match the path: Flute\Modules\Example\Controllers. Only public non-static methods are registered; a static method with #[Route] is skipped silently.
The route list is cached by a fingerprint of the controller files: a new or edited #[Route] is picked up without cache:clear, within 30 seconds outside debug mode. To check that a route exists, run php flute route:list or php flute route:detail /example/claim. Admin routes are not in that list.
The container builds the controller and the action arguments, so pass services through the constructor or method arguments. Path parameters such as {id} arrive in arguments of the same name. A GET handler changes nothing: in performance mode anonymous GET responses come from the page cache, and the handler may not run at all.
#[Route] argument | Type | Default | What it does |
|---|---|---|---|
uri | string | required | the address, parameters in curly braces |
methods | array|string | ['GET'] | HTTP methods; the core adds HEAD to GET itself |
name | ?string | null | the route name; without it the name is route_<md5> |
middleware | array|string|null | null | route middleware |
where | array | [] | parameter regular expressions: ['id' => '\d+'] |
defaults | array | [] | default parameter values |
withoutMiddleware | array|string|null | null | remove middleware, including one the core added |
There are short forms #[Get], #[Post], #[Put] and #[Delete] with the same arguments except methods, plus #[Middleware([...])] on a class or method. The #[RateLimit] attribute does nothing; limits come from throttle.
Responses
An action returns a Response, a string or a Blade View: a view goes out as text/html with status 200. Anything else ends in an InvalidArgumentException with Controller action must return a response or string.
| Need | How |
|---|---|
| a page | view('example::index', $data) |
| JSON | $this->json($data, 200) or json($data) |
| a redirect | redirect(route('example.index')) |
| an error | $this->error($message, 403): JSON for AJAX, the theme's error page otherwise; or response()->error(404, __('def.page_not_found')) |
| a notice after an action | $this->toast($message, 'success') |
Core middleware
The core adds the default group to every route: request.id, htmx.shell, prefetch.readonly, maintenance, throttle, ban.check. A route with POST, PUT, PATCH or DELETE also gets csrf at the front of the list. The exceptions: the route already has csrf or token, or it is an api/v1/* or oauth/* address without auth.
| Name | What it does |
|---|---|
auth | signed-in users only |
guest | guests only |
can:a,b | requires every listed permission |
can.any:a,b | requires at least one permission |
csrf | token check on unsafe methods |
elevated | a recent password confirmation; elevated:moderation,<parameter> for moderating another account |
throttle:by,limit,seconds | rate limit; by is ip, user, ip_user or bearer. A route's own throttle: replaces the one from the group |
htmx | htmx requests only |
htmx.shell | an htmx move between the site and the admin panel gets a full page load |
prefetch.readonly | a hover prefetch runs in a transaction that is rolled back |
request.id | the X-Request-Id header, also written to the logs |
ban.check | keeps blocked accounts out; ban.check:sign-in for signing in to an existing account |
maintenance | closes the site during maintenance |
site_mode | the site access mode |
page.permissions | per-page permissions |
token | an API key |
scope:resource,read | the key's permission on a resource |
api.auth | a user's personal token |
idempotency | a repeat with the same Idempotency-Key gets the first response |
link, link.sign | a request from a game-server plugin and the signature of the reply to it |
The class implements Flute\Core\Router\Contracts\MiddlewareInterface:
public function handle(FluteRequest $request, Closure $next, mixed ...$args): ResponseRegister a name in boot(): router()->aliasMiddleware('example.vip', VipMiddleware::class). Parameters after the colon arrive in $args. A class without that interface throws InvalidArgumentException on the first request. Middleware does not write to the database or change the session on GET.
When the CSRF check fails, the answer is 403 with "Your token has expired. Refresh the page". An address another server calls (a payment provider's webhook) drops the check with withoutMiddleware: ['csrf']. The core's payment gateway notification addresses are built this way.
Module REST API
How external clients get a key and call the API is covered in API keys and REST API. A module picks one of two paths.
For listing and editing records you need no controller. Describe a resource that extends Flute\Core\Api\Resource\AbstractEntityResource (there is an example in the API reference) and register it in boot(): api()->resource(new PayoutResource()). You get /api/v1/payouts and /api/v1/payouts/{id}, and the key's permission table gains payouts:read and payouts:write rows. Nobody adds those by hand: ScopeRegistry builds them from the registered resources, and write includes read. The Achievements and Discord modules register their resources this way.
For an endpoint outside listing and editing, the controller extends ApiController:
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Controllers;
use Flute\Core\Api\Envelope\ApiResponse;
use Flute\Core\Api\Http\Controllers\ApiController;
use Flute\Core\Router\Annotations\Route;
use Flute\Modules\Example\Services\Payouts;
use Symfony\Component\HttpFoundation\Response;
final class PayoutApiController extends ApiController
{
public function __construct(
private readonly Payouts $payouts,
) {
}
#[Route(
uri: '/api/v1/example/payouts/top',
methods: ['GET'],
name: 'api.v1.example.payouts.top',
middleware: ['token', 'scope:payouts,read', 'throttle:ip,60,60'],
)]
public function top(): Response
{
return $this->respond(fn(): ApiResponse => ApiResponse::ok($this->payouts->top(10)));
}
}respond() turns an ApiException into a {data, meta, errors} answer with the right status, and any other exception into server_error with no details. The resource named in scope: has to be registered, or no key can ever hold that permission. The GiveCore module's endpoint for privilege holders is built this way.
| Need | How |
|---|---|
| check the key's permission on a fixed address | middleware token plus scope:resource,read or scope:resource,write |
| check the permission when the resource is a path segment | $this->requireScope($request, $name, ScopeRegistry::READ) |
| a request on behalf of a user with their token | middleware api.auth and $this->requireAbility($request, 'example:read'); declare the token ability with api()->ability('example:read', 'Read payouts') |
| the answer | ApiResponse::ok($data, $meta); errors: ApiException::notFound(), featureDisabled(), badRequest(), validationFailed() |
| a write that never runs twice | add idempotency to the middleware |
Common mistakes
| What you see | Cause |
|---|---|
the route is missing from route:list | the method is static or not public, the namespace does not match the path, or the folder is not Controllers |
| 403 "Your token has expired. Refresh the page" | a POST without _csrf_token or the X-CSRF-Token header |
a LogicException about clashing route names in debug mode | two routes share one name; outside debug the error goes to the router log and one route overwrites the other |
a module address answers with the /{slug} page | a one-segment route overlaps the generic one; registration order decides, routes have no priority |
| the API answers 404 on a two-segment address | /api/v1/example/top matches the generic /api/v1/{resource}/{id}; use three segments or more |
a resource named config, resources, auth, docs, openapi.json or webhooks answers 404 | the core reserves these names |
This key is missing the required scope 'payouts:read'. | the key lacks the permission, or the payouts resource is not registered |