mbo's avatar
Level 3

Clear route from cookies

Good day,

Ik try to do the following:

  • upload image
  • crop image at the moment the image is called
  • cache the image with cloudflare The first two work. But cloudflare is not caching my images (bypass). I think this has to do with the fact that Laravel places cookies by passing my middleware.

What do i want to do: cleare my image routes from the middleware who places these cookies. The routes are placed in my "web" routes. Thereby my routes connected with 'web" are could by default. How can i overrule that for my image routes? Without breaking the app?

created middleware:

class RemoveCookieHeaders
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
                $response = $next($request);

        // Remove Set-Cookie headers
        $response->headers->remove('Set-Cookie');

        return $response;
    }
}

By using this middleware in my protected middleware like belowe it kills my app.

protected $middleware = [
       
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\RemoveCookieHeaders::class,
        
    ];

By putting it in a other group (like belowe) the middleware is not executed and the cookies are placed.

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
          
            
        ],

        'api' => [
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'WithoutCookie' => [
            \App\Http\Middleware\RemoveCookieHeaders::class,
        ],
    ];

Anyone a idea how to solve this?

0 likes
1 reply
LaryAI's avatar
Level 58

To solve the issue of Cloudflare not caching your images due to cookies being set by Laravel, you can create a custom middleware group specifically for your image routes that excludes any middleware that manipulates cookies. Here's how you can do it:

  1. Create the Middleware: It looks like you've already created a middleware RemoveCookieHeaders that removes the Set-Cookie headers. Ensure it's correctly implemented as shown in your question.

  2. Define a New Middleware Group: Instead of adding your RemoveCookieHeaders middleware to the global middleware stack or the web group, create a specific group for your image routes that does not include cookie or session handling middleware.

  3. Modify Kernel.php: In your app/Http/Kernel.php, define a new middleware group for your image routes. Here's how you can set it up:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'images' => [
        \App\Http\Middleware\RemoveCookieHeaders::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
  1. Apply the Middleware Group to Routes: In your routes file (typically web.php or a separate routes file if you prefer), apply this new middleware group to your image routes:
Route::group(['middleware' => ['images']], function () {
    Route::get('/image/{filename}', 'ImageController@show');
});
  1. Adjust Your Controller: Ensure your ImageController@show method handles the logic for serving images, potentially including any dynamic cropping or other manipulations before the response is sent.

  2. Test Your Setup: After implementing these changes, test your image routes to ensure that no cookies are being set and that Cloudflare can cache these responses.

This setup ensures that your image-serving routes are isolated from the default web middleware stack that includes cookie and session handling, thus allowing Cloudflare to cache the images as there are no cookies that would otherwise instruct Cloudflare to bypass caching.

Please or to participate in this conversation.