Nitro

Going further

Extending Nitro

Nitro has four ways for you to add to it: your own nitro: attributes, plugins in the browser, features that run around every component on the server, and attributes that work as features.

On this page

Each one is small on its own. Use your own attributes for behaviour in the page, such as a tooltip or a textarea that grows. Use plugins to listen to the runtime in the browser. Use features and attribute classes to run code around your components on the server.

Adding your own attributes

A nitro: attribute of your own takes two steps. First, list its name in config/nitro.php, so the compiler accepts it:

PHP
// config/nitro.php
'attributes' => ['autosize'],

Then register a directive with the same name in your JavaScript. The directive receives the element, the attribute's value and its modifiers, and it can return a function that cleans up:

resources/js/autosize.js
/**
 * nitro:autosize: a textarea that grows with its text. Its value is the most lines it grows to,
 * nitro:autosize="8"; past that, it scrolls.
 *
 * This file loads before Nitro does, so it registers the directive at nitro:init, before any component starts.
 */
document.addEventListener('nitro:init', ({ detail: { Nitro } }) => {
    Nitro.directive('autosize', ({ el, value }) => {
        const style = getComputedStyle(el);
        const line = parseFloat(style.lineHeight) || 20;
        const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
        const max = (Number(value) || Infinity) * line + padding;

        const fit = () => {
            el.style.height = 'auto';
            el.style.height = `${Math.min(el.scrollHeight, max)}px`;
            el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden';
        };

        fit();
        el.addEventListener('input', fit);

        return () => el.removeEventListener('input', fit);
    });
});
Blade
<textarea nitro:model="reply" nitro:autosize="8"></textarea>
nitro:autosize live, in this page View source ↓

280 characters left

Type a few lines into the box. It grows with your text, up to eight lines, and then it scrolls.

  • When it runs. The directive runs when its element appears. It runs again when the attribute's value or modifiers change, and not on other renders. The value is rendered like any attribute, so it can contain {{ }}.
  • What it receives. el is the element, value is the attribute's value as a string, and modifiers is a list of the words after its name, such as .top in nitro:tooltip.top. To pass data, use @json(...) in the value.
  • Cleaning up. The function the directive returns runs before the directive runs again, and when the element or its component leaves the page.
  • Mistakes are caught. A nitro: attribute that isn't listed fails the build. You can't list a name Nitro uses itself, such as click or model.

Registering a directive

A script that runs after @nitroScripts can call Nitro.directive() directly. A script that runs before it, such as a Vite module in the page's <head>, should register in a nitro:init listener, as the example above does. Nitro fires that event on document just before any component starts. A directive you register later still runs on the elements already on the page.

Talking to the component

A directive also receives component, by your property and method names: get() and set() a property, watch() it, call() a method, or dispatch() an event, as $this->dispatch() does, for any #[On] method to hear. Third-party libraries binds a library's value with them; here, an event:

JavaScript
Nitro.directive('sortable', ({ el, component }) => {
    const list = makeSortable(el, {
        onEnd: (ids) => component.dispatch('reordered', ids),
    });

    return () => list.destroy();
});
PHP Browser
#[On('reordered')]
public function reorder(array $ids): void
{
    $this->order = $ids;
}

Writing plugins

A plugin packages what you add to the runtime in the browser: listeners and your own attributes, used as one. Pass a function to Nitro.use(), and Nitro calls it once with the plugin API: on(), which is Nitro.hook(), and directive(), which is Nitro.directive().

JavaScript
Nitro.use(({ on }) => {
    on('beforeRequest', ({ headers }) => {
        headers['X-Tenant'] = document.body.dataset.tenant;
    });

    on('afterRequest', ({ method, status }) => {
        if (status >= 500) reportToMonitoring(method, status);
    });
});

A plugin listens to the same moments as any code on the page: Hooks lists them, with what each gives you.

  • Removing a listener. on() returns a function that removes the listener.
  • Late plugins catch up. A component.initialized or store.initialized listener also hears the components and stores already on the page.
  • Headers. A beforeRequest listener can add headers, but it can't change Nitro's own, such as the CSRF token.
  • Errors are contained. A listener that throws is reported through the error hook, and the other listeners still run.
  • Once. A plugin used twice runs once.
  • Earlier names. The names plugins used before hooks, component, render, store, request and response, still work.

Nitro uses this API too

#[Persist] and #[Sync], which keep a store's state and share it between tabs, are plugins built only on this API.

Running code around every component

A feature runs on the server, around every component. Use one for things a single component's hooks can't do, such as auditing every #[Server] call or setting a tenant on every component. Extend Nitro\Feature and override the hooks you need:

app/Nitro/Features/AuditCalls.php Server
namespace App\Nitro\Features;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Nitro\Component;
use Nitro\Feature;

class AuditCalls extends Feature
{
    public function __construct(private readonly Request $request) {}

    public function called(Component $component, string $method, mixed $result): void
    {
        Log::info('Nitro call', [
            'component' => $component::class,
            'method' => $method,
            'user' => $this->request->user()?->id,
        ]);
    }
}

Then list it in config/nitro.php:

PHP
// config/nitro.php
'features' => [App\Nitro\Features\AuditCalls::class],
Hook Runs
boot($component) On every request, when the component is created or restored
mounting($component) For a new component, before mount()
hydrate($component) On a #[Server] call, once the state is restored
updated($component, $changed) On a #[Server] call, once the browser's changes are set. Return false to stop the method from running
calling($component, $method, $arguments) Before a #[Server] method runs
call($component, $method, $arguments, $run) Around a #[Server] method: $run() runs it. Return what it gave, something else, or answer without calling $run()
called($component, $method, $result) After a #[Server] method returns, with the answer
exception($component, $method, $exception) A #[Server] method threw and the component's own exception() didn't handle it. Return true when you handled it
dehydrate($component) Before the state is sent to the browser, once per request
  • Order. Each hook runs after the component's own method of the same name, such as boot(). Your features run after Nitro's own, so updated() can see what #[Validate] found in $component->nitro()->errors.
  • Services. The container makes each feature once per request, so its constructor can take services.
  • Stores run features too, since a store is a component.
  • Stopping a method. Every feature's updated() runs, even after one returns false. An error a feature adds to $component->nitro()->errors reaches the browser like a validation message.

Around a method

call() wraps every #[Server] method, the way middleware wraps a request. Calling $run() runs the method and gives you what it returned, so you can put a transaction, a lock or a timer around it. Returning a value without calling $run() answers in the method's place, which suits a cache or a feature switch.

PHP
namespace App\Nitro\Features;

use Closure;
use Illuminate\Support\Facades\DB;
use Nitro\Component;
use Nitro\Feature;

class InTransaction extends Feature
{
    /** Every #[Server] method in a database transaction: if it throws, what it wrote is rolled back. */
    public function call(Component $component, string $method, array $arguments, Closure $run): mixed
    {
        return DB::transaction($run);
    }
}
  • Nesting. The first feature listed in config/nitro.php is the outermost. The method itself, and #[Cached], which may answer for it, are innermost.
  • The answer. Whatever call() returns is what the browser gets, and what called() hears.

When a method throws

A component can handle its own errors with an exception() method. A feature's exception() handles the rest across the app: it runs when the component has none, or when the component's own throws again. Report the error, set a message, and return true to say it's handled; the call then answers with the state as it is. The first feature to return true ends it. When none does, the error goes on as it would without features: an error page, or the component's fallback.

Writing attributes that work as features

A feature can also be an attribute that runs only where you place it. Extend Nitro\FeatureAttribute, and $this->target() tells you the property or method it's on:

app/Nitro/Attributes/Throttle.php Server
namespace App\Nitro\Attributes;

use Attribute;
use Illuminate\Support\Facades\RateLimiter;
use Nitro\Component;
use Nitro\FeatureAttribute;

#[Attribute(Attribute::TARGET_METHOD)]
class Throttle extends FeatureAttribute
{
    public function __construct(public int $perMinute = 10) {}

    public function calling(Component $component, string $method, array $arguments): void
    {
        $key = 'nitro:'.$component::class.':'.$method.':'.request()->ip();

        abort_if(RateLimiter::tooManyAttempts($key, $this->perMinute), 429);

        RateLimiter::hit($key);
    }
}
app/Nitro/Components/Contact.php Server
use App\Nitro\Attributes\Throttle;

#[Server]
#[Throttle(perMinute: 3)]
public function send(): void
{
    Mail::to($this->email)->send(new ContactMessage($this->message));
}
Placed on Its hooks
A #[Server] method calling() and called() run for that method only
A property updated() runs only when the browser changed that property
The class Every hook runs
  • Browser methods are refused. A browser method never reaches the server, so an attribute class on one fails the build.
  • Order. Attribute classes run after the component's own hooks, and before #[Validate] and the features in config/nitro.php. So a property's updated() can tidy a value before it's validated.
  • One per component. Each component gets its own instance, made from the attribute's arguments rather than by the container.

Nitro's #[Url] is one

#[Url] is itself an attribute class: its mounting() hook reads the property's value from the query string.

Next steps