Skip to content
On this page

Getting started ​

ExpressX is a framework handling both backend and frontend and their communication using websockets.
A single websocket is used to channel both data and events between the server and each client.

Plugins add new features, such as preserving connection state across page reloads.

bash
mkdir myproject
cd myproject
mkdir backend frontend

Initialize backend ​

The server API is exported by @jcbuisson/express-x/server.

bash
cd backend
npm init es6
npm install @jcbuisson/express-x express cors socket.io bcryptjs

Back-end example with a custom service ​

The following example provides a 'math' service with two custom functions 'square' and 'cube':

js
// app.js
import { expressX } from '@jcbuisson/express-x/server';
import cors from 'cors'

// `app` is a regular express application, enhanced with express-x services and real-time features
const app = expressX();
// regular express middleware, to allow access from our front-end
app.use(cors());

// create a custom 'math' service with 2 methods
app.createService('math', {
   square: (x) => x*x,
   cube: (x) => x*x*x,
});

app.httpServer.listen(8000, () => console.log(`App listening at http://localhost:8000`));

A service may have as many parameters as needed, of any types as long as they are serializable.

Run back-end ​

node app.js

Initialize front-end ​

The browser API is exported by @jcbuisson/express-x/client.

bash
cd frontend
npm init es6
npm install @jcbuisson/express-x socket.io-client @vueuse/core

Front-end example ​

index.html

html
<html>
   <input id="value-id" type="number" placeholder="Enter value"><br>
   <button id="square-id" class="btn">Square</button>
   <button id="cube-id" class="btn">Cube</button>
   <p id="result-id"></p>
</html>

<script type="module">
import io from 'socket.io-client';
import { createClient } from '@jcbuisson/express-x/client';

const socket = io('http://localhost:8000', {
   transports: ["websocket"],
});

const app = createClient(socket);

const valueInput = document.getElementById('value-id');
const squareBtn = document.getElementById('square-id');
const cubeBtn = document.getElementById('cube-id');
const resultParagraph = document.getElementById('result-id');

squareBtn.addEventListener('click', async (ev) => {
   const result = await app.service('math').square(valueInput.value);
   resultParagraph.innerHTML = result;
})

cubeBtn.addEventListener('click', async (ev) => {
   const result = await app.service('math').cube(valueInput.value);
   resultParagraph.innerHTML = result;
})
</script>

Run front-end ​

npx vite

Calling a service method from the frontend is as easy as await app.service('math').square(value)

By default, errors on the server-side are serialized and re-emitted on the client-side, so you can catch them if needed.

Add a CRUD API over a relational database ​

It is very easy to expose the data access method of an ORM such as Prisma through ExpressX:

js
// app.js
import 'dotenv/config'
import { expressX } from '@jcbuisson/express-x/server'
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.ts'

const adapter = new PrismaPg({
   url: process.env.DATABASE_URL,
})
const prisma = new PrismaClient({ adapter })
const app = expressX()

app.createService('post', {
   create: (data) => prisma.post.create({ data }),
   findMany: (where = {}) => prisma.post.findMany({ where }),
   update: (id, data) => prisma.post.update({ where: { id }, data }),
   remove: (id) => prisma.post.delete({ where: { id } }),
})

app.httpServer.listen(8000)

For production, add authentication and authorization hooks before exposing these methods to clients.

The client calls these methods through the normal service proxy:

js
const created = await app.service('post').create({
   title: 'Hello',
   content: 'Stored with Prisma',
})

const posts = await app.service('post').findMany()
await app.service('post').update(created.id, { title: 'Updated' })
await app.service('post').remove(created.id)

This service requires a network connection and does not provide synchronized reactive reads.

Real-time applications ​

When a connected client calls a service method, two things happen on method completion:

  • the resulting value is sent to the client
  • an event is emitted, and sent to connected clients we'll call subscribers. The calling client may or not be one of those subscribers.

For example in a medical application, whenever a patients's record is modified, an event could be sent to all his/her caregivers.

Channels are used for this pub/sub mechanism. Service methods publish events on channels, and clients subscribe to channels in order to receive those events. ExpressX provides functions to configure which events are published to which channels. A channel is represented by a name and you can create and use as many channels as you need.

Example: shared bilboard ​

In the following example of a shared bilboard, every time a client connects to the server, it joins (= is subscribed to) the 'all' channel. And whenever an event is emited by the bilboard service, this event is published on this channel, and then broacasted to all connected clients, leading to real-time updates.

js
// app.js
// Run it with: `node app.js`
import { expressX } from '@jcbuisson/express-x/server';
import cors from 'cors'

// `app` is a regular express application, enhanced with express-x services and real-time features
const app = expressX();
// express middleware which prevents cors issues with dev front-end
app.use(cors());

app.createService('bilboard', {
   // the posted message will be dispatched to all connected clients 
   sendMessage: (message) => {
      return message;
   }
});

// publish
app.service('bilboard').publish(async (context) => {
   return ['all']
});

// subscribe
app.on('connection', (socket) => {
   app.joinChannel('all', socket)
})

app.httpServer.listen(8000, () => console.log(`App listening at http://localhost:8000`));
html
<!-- index.html -->
<!-- Run it: npx vite -->
<html>
   <input id="message-id" type="text" placeholder="Enter message"><br>
   <button id="send-id" class="btn">Send</button>

   <div id="bilboard-id"></div>
</html>

<script type="module">
import io from 'socket.io-client';
import { createClient } from '@jcbuisson/express-x/client';

const socket = io('http://localhost:8000', {
   transports: ["websocket"],
});

const app = createClient(socket);

const messageInput = document.getElementById('message-id');
const sendBtn = document.getElementById('send-id');
const bilboardDiv = document.getElementById('bilboard-id');

sendBtn.addEventListener('click', async (ev) => {
   await app.service('bilboard').sendMessage(messageInput.value);
});

app.service('bilboard').on('sendMessage', (message) => {
   bilboardDiv.innerHTML = bilboardDiv.innerHTML + '<br>' + message;
})
</script>

The listener is triggered whenever the client receives from the server a sendMessage event from the bilboard service. This event is sent to all subscribers after the execution of app.service('bilboard').sendMessage() on the server.

Still an Express application ​

The server continues accepting HTTP connections on the same port, so you can still use your favorite middlewares, routers etc.

js
app.get('/api', function (req, res) {
   const data = { a: 123, b: 234 }
   res.send(data)
})