In this tutorial I will show a protocol that I rarely see used, probably because the boilerplate required, but once that boilerplate is in place, it will be very nice to work with!

I've saved the basic boilerplate code in a Github repo called JSQL.

A general purpuse JavaScript protocol and "query language" for communicating with a server via JavaScript

"AJAX" changed the way we write "web apps". And Websockets have been supported by browsers for several years now!
Websockets allows two way communication between the server and the client (web browser), and not only reduces overhead from HTTP request, it also allows server push.

But what language should you use to let your JavaScript front-end communicate with your JavaScript back-end !?
JavaScript of course!

Here's an example of sending and handling a query/request:

Client side

CLIENT = Namespace/object.
CLIENT.api = function/method to query/call the server/API
"hello" = Name of endpoint/api
{to: "world"} = options object.
function hello = Function to be called with the server/API response.

Server side

API = Namespace/object
API.hello = Name of the endpoint/api
function hello = function/method for handling requests
options = The options object from the client*
callback = The callback function from the client*

* The data has been serialized and sent over the network and the protocol will make sure the right callback is called.

Events and observables

Websockets allow us to push data to the client without polling or requesting it. Here's an example on how we can handle such push events

CLIENT = Namespace/object
CLIENT.on = Method for adding event listeners
"progress" = Name of the event.
function showProgress = function to be called when there's a "progress" event.


  1. Client adds an id (counter) to each request object, and associates the id with the callback function
  2. Client serialize (JSON.stringify) the request and sends it over Websocket (SockJS) to the server
  3. Server deserialize's (JSON.parse) the request
  4. Server creates a response object, adds the request id to it, and send's it back to the client
  5. Client calls the callback function associated to the request id

See JSQL repo for example implementation.

Written by April 17, 2018.

Follow me via RSS:   RSS https://z├Ąta.com/rss_en.xml (copy to feed-reader)
or Github:   Github https://github.com/Z3TA