4 steps to add a serverless back end to React
Long Nghiem
Posted on September 15, 2020
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 🤠)
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:
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
- 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:
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:
// 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:
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, 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 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:
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.
// 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 once. We recommend to initialize it in the entry point of your main project:
// src/index.js
import “@warpjs/engine”;
Regarding the UI, let’s replace the content of App.css
, App.js
, and add the Users.js
component I prepared.
Let’s have a look through the way the serverless back-end is called in Users.js
:
// 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.
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. It’s free, spam-free, and comes with free credits. When it’s
done, let’s get back to our console to log in:
npx warp login
In the Warp console, 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.
# 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.
# 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 for many use cases in GitHub, I recently recorder a tutorial video for Vue.JS, and you can find step-by-step tutorials for Angular and Vue.js.
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 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!
Posted on September 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.