JAMstack best practices: Adding a serverless back-end to Angular
Published: 2020-09-15 13:13:02

JavaScript frameworks, and Angular, in particular, are growing at a very fast pace these days. The latest updated version of Angular offers several benefits such as MVVM, exceptional support for TypeScript, structure, and architecture specifically created for project scalability. What better completes a state-of-the-art Angular front end than a nice serverless back end? We will introduce here a way to perform better and faster with Angular by adding a serverless (FaaS) back-end to it while avoiding to code the HTTP parts on both sides, front and back.

I will show you how to do that with the [ScaleDynamics platform](https://scaledynamics.com/) — a new approach to serverless — that offers a unique way to code and deploy back-ends on serverless function (FaaS). You can deploy it on any type of public FaaS such as AWS Lambda, GCP functions, or on private clouds.

![Lego_1](https://dev-to-uploads.s3.amazonaws.com/i/27kvlkagm3sqh7x1o1zr.gif)

#**1. Initialize project**
First, we create our main Angular project:
```Javascript
$ npm install -g @angular/cli
$ ng new angular-warp-tuto
```
#**2. Set up ScaleDynamics platform server**
In our example we will create a basic HTTP server proxy, to do that we will:

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

To do so, let’s create a server directory at the root of our main project and initialize a new `Node.js` project inside it:
```Javascript
mkdir angular-warp-tuto/server
cd angular-warp-tuto/server
npm init -y
```
And then, install the [Axios library](https://www.npmjs.com/package/axios) that we need:
```Javascript
npm install axios
```
In the server subproject, let’s create an `index.js` 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”,
 }));
};
```
Now, this is a very important part, we need to tell the platform to turn function into a serverless function (FaaS) and to host it as a serverless function by doing this:
```Javascript
// getUsers is the function that we will call from the Front-end
module.exports = { getUsers };
```
You have it done? From now on, we don’t have to deal with HTTP arguments, errors, endpoints… ScaleDynamics will take care of that for us.

![Lego_2](https://dev-to-uploads.s3.amazonaws.com/i/jvgacquqqv2yyfmn3oc3.gif)

Next, to configure the platform, we create a `warp.config.js` file like this example:
```Javascript
module.exports = {
 // project name in the ScaleDynamics console (demo is created by default)
 project: “demo”,
 output: {
  format: “node-module”,
  // path to the “node_modules” directory of our main project
  projectPath: “../”,
  // module name to import it in our main project
  name: “warp-server”,
 },
};
```
The ScaleDynamics console will be introduced further regarding the “project” property.

The platform will generate an `npm` package named `warp-server` to be used in the client project thanks to the node-module [output format](https://warpjs.dev/docs/api/warp-config#output). This works as a helper module (a wrapper) to call our server.
#**3. Set up ScaleDynamics in project**
Our server is ready, now we need to set up ScaleDynamics in our project.

ScaleDynamics comes with a command-line interface (CLI) on the server-side to help us start our local emulator, build our project, and deploy it on a cloud. On the client-side, the platform engine and the helper module will prevent us from making HTTP calls and that’s all we need on this side.

Now, get back to the project, we need to install these small dependencies:
```Javascript
cd ..
npm install @warpjs/engine
npm install warp npm-run-all — save-dev
```
Then, add the server parts in the start and build commands, and the deploy command-line in `package.json`:
```Javascript
“scripts”: {
+ “postinstall”: “cd ./server && npm install”,
“ng”: “ng”,
- “start”: “ng serve”,
+ “start:client”: “ng serve”,
+ “start:server”: “warp start-emulator -w ./server”,
+ “start”: “run-p start:*”,
- “build”: “ng build”,
+ “build:client”: “ng build — prod”,
+ “build:server”: “warp build ./server”,
+ “build”: “run-s build:server build:client”,
+ “deploy”: “warp deploy — asset-dir dist/angular-warp-tuto ./server”,
“test”: “ng test”,
“lint”: “ng lint”,
“e2e”: “ng e2e”
},
```
Just one more step before we can run and test our project, we need to import the [Warp engine](https://warpjs.dev/docs/api/engine) once to call the serverless function in our code.
I recommend to initialize it in the entry point of the main project:
```Javascript
// src/main.ts
import “@warpjs/engine”;
```
Then, import the `npm` module to init and call the serverless function. Here’s how it looks like when the serverless back-end is called:
```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();
```
Everything is all set, you’re free to test your project now 🤞 🙏🏻
#**4. Run**
We need a ScaleDynamics account to run and deploy our project in the cloud. If you do not have one yet, you can request a [free trial](https://scaledynamics.com/platform) this link. It’s free and spam-free 😊.

After you get your account, get back to the console to log in:
```Javascript
npx warp login
```
We can run the project now, this command-line will run a serverless emulator for the back-ends, and will also start a server to serve our Angular front end.
```Javascript
# run a dev server:
npm run start
```
After that, a browser will pop up with a list of fake users and Lego faces as profile pictures. Do not hesitate to play the front-end or back-end code, both servers will live-reload 😎

Now is the time… The last step: deploy it on a cloud!

ScaleDynamics will deploy the back end on a FaaS platform (GCP functions) and the front-end on a Google storage.
```Javascript
# build and deploy to production
npm run build
npm run deploy
```
#**Your project is now ready!**

![Lego_3](https://dev-to-uploads.s3.amazonaws.com/i/tq3xeuv5qwjq7xi2aqnr.gif)

Now, we have our URL, client and server are well hosted. Throughout the process, we did not have to deal with any HTTPs requests, route, security, endpoints, or errors… that gives us a much faster experience, the opportunity to focus on the logic and the UI, and to forget a little about the pipes 🔧

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 recorded [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 [Vue.js](https://dev.to/scaledynamics/8-simple-steps-to-add-a-serverless-back-end-to-a-vue-js-project-2j60) and [React](https://medium.com/warpjs/4-steps-to-add-a-serverless-back-end-to-react-ff2a6303727b).

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 🙂
#**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!