Skip to content

Custom APIs

Middleware

When you use DEFINE API, the THEN block is the handler that decides the HTTP-shaped response. Middleware is everything you run before that handler, such as timeouts, logging, auth checks, or tweaks to the outgoing payload. SurrealDB runs built-in helpers from the API functions package alongside your own fn:: functions, in the order you list them.

Custom middleware functions are ordinary user-defined functions. Each one receives:

  • The current request object (conventionally $req).

  • A next closure that continues the chain and eventually runs THEN when no middleware remains.

You can add extra parameters after those two. Their values are supplied when you attach the function to DEFINE API, such as the percentage of a discount.

The function must return an object - that is the response object passed to the next middleware or returned to the client. Names like $req and $next are only conventions; what matters is the order of arguments and that you actually call $next($req) when you want the pipeline to proceed.

The examples continue the guesthouse API from Managing APIs with a /quote route, which prices a stay. Middleware adds VAT to the quote and then applies a discount.

The handler returns a fixed quote for three nights in the garden room:

DEFINE API "/quote"
    FOR get
        THEN {
            {
                status: 200,
                body: { room: "garden", nights: 3, price: 400 }
            };
        };

api::invoke("/quote").body;
Output
{
	nights: 3,
	price: 400,
	room: 'garden'
}

This middleware calls $next($req) to obtain the handler's result, then adds the VAT and the total to the body before returning it. Adding two objects with + replaces their top-level fields, so the function builds the new body from $res.body first, and the price and the other fields of the body survive:

DEFINE FUNCTION fn::add_vat($req: object, $next: function) -> object {
    LET $res = $next($req);
    LET $vat = $res.body.price / 5;
    $res + { body: $res.body + { vat: $vat, total: $res.body.price + $vat } }
};

DEFINE API "/quote"
    FOR get
        MIDDLEWARE
            fn::add_vat()
        THEN {
            {
                status: 200,
                body: { room: "garden", nights: 3, price: 400 }
            };
        };

api::invoke("/quote").body;

The handler is unchanged, but the caller now sees the quote with VAT at 20 percent:

Output
{
	nights: 3,
	price: 400,
	room: 'garden',
	total: 480,
	vat: 80
}

A second function, fn::discount, takes an extra parameter for the percentage and lowers the price. The value 10 in fn::discount(10) is passed to that parameter.

Order matters when adding middleware. The first function in the list is the outermost one: it runs first, and it receives the response last, after every function listed below it has changed it. Here VAT must be worked out on the discounted price, so fn::add_vat() comes first and wraps fn::discount(10):

-- Setup from the example above
DEFINE FUNCTION fn::add_vat($req: object, $next: function) -> object {
    LET $res = $next($req);
    LET $vat = $res.body.price / 5;
    $res + { body: $res.body + { vat: $vat, total: $res.body.price + $vat } }
};

DEFINE FUNCTION fn::discount($req: object, $next: function, $percent: int) -> object {
    LET $res = $next($req);
    $res + { body: $res.body + { price: $res.body.price * (100 - $percent) / 100 } }
};

DEFINE API "/quote"
    FOR get
        MIDDLEWARE
            fn::add_vat(),
            fn::discount(10)
        THEN {
            {
                status: 200,
                body: { room: "garden", nights: 3, price: 400 }
            };
        };

api::invoke("/quote").body;
Output
{
	nights: 3,
	price: 360,
	room: 'garden',
	total: 432,
	vat: 72
}

With the two functions the other way round, fn::add_vat() works out the VAT on the full price of 400 before the discount applies, and the response has a price of 360 with a total of 480.

Was this page helpful?

Last updated