Skip to main content

Middleware

You can also employ middleware with use: these are run first at every request. Note that unlike other methods (e.g.: get) those may return a response but do not have to.

note

See request and response documentation to see how to add and retrieve data from them.

Existing Middlewares​

List of existing middleswares. See the documentation for more details.

Feel free to make a PR to add to the list.

Creating middlewares​

Below we add a middleware that simply print the time at which the request is recevied.

library(ambiorix)

app <- Ambiorix$new()

app$use(\(req, res){
print(Sys.time())
})

app$get("/", \(req, res){
res$send("Using {ambiorix}!")
})

app$get("/about", \(req, res){
res$text("About")
})

app$start()

Multiple middleware can also be used. These can be used to modify add parameters to the request.

library(ambiorix)

app <- Ambiorix$new()

app$use(\(req, res){
req$x <- 1 # set x to 1
})

app$use(\(req, res){
print(req$x)
})

app$get("/", \(req, res){
res$sendf("x set to %s", req$x)
})

app$start()

Common Pattern​

Existing middlewares tend to use function factories, which is useful if you want to package of write reusable middleware.

middleware <- \(prefix){
\(req, res){
cat(PREFIX, "-log\n")
}
}

app$use(middleware("PREFIX"))