Core Concepts

Middleware

A guide to middleware in Raptor

Introduction

What is Middleware?

Middleware sits between the request and response of an HTTP server. The middleware function receives an incoming request, allowing you to inspect it, transform it and respond immediately (or skip to the next middleware in the stack). This particular design gives you absolute flexibility - you can build anything from simple micro-services to large complex applications.

Usage

Adding Middleware

To add a new middleware to the stack, all you have to do is add a callback function using the Kernel's use() method.

import { Kernel, type Context } from "@raptor/kernel";
 
const app = new Kernel();
 
app.use((_context: Context, _next: CallableFunction) => {
  return 'Hello, Dr Malcolm!';
});
 
app.serve();

Calling the Next Middleware

The next() middleware function is responsible for invoking the subsequent middleware in the stack. It must be called if the current middleware doesn't handle the request and provide a response; otherwise, the system will fail to respond successfully.

As an example of calling the next middleware, the following script demonstrates how to calculate runtime across two middleware:

app.use(async (_context: Context, next: CallableFunction) => {
  const start = Date.now();
 
  await next();
 
  const ms = Date.now() - start;
 
  console.log(`${ms}ms`);
});
 
app.use(async () => {
  await new Promise(resolve => setTimeout(resolve, 3000));
 
  return 'Hello, Dr Malcolm!';
});
 
// console: ~3004ms

Execution Order

Middleware are executed in the order they are added to the stack (Kernel).

Next Steps

For more information about Middleware, check out the Context documentation.

© 2026 Raptor