Advanced Guides

Creating and hosting a full-stack web application

Introduction

Launching a full stack application can be daunting. You have to worry about hosting your frontend, configuring/provisioning a server, and tying everything together. You may not have known it, but Back4App provides an optimal infrastructure for all of the above.

You can easily serve your frontend HTML (including frontend frameworks like React and Vue) with Back4App’s Web Hosting. Cloud Code makes an excellent backend that launches quickly. In this guide we’ll build a complete, albeit rudimentary, web application on Back4App.

This is a guest tutorial written by John Considine, lead developer at K-Optional.

Goals

Launch a full-stack web-application on Back4App

Prerequisites

To complete this tutorial, you need:

  • To be familiar with the command-line
    • Git and NPM should be installed
  • Have a Back4App Account, with the cli tool installed and configured, see here for help
  • Create a brand new project on your Back4App dashboard- see here for help
    • This tutorial must be set the Parse Server Version 3.1.x. See directly below for more details

This project will use the newly released version 3.1 Parse Server. This means you need to make sure your Back4App project is set to this release- it won’t work otherwise. On your project dashboard, go to Server Settings » Manage Parse Server(settings) and select 3.1.1 (it may be in Beta). For more information on migrating to Parse Server 3.1.x, see this guide. See this guide if you do not understand the syntax of the cloud code for this project.

Project Background

We will launch a rudimentary ticket exchange application. It allows users to signup, login, and post tickets they are selling to different events- which admins can create using the Dashboard. Other user’s can contact them by their email or phone number, depending on what the poster chooses to display.

I have launched the app here, using the same code we explore in this guide. You are free to create an account, post tickets, and see what the app looks like.

The point of this tutorial is to demonstrate how to efficiently launch an app. Thus rather than dwelling on each line of code, we will start with a mostly finished codebase and focus on the ease of deployment. There is only one place where you’ll need to edit code:

  • In step 1 you’ll need to add your project settings (Application ID, JavaScript Key, and server URL).

However, you’re welcome to edit and extend this application in anyway you like.

Step 0 - Project Structure

Before you start preparing code, it’s important to understand the file structure of this project. I’ll use this as a reference throughout this guide. Here’s what your directory will look like when everything is finished:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
project
│   .parse.local
│   .parse.project
│   .gitignore
│   README.md
└───public
│   │   index.html
│   │   login.html
│   │   signup.html
│   └───css
│       │   signin.css
│       │   bootstrap.min.css
│   └───js
│       │   main.js
│       │   parse.js
│       │   signin.js
│       │   signup.js
│
└───cloud
    │   main.js

The main takeaways from this setup are:

  1. The frontend code lives in the public directory. A frontend is simply the part of an application that your end user will interact with
  2. The backend code lives in the cloud directory. The backend does the behind-the-scenes work in an application. This includes saving things to the database and sending data.

The frontend tells the backend what to do by sending HTTP requests. In our case, this means running cloud functions

Please also note the simplicity of this setup. Three HTML files represent the three pages in this application. Our whole backend is a single file!

In Step 2 we will take a brief look at the frontend code- that is, the public directory. In Step 3 we move to the backend.

Step 1 - Preparing the files

As mentioned in the prerequisites, you should have a fresh project on Back4App created AND your CLI tool configured

Before visiting any of the code, you’ll have to have it downloaded and ready. In this step we do just that. Please note that you will run several commands on your command line. I will give you each of them to copy and run. If you feel confused during this step, don’t worry; this is just the process necessary to connect a Back4App app to a project I have on git. It is not important to know what’s going on.

In this step we:

  1. Initialize a local directory with your Back4App project using the cli
  2. Pull the example project files into this directory using .git

Initialization with Back4App

On your command line run

1
b4a new

You should be prompted:

1
2
Would you like to create a new app, or add Cloud Code to an existing app?
Type "(n)ew" or "(e)xisting":

Go with “e” for existing. Then select your application that you created from the list. Next, you’ll be asked to name the directory where the code will be installed. You can just hit ‘enter’ if you don’t have a preference. For the sake of this project, I will assume the directory is called “ticketlister”. Finally, when asked:

1
2
3
Directory Name:
You can either set up a blank project or download the current deployed Cloud Code
Please type "(b)lank" if you wish to setup a blank project, otherwise press ENTER

Just hit enter (do NOT hit blank). When this command returns, you can cd into the new directory. You should see two directories, one called “cloud” the other called public”.

Your entire output should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ b4a new
Would you like to create a new app, or add Cloud Code to an existing app?
Type "(n)ew" or "(e)xisting": e
1: ticketlister
Select an App to add to config: 11
Please enter the name of the folder where we can download the latest deployed
Cloud Code for your app "ticketlister"

Directory Name: 
You can either set up a blank project or download the current deployed Cloud Code
Please type "(b)lank" if you wish to setup a blank project, otherwise press ENTER: 
Successfully configured email for current project to: "[email protected]"
Your Cloud Code has been created at /tmp/ticketlister.

This includes a "Hello world" cloud function, so once you deploy,
you can test that it works, with the printed curl command.

Next, you might want to deploy this code with:

	cd /tmp/ticketlister
	b4a deploy

Once deployed you can test that it works by running:
curl -X POST \
 -H "X-Parse-Application-Id: Ivy4QAJQuAjDhpqQ2D3MCR4jlrCvDcVVH6yom1kk" \
 -H "X-Parse-REST-API-Key: yLgPHNEnt0jnzWy9BYt6ZCWHqmsWRyvCfsmqrvuS" \
 -H "Content-Type: application/json" \
 -d "{}" \
 https://parseapi.back4app.com/functions/hello

$ cd ticketlister 
$ ls
cloud  public

Syncing the app with the project files

In addition to the cloud and public folders, there will be two files in your directory:

  • .parse.local
  • .parse.project

These hold data pertaining to the Back4App project. Everything else should be overwritten with the existing project files from the repo. The following is the easiest way to do this:

1
2
3
4
5
cd ticketlister
git init
git remote add origin https://github.com/back4app/back4app-ticketlister
git fetch origin
git checkout --force -b  master --track origin/master

If everything has worked, you should now be set with the following files:

$ ls -R
README.md         cloud             index.js          package-lock.json package.json      public

./cloud:
main.js

./public:
css         index.html  js          login.html  signup.html

./public/css:
bootstrap.min.css signin.css

./public/js:
main.js   parse.js  signin.js signup.js

Don’t worry- that was the hard part! Now we can focus on the project.

Step 2 - The Frontend

As a reminder, the frontend code for this app lives in the public directory (see Step 0). To keep things relatively simple, I opted not to use a frontend framework like React, Angular, or Vue. This way, there are no external dependencies or builds.

The project does use HTML5 Web Components. These are supported natively in the browser. They help encapsulate the functionality of different parts of the user interface. They allow the developer to declare new HTML elements (think ‘<p>’). Otherwise, they really just use plain-old JavaScript.

In the public/js directory, there are 4 JavaScript files:

$ ls public/js
# main.js   parse.js  signin.js signup.js
  1. main.js is the code loaded by the main page, index.html. This page is where users list tickets etc.
  2. signup.js is the code loaded by the signup page, signup.html
  3. signin.js is the code loaded by the signin page, login.html
  4. parse.js is a simple file that all the pages use. It creates the connection to the backend. This is the only file you will need to edit and the project will not work unless you do!
Adding your Back4App credentials

First you’ll need to grab your Application ID and your JavaScript Key from your Back4App project. After logging in to Back4App, select your project. Then click App Settings on the left-hand side, and select Security & Keys.

Server Settings

You should see several keys displayed. Grab the Application ID and JavaScript Key and keep them handy.

Finally, open up public/js/parse.js and place each of the strings in the proper place. Remember to make sure the serverURL is https://parseapi.back4app.com.

1
2
3
4
5
6
7
// PART 1: Put your APP ID, JS Key, and SERVER URL
Parse.initialize(
  '', // YOUR APP ID
  '' // YOUR Javascript  KEY
);
// YOUR SERVER URL
Parse.serverURL = 'https://parseapi.back4app.com';

The application now can communicate with the server!

A shallow dive into the code.

Though all of the code in this project is outside the scope of this guide, I encourage you to browse each of the files. Nothing is to complex, and I’d like to take a quick minute to give a 1,000-foot view.

  • This project uses HTML5 Web Components to encapsulate each logical section of the interace.
  • The important markup in the HTML files resides within the html <template> tags. This is how we describe the layout
  • The “functionality” of the application occurs in the JavaScript files. This is where the app describes what to do when a form is submitted, or a button clicked etc.

For example, take the login component. The markup (public/login.html) looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<template id="signin-template">
  <style>
    @import 'css/signin.css';
    @import 'css/bootstrap.min.css';
  </style>
  <div class="signin-wrapper text-center">
    <form class="auth-form">
      <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input
        type="email"
        id="inputEmail"
        class="form-control"
        placeholder="Email address"
        required=""
        autofocus=""
      />
      <label for="inputPassword" class="sr-only">Password</label>
      <input
        type="password"
        id="inputPassword"
        class="form-control"
        placeholder="Password"
        required=""
      />
      <button class="btn btn-lg btn-primary btn-block" type="submit">
        Sign in
      </button>
      <div class="text-center"><a href="/signup.html"> Sign Up</a></div>
    </form>
  </div>
</template>
<!-- This tag below simply tells the browser to render the component we declared above -->
<login-form></login-form>

And the functionality appears in the JavaScript file (public/signin.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Code above ^
    // When the code is ready, listen for the form to be submitted. When it is,
    //  call the 'onSubmit' method
    connectedCallback() {
      const form = this.shadowRoot.querySelector('form');
      form.addEventListener('submit', this.onSubmit.bind(this), false);
    }
  // Obtain the email and password from the markup inputs
    onSubmit(e) {
      e.preventDefault();
      //   Get inputs
      const email = this.shadowRoot.querySelector('#inputEmail').value;
      const password = this.shadowRoot.querySelector('#inputPassword').value;
      this.login(email, password);
    }
  // Send a request to the backend, attempting to login. If the login
  //  is successful, go to the index.html page. Otherwise, give the user
  // an alert explaining what went wrong
    login(email, password) {
      // Add login method here
      Parse.User.logIn(email, password)
        .then(user => {
          window.location.href = 'index.html';
        })
        .catch(e => {
          alert(e.message);
        });
    }
    // More code below

The whole application takes this general structure. Keep an eye out for the times the frontend talks to the backend like this: (public/js/main.js).

In the next step, we’ll look into how these functions are declared.

Step 3 - The Backend

The entire backend will live in cloud/main.js, the Cloud Code functions file (see Step 0). It consists of a very modest amount of code, attesting to how much we can accomplish for so little with Back4App.

Part of the app (creating events that tickets can list under) will simply use the Back4App dashboard. This awesome functionality comes with our project, so no need to reinvent the wheel!

Again, examining each line of code is outside our scope. We will, however, take another broad view of how the code works.

  • You declare Cloud Functions in the cloud/main.js file. These functions can be invoked from the frontend (see Step 2). For more information on Cloud Functions, see the documentation.
  • Furthermore, these Cloud Functions are actually run on a Parse Server. This guide discusses some of the syntax that’s used, so it may be helpful to have a look.

More specifically, the functions we define our:

  1. ‘user:signup’ - Code for handling user signup flow
  2. ‘tickets:list’ - Code for retrieving all listed tickets
  3. ‘tickets:create’ - Code for creating a new ticket
  4. ‘events:list’ - Code for listing all events

And one last code note: I added a simple method towards the top of the file:

1
2
3
const requireAuth = user => {
  if (!user) throw new Error('User must be authenticated!');
};

Certain Cloud Functions require a user to be logged in. By calling this function with the user property of the request, we ensure that no one can make unauthorized requests.

I highly encourage you to skim the rest of the functions to see how they work. Now that you know what they do, we can deploy!

Step 4 - Deploying

We’ve buttoned up all the code, and now the app can be deployed to Back4App. The following command will upload all public and cloud files:

1
b4a deploy

Local website hosting

To obtain a public domain to view your uploaded web app, you will need to switch on Web Hosting from your Back4App dashboard.

First, open “Server Settings” on the left side of the dashboard:

Server Settings

Next, click the “Settings” link under “Web Hosting and Live Query”

Web Hosting Settings

And finally, check “Activate Back4App Hosting”. You’ll need to pick a unique subdomain; I already claimed ticketlister for this project so pick something different. Optionally, you can configure a domain you own to “point” to this back4app domain. I did this for http://ticketlister.koptional.com and my settings look like this:

Custom Domain Settings

Please note the text below “Custom Domain”, if you plan to launch off your own website.

If you complete this step properly, you can go to your domain and use the app. If you don’t have a custom domain, just open http://<YOUR_SUBDOMAIN>.back4app.io, where YOUR_SUBDOMAIN is the name you just selected.

Step 5 - Usage and the Dashboard

Using the app and listing tickets

To start listing tickets, you’ll have to create an event from the admin dashboard on Back4App.

Go to the data browser, and create an ‘Event’ class. Add the columns ‘name’ (a string), and ‘when’ (a date). Then you can add an event directly. Remember to fill out all columns. It should look something like this:

Adding Name

Adding When

Creating Event

Now, on your web app, you can log in and list a ticket with that event.

Listing Ticket

This admin functionality that comes with Parse / Back4App is another shortcut that decreases your workload.

Conclusion

Creating a web application with a backend is something that often takes weeks and months. We took advantage of Back4App’s powerful infrastructure and the Parse SDK to launch one much quicker. Using this approach for any application allows you to build amazing things without wasting time.