Search code examples
laravelresponse-headers

"Best" way to inject a Livewire component into the response with Laravel middleware


I want to add a Livewire component to every request using middleware rather than having to manually add the component. I've done a bit of research and have looked at Spatie's Laravel cookie consent package, which accomplishes something very similar. To determine that they add their component to the right request (like not JSON, file download, XML, or other requests), they look for a closing </body> tag. Would it be just as "good" (accurate, in line with best practices, etc.) to instead check the response header Content-Type for text/html + that it isn't a redirect using the isRedirection() method? For example, rather than Spatie's containsBodyTag() function, this:

protected function isHtml(Response $response): bool
{
    return str_contains($response->headers->get('Content-Type'), 'text/html') && ! $response->isRedirection();
}

Solution

  • Both approaches may have trade-offs depending on your app's particular details.

    Spatie's approach of checking for a body tag will avoid messing with HTML partials your app might return; HTML intended to be swapped-out for a particular div in your existing page, for example. Many apps don't do this at all, so the answer is to some extent "it depends".