Skip to content

Middlewares

Darshan edited this page May 22, 2024 · 2 revisions

There are basically 2 ways to manage middleware, legacy and modern.


Legacy mode only allowed intercepting the incoming request and send/manage a response from there and then, see below -

  1. Direct:

    appExpress.middleware((request, response, log) => {
      log('Requested Path:', request.path);
    });
  2. Using variable:

    // middlewares/analytics.js
    export const analyticsMiddleware = (request, response, log, error) => {
      // Implement analytics logic here
      try {
          analyticsSingleton.log('path', request.path);
          log(`logged a ${request.path} to analytics!`);
      } catch (err) {
          error(`Error logging to analytics: ${err.message}`);
      }
    };
    
    // index.js
    import analytics from './middlewares/analytics.js';
    appExpress.middleware(analytics);
  3. Exiting the Middleware chain:

    appExpress.middleware((request, response, log) => {
      const { userJwtToken } = request.body;
      const isConsole = request.path.includes('/console');
    
      if (isConsole && !userJwtToken) {
          throw Error('No JWT Token found, aborting the requests.');
      }
    });

Note: Middlewares are processed in the order they are added.


Modern mode allows you to intercept the incoming request as well as the final processed response, see below -

appExpress.middleware({
  incoming: (request, response, log, error) => {},
  outgoing: (request, interceptor, log, error) => {
    // interceptor includes processed
    // `body`, headers, and statusCode which you can modify!
  }
});

Depending on your use-case, you can use either extend incoming, or outgoing or both.


Note: Legacy and modern mode are both compatible with the latest version of AppExpress!

Clone this wiki locally