Middleware

Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.

Use Cases

Integrating Middleware into your application can lead to significant improvements in performance, security, and user experience. Some common scenarios where Middleware is particularly effective include:

  • Authentication - Middleware can be used to verify user credentials before granting access to protected routes.
  • Authorization - Middleware can be used to check user roles and permissions before allowing access to specific resources.
  • Logging - Middleware can be used to log requests, responses, and errors for debugging and monitoring purposes.
  • Server-Side Redirects: Redirect users at the server level based on certain conditions (e.g., locale, user role).
  • Caching - Middleware can be used to cache responses to improve performance and reduce server load.
  • Rate Limiting - Middleware can be used to limit the number of requests from a single IP address to prevent abuse.
  • Compression - Middleware can be used to compress responses to reduce bandwidth usage and improve load times.

Recognizing situations where middleware may not be the optimal approach is just as crucial. Here are some scenarios to be mindful of:

  • Heavy Processing - Avoid performing resource-intensive operations in middleware to prevent bottlenecks.
  • Blocking - Be cautious of middleware that blocks requests or responses, as this can lead to performance issues.
  • Over-Engineering - Keep middleware simple and focused on specific tasks to avoid unnecessary complexity.
  • Security Risks - Be mindful of potential security vulnerabilities introduced by middleware, such as injection attacks.
  • Direct Database Operations: Performing direct database operations within Middleware is not recommended. Database interactions should done within Route Handlers or server-side utilities.

Convention

Prisma PHP follows a convention-based approach to Middleware, where each Middleware is defined as a class with a specific structure. Middleware classes should be stored in the Lib/Middleware directory and registered in the bootstrap.php file located in the root directory of your project.

Here is an example of how to register Middleware in the bootstrap.php file:

<?php

  use Lib\Middleware\AuthMiddleware;

  function determineContentToInclude()
  {
      /** 
       * ============ URI Handling ============ 
       * The $requestUri variable now contains the full URI including query parameters. 
       * Examples: 
       * - Home page: '/' 
       * - Dynamic routes with parameters (e.g., '/dashboard?v=2' or '/profile?id=5') 
       * ======================================
       */
      $requestUri = $_SERVER['REQUEST_URI'];
      $requestUri = empty($_SERVER['SCRIPT_URL']) ? uriExtractor($requestUri) : $requestUri;
      /** 
       * ============ URI Path Handling ============ 
       * The $uri variable now contains the URI path without query parameters and without the leading slash. 
       * Examples: 
       * - Home page: '' (empty string) 
     * - Dynamic routes (e.g., '/dashboard?v=2' or '/profile?id=5') -> Only the path part is returned (e.g., 'dashboard' or   'profile'), without the query parameters. 
       * ============================================
       */
      $scriptUrl = explode('?', $requestUri, 2)[0];
      $pathname = $_SERVER['SCRIPT_URL'] ?? $scriptUrl;
      $pathname = ltrim($pathname, '/');
      $baseDir = APP_PATH;
      $includePath = '';
      $layoutsToInclude = [];
  
      /** 
       * ============ Middleware Management ============
       * AuthMiddleware is invoked to handle authentication logic for the current route ($pathname).
       * ================================================
       */
      AuthMiddleware::handle($pathname);
      // Place your custom middleware here
      /** 
       * ============ End of Middleware Management ======
       * ================================================
       */
  }
  
  ?>