How to call a server-side function from client-side?

It is possible to call server-side functions in client-side code using the ~% syntax. For security reasons, these functions must first be declared explicitely as "server functions" (with the type of their argument).

let f x = ...

let%client f_rpc = ~%(server_function [%derive.json: int] f)

...

[%client ... f_rpc 4 ... ]

Server functions are just syntactic sugar for non-attached coservices returning OCaml values.

Note that your project needs to load the json plugin for ppx_deriving, which is available as the Ocamlfind package js_of_ocaml.deriving.ppx.

If the function takes a more complex type, this type must have been declared with ppx_deriving. For example,

type t = int * string [@@deriving json]

Our infrastructure provides server-side data validation of the data sent, and prevents malformed data from crashing the server.