4 steps to add a serverless back end to React
Published: 2020-09-15 13:46:41

In this world, there're two kinds of web developers: those who code front ends, and those who code back ends… (inspired by [Mr. Leone](https://www.youtube.com/watch?v=s2w9X_tHU7k) 🤠)

You, you want to be a full-stack. But deep in your heart, you know you belong to one of those two kinds. Wherever your natural skills are, this article will help you on the path of the JavaScript full-stack development. Serverless is a nice approach to avoid server management while scaling with virtually no limit. Let’s see how to make it even easier with ScaleDynamics, which spares us the HTTP coding parts on both sides.

In terms of serverless, I guess you already know Vercel — that offers static and Jamstack deployment, Serverless Functions, and Global CDN, however, I won’t talk about Vercel but about a newer serverless platform — ScaleDynamics which introduces a unique approach to code and deploy back-ends on serverless function (FaaS). It is basically kind of a Vercel for Enterprises — because you can deploy it on any cloud, even private clouds, and on-premise — with a new approach for developing and coding the APIs.

So without any further ado, let’s get started!

#**1. Initialize project**
First, create your main React project:
```Javascript
npx create-react-app react-warp-tuto
```

#**2. Set up ScaleDynamics server**
In this step, we will create a Basic HTTP proxy in `Node.js` in order to:

- Fetch data from a [REST API](https://jsonplaceholder.typicode.com/users)
- Filter data to avoid to request too much data as client-side
- Add random avatars in response (to make the rendered page look prettier ;)

To do so, let’s create a server directory at the root of your main project and initialize a new `Node.js` project inside it:
```Javascript
mkdir react-warp-tuto/server
cd react-warp-tuto/server; npm init -y
And install the [Axios library](https://www.npmjs.com/package/axios) we need:
npm install axios
```
Now, here’s the fun part! In the server subproject, we create an `index.js` in order to create back-end serverless function:
```Javascript
// server/index.js
const axios = require(“axios”);
const getUsers = async () => {
 // fetch users from API
 const { data } = await axios.get(“https://jsonplaceholder.typicode.com/users");
// Pick attributes and add photo
 return data.map(({ id, name, email, phone, company, address }) => ({
  id,
  name,
  email,
  phone,
  city: address.city,
  work: company.name,
  photo: “https://randomuser.me/api/portraits/lego/" + (id % 10) + “.jpg”,
 }));
};
// getUsers is the function that you will call from the Front-end
module.exports = { getUsers };
```
Did you notice that last line of code? That part is very important: it will technically tell ScaleDynamics to turn that function into a serverless function (FaaS) and to host it as a serverless function. Basically, you don’t need to deal with HTTPs, arguments, errors, endpoints… ScaleDynamics will do it all for you.

Then, we create a `warp.config.js` files to configure ScaleDynamics as follows:
```Javascript
module.exports = {
 // project name in the Warp console (demo is created by default)
 project: “demo”,
 output: {
  format: “node-module”,
  // path to the “node_modules” directory of your main project
  projectPath: “../”,
  // module name to import it in your main project
  name: “warp-server”,
 },
};
```
Regarding the project name, the ScaleDynamics console will be introduced further.

Thanks to the node-module [output format](https://warpjs.dev/docs/api/warp-config#output), ScaleDynamics will generate a module named `warp-server` to be used in the client project. Consider it is a helper module, a stub, to call the server.

#**3. Setup ScaleDynamics in project**

On the server-side, ScaleDynamics comes with a [command-line interface](https://warpjs.dev/docs/api/cli) to let you start a local emulator, build the project, and deploy it on a cloud.

On the client-side, you only need the Warp engine and the generated helper module to call the server API (this prevents us to make an HTTP call).

Back to our parent project, let’s install these small dependencies:
```Javascript
cd ..
npm install @warpjs/engine
npm install warp npm-run-all — save-dev
```
While it’s running, in `package.json`, let’s add the server parts in the start and build commands, plus the deploy command-line.
```Javascript
// package.json
“scripts”: {
+ “postinstall”: “cd ./server && npm install”,
- “start”: “react-scripts start”,
+ “start:client”: “react-scripts start”,
+ “start:server”: “warp start-emulator -w ./server”,
+ “start”: “run-p start:*”,
- “build”: “react-scripts build”,
+ “build:client”: “react-scripts build”,
+ “build:server”: “warp build ./server”,
+ “build”: “run-s build:server build:client”,
+ “deploy”: “warp deploy — asset-dir build/ ./server”,
“test”: “react-scripts test”,
“eject”: “react-scripts eject”
},
```
Finally, to call a serverless function in your code, you have to import the [Warp engine](https://warpjs.dev/docs/api/engine) once. We recommend to initialize it in the entry point of your main project:
```Javascript
// src/index.js
import “@warpjs/engine”;
```
Regarding the UI, let’s replace the content of [`App.css`](https://github.com/WarpJS/samples/blob/master/react/src/App.css), [`App.js`](https://github.com/WarpJS/samples/blob/master/react/src/App.js), and add the [`Users.js`](https://github.com/WarpJS/samples/blob/master/react/src/Users.js) component I prepared.
Let’s have a look through the way the serverless back-end is called in [`Users.js`](https://github.com/WarpJS/samples/blob/master/react/src/Users.js):
```Javascript
// imports the Warp helper module, to back-end wrapper
import WarpServer from “warp-server”;
// creates an instance of the helper
const { getUsers } = new WarpServer();
// async call to the serverless function
const users = await getUsers();
```
Then, when the promise is returned, the `users` state variable is set.
```Javascript
getUsers().then((data) => {
  this.setState({ users: data })
})
```
We’re all set, let’s test it now 🤞 🙏🏻

#**4. Run**

As we will deploy our project on the cloud, we first need to authenticate ourselves with a ScaleDynamics platform account. If you do not have one yet, you can request a [free trial with this link](https://scaledynamics.com/platform). It’s free, spam-free, and comes with free credits. When it’s 
done, let’s get back to our console to log in:
```Javascript
npx warp login
```
In the [Warp console](https://starbase.warpjs.com/), there is by default a “demo” project. For new projects, you will just need to create a new one and to use the same name in your `warp.config.js` “project” attribute.

Let’s run the project now. This command-line will run a serverless emulator for the back end, with ScaleDynamics, and will start a React server as usual.
```Javascript
# run a dev server:
npm run start
```
The browser window opens itself with our wonderful list of fake users with Lego avatars. Feel free to update the front end or back end without killing your servers, it both supports live-reload 😎

Now let’s kill this local server (Ctrl+C twice) and deploy it on a cloud.
```Javascript
# build and deploy to production
npm run build
npm run deploy
```
ScaleDynamics deploys the back end on FaaS platform GCP functions (as I write these lines, more options exist though), and the front-end on a Google storage (for the sake of this demonstration).

#**Your project is now ready!**

So, at this step, you get your URL, client, and server which are hosted. Throughout the process, we did not have to deal with any HTTP requests, route, security, endpoints, errors…that saved us lots of headaches and tons of time.

To integrate with other frameworks, you can find a lot of [code samples](https://github.com/WarpJS/samples) for many use cases in GitHub, I recently recorder a [tutorial video for Vue.JS](https://www.youtube.com/watch?v=-1aP7LhIkdc&feature=youtu.be), and you can find step-by-step tutorials for [Angular](https://dev.to/longnghiem95/jamstack-best-practices-adding-a-serverless-back-end-to-angular-2ii9) and [Vue.js](https://dev.to/scaledynamics/8-simple-steps-to-add-a-serverless-back-end-to-a-vue-js-project-2j60).

I hope you’ve found this tutorial helpful and if you have any questions, don’t hesitate to leave it in the comment section below 🙂

The last article in this series is for Angular, so stay tuned 🤟

#**Credits**

Big thanks to [Nicolas Pennec](https://twitter.com/NicoPennec) who developed the app we took as an example. He is a JavaScript Expert in ScaleDynamics. He co-organizes RennesJS, a French JavaScript Meetup, so if you come by Brittany you’re more than welcome to join us!