Skip to Content
Module developmentModule basics

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.

app/Modules/Example/Controllers/PayoutController.php
<?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] argumentTypeDefaultWhat it does
uristringrequiredthe address, parameters in curly braces
methodsarray|string['GET']HTTP methods; the core adds HEAD to GET itself
name?stringnullthe route name; without it the name is route_<md5>
middlewarearray|string|nullnullroute middleware
wherearray[]parameter regular expressions: ['id' => '\d+']
defaultsarray[]default parameter values
withoutMiddlewarearray|string|nullnullremove 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.

NeedHow
a pageview('example::index', $data)
JSON$this->json($data, 200) or json($data)
a redirectredirect(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.

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:

app/Modules/Example/Controllers/PayoutApiController.php
<?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.

NeedHow
check the key's permission on a fixed addressmiddleware 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 tokenmiddleware api.auth and $this->requireAbility($request, 'example:read'); declare the token ability with api()->ability('example:read', 'Read payouts')
the answerApiResponse::ok($data, $meta); errors: ApiException::notFound(), featureDisabled(), badRequest(), validationFailed()
a write that never runs twiceadd idempotency to the middleware

Common mistakes

What you seeCause
the route is missing from route:listthe 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 modetwo 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} pagea 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 404the 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

Learn more

On this page