Middleware

Learn how to use middleware

Middleware

Middleware is a function that runs before the route handler. It can be used to perform operations like logging, authentication, etc.

Usage

To use middleware, you can create it via aurora.Middleware and then use it in the route.

local aurora = require("@aurora/")

-- Create a middleware
aurora.middleware("name" ,function(request)
    print("Middleware")

    return { status = 200 }
end)

To use the middleware, you can pass it as the third argument in the route.

local aurora = require("@aurora/")

-- Create a middleware
aurora.middleware("name" ,function(request)
    print("Middleware")

    return { status = 200 }
end)

-- Create a route
aurora.get("/middleware", function(req, res)
    print("Route")

    res.send("middleware ran")
end, {"name"})

aurora.serve()

Stop Middleware

You can stop the middleware from running by returning a response from the middleware.

local aurora = require("@aurora/")

-- Create a middleware
aurora.middleware("name" ,function(request)
    print("Middleware")

    if request.query["stop"] == "true" then
        return { body = "Stopped", status = 400 }
    end

    return { status = 200 }
end)

-- Create a route
aurora.get("/middleware", function(req, res)
    print("Route")

    res.send("middleware ran")
end, {"name"})

aurora.serve()

Visit /middleware?stop=true to see the middleware stop the route from running.

Middleware Order

The order of the middleware is important. The middleware will run in the order they are passed in the route.

Built-in middleware like logging will run before the custom middleware.

function middleware(name: string,handler: (request: Request) -> Response): Response