Middleware

Middleware

Middlewares are a collection of asynchronous functions that have access to the context object and can modify it before the request in handled. Middleware can be used for various tasks such as logging, or authentication.

Creating a logging middleware

In order to demonstrate how middlewares work, lets start with the Aetheris server we created in the quick start guide.

src/server/index.ts
import { createAetheris, router } from "@aetheris/server";
 
const aether = createAetheris();
 
export const app = router({
    helloWorld: aether.handler({
        resolve: async () => {
            return "Hello, World!";
        },
    }),
});
 
export type App = typeof app;

Here we have a basic hello world Aetheris server. Let's expand on this by adding a middleware that adds a logger to the context object. In this example we will be using pino (opens in a new tab).

src/server/index.ts
import { createAetheris, router } from "@aetheris/server";
import pino from "pino"
 
const aether = createAetheris();
 
const logger = pino();
 
const withLogger = aether.use(() => {
    return {
        logger,
    };
});
 
export const app = router({
    helloWorld: withLogger.handler({
        resolve: async ({ logger }) => {
            logger.info("helloWorld was called.");
            return "Hello, World!";
        },
    }),
});
 
export type App = typeof app;

Now any handler created from withLogger will have access to the logger property in the context object. Additional middleware can access the context provided from previous middleware, allowing you to chain middleware together.

src/server/index.ts
import { createAetheris, router } from "@aetheris/server";
import pino from "pino"
 
const aether = createAetheris();
 
const logger = pino();
 
const withLogger = aether
    .use(() => {
        return {
            logger,
        };
    })
    // In order for context to be inferred, we have to chain the middleware together.
    .use(({ logger, path }) => {
        logger.info(`${path}`)
    });
 
export const app = router({
    helloWorld: withLogger.handler({
        resolve: async ({ logger }) => {
            return "Hello, World!";
        },
    }),
});
 
export type App = typeof app;