Building lightning-fast APIs with FeatherJS
Tags: javascript, webdev
Published: 2020-05-20 19:31:21

---
title: Building lightning-fast APIs with FeatherJS
published: true
date: 2020-05-01 15:55:17 UTC
tags: javascript,webdev
canonical_url: https://blog.logrocket.com/building-lightning-fast-apis-with-featherjs/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/mrdhg1g2wki98y18hvkb.png
---
**Written by [Nedy Udombat](https://blog.logrocket.com/author/nedyudombat/)**✏️

## Introduction

Feathers is a lightweight web framework built over [Express](http://expressjs.com/) for creating applications. Feathers can be used with JavaScript or TypeScript. Users say prototype applications can be built in a matter of minutes with [FeathersJS](http://docs.feathersjs.com/), and production ready applications in a matter of days.

## So why FeathersJS?

For those of us that are curious about why we should consider trying out new tools, here are a couple of reasons you should give FeathersJS a shot:

- It is light-weight web-framework.
- It can be used in creating real-time applications.
- It works with JavaScript or TypeScript (they have got everyone covered)
- Feathers is can work almost anywhere
- It can work with any backend technology — it comes with out-of-the-box support and configuration for [Socket.io](https://socket.io/) and [Primus](https://github.com/primus/primus) depending on your preference
- It works on the server with Node
- It supports over a lot of different databases such as Postgres, Mongo, MySql, NeDB, File System, LocalStorage, SQLite, MSSQL, Cassandra, etc.
- It works on the browser via JavaScript and which means it can be used with a lot of frontend technologies like Vanilla JavaScript, React, VueJS, Angular
- It works on mobile too(who would have thought?), it can be used with React Native, Ionic, Android or iOS
- And yes you can build prototype applications in minutes

## What we will build

In this article, we will be building a simple prototype version of an API with authentication in minutes using FeathersJS and an in-memory database called [NeDB](https://github.com/louischatriot/nedb). So go ahead and ensure you have all the prerequisites installed so we can get to the fun stuff.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

### Prerequisites

- Basic knowledge of JavaScript
- Knowledge of creating RESTful API’s with Express
- The latest version [Node.js](https://nodejs.org/en/) installed on your machine
- A terminal such as [ITerm2](https://iterm2.com/) (Mac OS), [Git bash](https://git-scm.com/downloads)(Windows)
- RestAPI client such as [Postman](https://www.postman.com/), [Insomnia](https://dev.to/scottw/insomnia-rest-client-578d-temp-slug-9682618), etc.

### Installing FeathersJS

The only step to installing and setting up FeathersJS is to install the CLI application globally by running the following command:

```jsx
npm install -g @feathersjs/cli
```

### Creating your API

With these simple steps, we will get our API up and running with authentication:

```jsx
mkdir api-app && cd api-app
```

The command above basically creates a folder where our API will live, and it changes your current directory to that folder:

```jsx
feathers generate app
```

After running this command, you will be asked a couple of questions to determine how your API will be built, and what technologies it will use.

Here is a list of the options I went with:

![The code to build our prototype app.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/Feather-class.png?resize=730%2C447&ssl=1)

Viola! Our API is ready.

After installation, you can open your preferred REST API client and test this out.

Run the command below to start up the API server:

```jsx
npm start
```

If you try visiting the base route `http:localhost:3030` in your REST API clients you should see this response:

![A screenshot of our postman response](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/untitled-request.png?resize=730%2C435&ssl=1)

Or, if you try visiting that route with your browser, you would be greeted with this page:

![A screenshot of our browser request.](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/feathers.png?resize=730%2C435&ssl=1)

At this point, registration, authentication, and authorization is pretty much setup. You can sign up by sending a POST request with your details to the `/users` route.

You can login via the `/authentication` route and a token will be returned in the response. This token can then be used as authorization to access other routes such as sending a GET request to `/users` to retrieve all users.

### Generate a service

Now that we have authentication all set up, let’s create a new service that performs CRUD operations on contacts (i.e creates, reads, updates, and deletes contacts).

In a typical REST API CRUD project, we would have to write each method to handle each of the CRUD operations. Well, not with FeathersJS.

With FeathersJS, a single command creates a service that performs all the CRUD operations on a model and the code is abstracted. Let me show you.

In your terminal, run the command below:

```jsx
feathers generate service
```

You will be asked a couple of questions here.

For the purposes of this article, these are the options I went with:

![A screenshot of our Feathers generate service.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/create-featherjs.png?resize=730%2C447&ssl=1)

Once all the packages are installed, you can go ahead and perform all CRUD operations on the **contacts** service via the `/contacts` route. But before we do that, let’s take a look at the generated files.

**Contact model** (`/src/models/contacts.model.js`): This is where we would define our schema and model to shape what data we collect and how it is stored in the database. NeDB on the other hand does not support schemas, so our model files looks like this:

![An image of the contract model.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/user-service-module.png?resize=730%2C456&ssl=1)

In a situation where a database that allows schema such as MongoDB or Postgres is used, this is the schema that would be defined.

**Contact class** (`/src/services/contact/contacts.class.js`): This is where the CRUD methods are written, but in this case this file is next to empty. This is because the CRUD methods are abstracted and the files just instantiates the `contact` class, which extends the `service` class.

![The code for our contact class in FeatherJS.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/contract-service.png?resize=730%2C456&ssl=1)

**Contact Hooks** (`/src/services/contact/contacts.hooks.js`): This is what determines the workflow of our CRUD operations.

This is what a typical Hooks file looks like:

![A typical contacts Hook file.](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/contact-hooks.png?resize=730%2C456&ssl=1)

For this contacts Hooks, we can see that the before-all Hooks has the `authenticate('jwt')`. This means that before you perform any CRUD operations on the contacts service, you must provide a token.

In other words, you must be logged in.

Hooks functions can be used before, after, or when an error occurs during a CRUD operation.

For instance, if you want to validate that the contacts contain a full name, email, and phone number on creation, this would be done in the before Hook and it would look something like this:

```jsx
before: {
  all: [ authenticate('jwt') ],
  find: [],
  get: [],
  create: [ function(context) {
    // perform validation 
    return context;
  }],
  update: [],
  patch: [],
  remove: []
},
```

If you also wish to do something after the data has been created, read, updated, or deleted, you will have to write that function in the after Hook. For Instance, if you want to send mail to the contact’s mail, it would look something like this:

```jsx
after: {
  all: [],
  find: [],
  get: [],
  create: [ function(context) {
    // send email function
    return context;
  }],
  update: [],
  patch: [],
  remove: []
},
```

Same thing goes if you want to handle an error gotten in a certain manner. For instance, if you want to use an error logger like [Sentry](https://sentry.io/welcome/), that would be added in the error Hooks.

**Contact service** (`/src/services/contact/contacts.service.js`): This is where the single route service is defined, Hooks & model is registered, and the service is initialized. It looks somewhat like this:

* * * 
## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *

![Our initialized contacts service.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/contacts-paginate.png?resize=730%2C456&ssl=1)

The code is pretty small. This is due to the fact that FeathersJS handles a lot of the lifting behind the scenes in the form of abstraction.

**NOTE** : FeathersJS uses different strategies to handle authentication such as Local, JWT, OAUTH, Google, Github, etc. When trying to make a POST request to `/authentication` please specify the strategy. See example below:

POST request to the `/authentication` route to login(generate an access token):

![Post authentication using FeatherJS.](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/05/post-authentication.png?resize=730%2C436&ssl=1)

## Conclusion

FeathersJS really makes it easy for us to prototype applications in minutes.

To build a production-ready application, you might need to opt for a more robust database such as [MongoDB](https://www.mongodb.com/) or [Postgres](https://www.postgresql.org/) as opposed to NeDB.

You might also want to check out their well written [documentation](https://docs.feathersjs.com/) for more on FeathersJS abilities and their [Awesome Feathers](https://github.com/feathersjs/awesome-feathersjs) page for all things Feathers.

The post [Building lightning-fast APIs with FeatherJS](https://blog.logrocket.com/building-lightning-fast-apis-with-featherjs/) appeared first on [LogRocket Blog](https://blog.logrocket.com).