Middleware

Middleware functions allow you to run code before and after your route handlers. GraceJS supports both before-route and after-route middleware.

Before-Route Middleware

Before-route middleware can perform tasks such as authentication, request logging, and setting common headers.

import { createBeforeRoute } from '@grace-js/grace';

const authenticate = createBeforeRoute(async (context) => {
  // Perform authentication
  if (!context.headers.authorization) {
    throw new Error('Unauthorized');
  }
});

export default authenticate;

After-Route Middleware

Similarly, after-route middleware is useful for tasks like logging responses or setting response headers.

import { createAfterRoute } from '@grace-js/grace';

const logResponse = createAfterRoute(async (context, response) => {
  console.log(response);
});

export default logResponse;

Last updated