Skip to main content

Middleware

Cradle networking allows the use of middlewares to control the flow of data the server is receiving from the client. This is useful for things such as data validation, logging, and more. For example, you could use a middleware to check if the player is allowed to send data to the server, and if they are not, you could kick them from the game or log the attempt.

Note

Middlewares are exclusive to the server. The client cannot use middlewares.

Creating a Global Middleware

Global middlewares are middlewares that are ran on every request. This is useful for things such as logging, data validation, and more.

To create a global middleware, you can use the Cradle:CreateMiddleware method.

local Cradle = require(game:GetService("ReplicatedStorage").Cradle)

Cradle:RegisterMiddleware(1, function()
-- Code here
end, { -- Table of Services
Cradle:GetService("DataService")
})

The first argument is the priority of the middleware. The higher the priority, the earlier it will be ran.

The second argument is the function that will be ran when the middleware is called.

The third argument is a table of services that the middleware will have access to. The services are passed as arguments to the function.

caution

It is recommended to only use this in the bootstrapper. See the Excution Model guide to learn more about it.

Creating Remote Middlewares

Remote middlewares are middlewares that are ran on a specific remote. This is useful for when you want to validate data for a specific remote.

To create a remote middleware, you can use the Cradle:CreateRemoteMiddleware method.

local Cradle = require(game:GetService("ReplicatedStorage").Cradle)

local MoneyService = Cradle:CreateService({
Name = "MoneyService",
Client = {
updateEvent = Cradle.RemoteComm.RemoteEvent.new()
}
})

function MoneyService:Init()
self.Client.updateEvent:AddMiddleware(1, function()
-- Code here
end)
end

The first argument is the priority of the middleware. The higher the priority, the earlier it will be ran.

The second argument is the function that will be ran when the middleware is called.

caution

It is recommended to use this within a service :Init() method.