paint-brush
Setting Up a Backend for React App in 15 Minutesby@pavel_ershov
6,319 reads
6,319 reads

Setting Up a Backend for React App in 15 Minutes

by Pavel ErshovJune 8th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Directual provides visual tools for configuring the whole backend for your app. Directual includes cloud database, API-builder, role-based account control, workflow automation and features for integrations. Using React is the most trusted JS-library: React is most trusted. React is clean, flexible and fast. It's clean and flexible. It’s free until the app does not produce significant significant load (up to 10k requests/month) Use Directual to build your UI components as you used to: classes, hooks, etc.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Setting Up a Backend for React App in 15 Minutes
Pavel Ershov HackerNoon profile picture

Recently I have introduced Directual on Hackernoon (see Low-code for hackers). Now I would like to continue with absolutely practical post. First, I will show the general scheme of combining Directual and React, and then you will find the live-demo of building an app from scratch to production-ready Docker-container.

Low-code Approach for Building a Backend

Quick recap. A development often gets stuck due to the backend part. It takes too long to update API-methods, setup authentication and mess up with an infrastructure. There is a way to make it simpler. Directual provides visual tools for configuring the whole backend for your app. It includes cloud database, API-builder, role-based account control, workflow automation and features for integrations. Such a visual approach is called low-code.

Why React?

We haven’t use any technology just because ‘it’s trendy’. We should solve the problem quickly and efficiently. There are no-code platforms for building a frontend, but if you need rather complex interface, using React will be the best choice. It's clean, flexible and fast. According to the recent StateofJS research, React is the most trusted JS-library:

React + Directual

Using Directual you can setup the whole backend in less than 15 minutes, and then, should any change in database or API required, you can make that change almost instantly.

User Interface (UI)

Feel free to build your UI components as you used to: classes, hooks, etc. And there, in your components you can use the following Directual features:

  • Authentication methods: login, logout, auth context, etc.;
  • Getting data from the database;
  • Posting data into the database.

Have a look at these code patterns:

import Directual from 'directual-api';
import { useAuth } from '../auth' // auth.js is a React-wrapper for directual-api authentication methods
//...
const api = new Directual({ apiHost: '/' })
const auth = useAuth();
//...
const dataStructure = '' // todo: insert here Sysname of your data structure
const endpoint = '' // todo: insert here Method name of your API-endpoint
//...
// Auth context:
auth.user // returns user ID
auth.sessionID // returns user session ID
auth.isAutorised() // returns true if user is authorised
auth.hasRole('role') // returns true if user.role == 'role' (see user management further)
//...
// GET request:
function getData() {
    api
      // Name of Data structure (table) in the Database
      .structure(dataStructure)
      // GET request + query params (sessionID)
      .getData(endpoint, { sessionID: auth.sessionID})
      // other possible query params: page, pageSize, sort and any custom parameter for Filtering
      .then((response) => {
        // handling response
      })
      .catch((e) => {
        // handling errors
      })
  }
//...
// POST-request:
let payload = {} // Request payload
function postData() {
    api
      // Name of Data structure (table) in the Database
      .structure(dataStructure)
      // POST request + payload + query params
      .setData(endpoint, payload, { sessionID: auth.sessionID })
      .then((response) => {
        // handling response
      })
      .catch((e) => {
        // handling errors
      })
  }
//...

Low-code Cloud Backend

Now let’s see how to setup database, API-endpoints and workflows on Directual. First, you need an account—it’s free until the app does not produce significant load (up to 10k requests/month).

Database

There are tables (data structures). Each data structure contains objects.

Each data structure can be configured with the following field types: string, number, decimal, boolean, json, array, link and arrayLink.

There are specific system data structures. The crucial for us at the beginning is App users (system name

WebUsers
). Its objects are the users of your app. Property
id
is a username and
password
is an encrypted user’s password. Property
role
can be used for role-based security and specific features in your app (see
.hasRole
method in the code snippet above).

Here is a short video-tutorial about configuring database on Directual:

API-builder

API layer is an obligatory medium between a database and a UI. Each API-method must provide data following user-based security. For each API-endpoint you are setting up the data structure, and the list of properties available for GET and POST requesting.

Workflows (Scenarios)

Any significant app requires backend logic. There are Directual scenarios for processing the data both in real-time and in scheduled way. Basic scenario steps are just actions under objects, so these steps are quite universal. These scenarios can also integrate your app backend with third-party systems via API.

Directual React Module

Directual React Module contains two files:

  • auth.js provides methods: 
    .user
    .sessionID
    .isAutorised()
    .hasRole()
    .
  • setupProxy.js creates middleware proxy to 
    directual-api
    , for resolving the problem linked with CORS. We need to install
    http-proxy-middleware
    package.

Also you need to have the 

.env
 file in root directory. This file has to contain Directual App id:
APP_ID=_YOUR_APP_ID_

You can find (or create) your App ID in API section on the platform:

Live-demo

I wanted my friends to be able to recommend me movies. So, the app solved that problem. There are 'watched' and 'to watch' movie lists and the form for submitting a recommendation (signing in is required). The result is here MyMovieList, find its code on GitHub.

We will cover:

  • Bootstrapping React app based on Directual boilerplate-code;
  • Using React hooks for handling state;
  • Building authentication and private routing;
  • Configuring database and required APIs in Directual;
  • Getting/Posting data from/to the database;
  • Connecting a third-party API for enriching data;
  • Building and packing our product into Docker container.

I've recorded the whole development process. It took 2 hours 53 minutes, without any fuzz. I tried to compose it as a tutorial for beginners, so I didn't cut anything. If you are an experienced frontend-developer, you may consider watching all the details a bit boring, so, use the timestamps on Youtube.

Hope that it was useful for you! I will be happy to receive a feedback.