Working with (lazy) cors and group routes

Hi !

I following the documentation here https://www.slimframework.com/docs/v3/cookbook/enable-cors.html and all works.

The problem is, I use the same $app for front, back and api routes. I enable lazy cors inside a ->group function
(for api) but all routes have the new access control I set in the group. Front and back etc.

Any idea…?

The code looks like

/** Enable cors */
$app->options('/{routes:.+}', function ($request, $response, $args) {
     return $response;
});

$app->group('/api/v1', function () use ($app) {

    $this->get('/js/{public_key}', AssetsController::class.':getModuleJavascript');

    $this->group('', function () use ($app) {
    
        /** Enable cors */
        $this->add(function ($request, $response, $next) {
            $response = $next($request, $response);
            return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'pkey')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST');
        });
    
        $this->get('/form/{tokenform}', ApiController::class.':getFormDatas');
        $this->post('/consent', ApiController::class.':addConsent');
    });
    
})->add(new ApiMiddleware());

ps : If I putt the ->add method enabling lazy cors into group like that ->group()->add() the lazy cors don’t work anymore…

Thx a lot

In this special case, the CORS middleware could be added into the route group and could also check the requested path for its responsibility.

Example

CORS middleware for all routes below api/*:

use Slim\Http\Request;
use Slim\Http\Response;

$app->add(function (Request $request, Response $response, $next) {
    // Handle only OPTIONS requests
    if ($request->getMethod() !== 'OPTIONS') {
        return $next($request, $response);
    }

    // Must be a api/* route
    $urlPath = $request->getUri()->getPath();

    if ($urlPath !== '/api' && strpos($urlPath, '/api/') !== 0) {
        return $next($request, $response);
    }

    $response = $next($request, $response);
    $response = $response->withHeader('Access-Control-Allow-Origin', '*');
    $response = $response->withHeader('Access-Control-Allow-Methods', $request->getHeaderLine('Access-Control-Request-Method'));
    $response = $response->withHeader('Access-Control-Allow-Headers', $request->getHeaderLine('Access-Control-Request-Headers'));

    return $response;
}