We're live-coding on Twitch! Join us!
Build Light-Weight REST and Realtime Apps with FeathersJS

Build Light-Weight REST and Realtime Apps with FeathersJS

In the barest of definitions, Feathers is a simple minimalistic realtime framework for web applications built over Express. What this means is that with Feathers, you can keep using middlewares but in addition, you get realtime, RESTful services and ORM support out of the box. In this post, we’ll explain the basics and features of FeathersJS as well as build a small realtime messaging application to demonstrate a few of the features.

Why FeathersJS?

You could be one of the very few that prefers to challenge concepts and dig deeper into why should i use this framework?

Well, here’s a few reasons:

  1. Unlike a few others, Feathers easily integrates with any client-side framework.
  2. Feathers is universal by design. It works on the browser (JavaScript), on mobile (React Native, Ionic) and on the server with Node.js.
  3. Feathers is a modern framework built with promises and ES6, you get all the best and modern coding conventions by default.
  4. Feathers is structured to build service-oriented apps making it comfortable for you to split your application into microservices and scale with ease.
  5. Feathers is data agnostic. It has adapters for over 15 data sources including MongoDB, PostgreSQL, etc.
  6. Feathers ships with external plugin that allows you to implement authentications, SMS and email messaging.

Other features

Before we proceed to build a realtime app with Feathers, here are a few of its core features i thought you’d want to know:

  • Feathers put realtime on the forefront of your applications, not at the back.
  • You can build robust lightweight web applications really quickly
  • Build API’s with authentications
  • Interface with existing technologies like React, Angular etc.
  • It is fully customizable, you can use the tools provided by Feathers or mix-match them with your own tools.
  • ORM support for databases.

Now that we are familiar with the few things we can do with Feathers, let’s go ahead and build our app.

Prerequisites

All you need to get started with FeathersJS is a working computer system with NodeJS and any preferred generator installed. However, to build specific projects, you may occasionally need to install more packages as your project requires.

Getting started

The best way to quickly get started with Feathers is through the command line interface tool. With NodeJS open a terminal window and run this commands:

Essential Reading: Learn React from Scratch! (2019 Edition)
## install feathers cli globally
$ npm install -g @feathersjs/cli

## Install Yeoman generator for feathers
$ npm install -g  yo generate-feathers

## create a new project directory "feathers-demo"
$ mkdir feathers-demo

## navigate into the new project directory "feathers-demo"
$ cd feathers-demo

## create a new application "feathers-app"
$ yo feathers

## start the development server
$ npm start

This will prompt for the project config details like project name, description, API type, database etc. After that, your project will be generated and live on localhost:3030. If you navigate to that port on your browser, you should see your app live:

Great, you have a brand new FeathersJS application. But at the moment it doesn’t really do much so we’ll go ahead and add a service to get things going. Since we are building a demo realtime app, let's create a message service. Go back to the terminal and run the command below:

$ yo feathers:service

This will throw a bunch of prompts to get more information about the service you want to create, answer the prompts and proceed:

At this point, if we restart the development server and navigate to the new path on the browser localhost:3030/message we will get the database displayed like so:

Great, now our database is showing up as expected!. However, it is empty, let's do something about that, back in your terminal, run this curl command:

curl 'http://localhost:3030/message/' -H 'Content-Type: application/json' --data-binary '{"text": "Hello world"}'

This will send a post request to our /message endpoint and the post data should reflect in our database like so:

Great our data is posted!. What happened here is, Feathers automatically made an API for us, we didn’t have to create any of the /get() or /post() methods. You may have also noticed that we have an automatically generated unique ID for each message.

It was cool but that's not all the functionality we want, we want to allow users post data to this database and render it on the client in realtime. To do this, open the public/index.html file and update the code with the one below:

    <!-- public/index.html -->
    <html>
      <head>
        <title>Welcome to Feathers</title>
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css"
          integrity="sha384-PDle/QlgIONtM1aqA2Qemk5gPOE7wFq8+Em+G/hmo5Iq0CCmYZLv3fVRDJ4MMwEA"
          crossorigin="anonymous"
        />
      </head>
      <body>
        <main class="container">
          <img
            class="logo"
            src="svg"
            alt="Feathers Logo"
          />
        </main>
        <div class="card mt-5">
            <div class="card-header">
              Messages
            </div>
            <div class="card-body">
              <h5 class="card-title">Send Message</h5>
              <input class="form-control" type="text" placeholder="message" id="message"/>
              <button onclick="sendMessage()" type="button" class="btn btn-primary mt-2">
                  Send Message
                </button>
            </div>
          </div>
      <div>

    </div>

        <script src="//cdn.rawgit.com/feathersjs/feathers-client/v1.0.0/dist/feathers.js"></script>
        <script src="socket.io/socket.io.js"></script>
        <script type="text/javascript">
          var socket = io()
          var app = feathers()
          app.configure(feathers.socketio(socket))
          var messages = app.service('message')

          messages.on('created', function(message){
            console.log('Message created on client', message)
          } )
          function sendMessage(){
            var messageText = document.getElementById('message').value;
            messages.create({text: messageText})
          }
        </script>
      </body>
    </html>

Great, now when you check back at our Feathers app on localhost:3030 you will get an updated user interface from where we can update our database like so:

Here, we type the message in the input field on the left and click the Send Message button. This adds the text to our database and we then navigate to localhost:3030/message on the right and we see the message added to our database.

Lastly, let’s update the app to render our messages on the UI in realtime. Update the index.html file again with the code below:

    <!-- public/index.html -->
    <html>
      <head>
       ...
      </head>
      <body>
      .... 
     +   <div class="card">
     +       <div class="card-body">
     +         <p id="messageList" class="card-text"></p>
     +       </div>
     +   </div>
      ....

        <script src="//cdn.rawgit.com/feathersjs/feathers-client/v1.0.0/dist/feathers.js"></script>
        <script src="socket.io/socket.io.js"></script>
        <script type="text/javascript">
      ....
          messages.on('created', function(message){
     +      var newMessage = document.getElementById("messageList");
     +      newMessage.innerHTML += "<h4>" + message + "</h4>"
            console.log('Message created on client', message)
          } )
          function sendMessage(){
            ...
           }
        </script>
      </body>
    </html>

And now app renders messages on both our database and our UI in realtime across all clients like shown in the image below:

Conclusion

In this post, We have looked at the basics and features of FeathersJS. We have also demonstrated how to get started with FeathersJS to build realtime scalable web applications. You can find out more about Feathers in the official documentation page.

Like this article? Follow @codebeast on Twitter