Skip to content

Skip CSP middleware when Vite is hot reloading #154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/AddCspHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
use Symfony\Component\HttpFoundation\Response;

class AddCspHeaders
Expand All @@ -19,8 +20,8 @@ public function handle(
return $response;
}

// Skip CSP middleware when Laravel is rendering an exception
if (config('app.debug') && $response->isServerError()) {
// Skip CSP middleware when Laravel is rendering an exception or Vite is hot reloading
if (config('app.debug') && ($response->isServerError() || Vite::isRunningHot())) {
return $response;
}

Expand Down
18 changes: 18 additions & 0 deletions tests/AddCspHeadersTest.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Vite;
use Illuminate\Support\Facades\Route;
use Mockery\MockInterface;
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertFalse;
use function PHPUnit\Framework\assertNull;
Expand Down Expand Up @@ -331,6 +333,22 @@ public function configure(Policy $policy): void
assertFalse($headers->has('content-security-policy'));
});

test('route middleware is skipped when vite is hot reloading', function (): void {
config(['app.debug' => true]);

$this->mock(Vite::class, function (MockInterface $mock): void {
$mock->shouldReceive('isRunningHot')->andReturn(true);
});

Route::get('other-route', function () {
return 'ok';
})->middleware(AddCspHeaders::class.':'.Basic::class);

$headers = getResponseHeaders('other-route');

assertFalse($headers->has('content-security-policy'));
});

it('will handle scheme values', function (): void {
$policy = new class implements Preset {
public function configure(Policy $policy): void
Expand Down