📜 ⬆️ ⬇️

Single Page Application in Cloud Storage

Single page application

We have already written about how our cloud storage can be used as a platform for hosting static sites ( 1 and 2 ). Today we will talk about how modern sites can be placed on the basis of the repository, which are based on the Single Page Application (SPA) approach that is popular and relevant today.


SPA as an approach


')
SPA abbreviation stands for "single page application" ("one-page application"). In the narrow sense, it is used to refer to a one-page site that runs directly on the client in the browser. In a broader sense, SPA (sometimes also used the abbreviation SPI - “single page interface”) means a whole approach to web development, which is becoming increasingly widespread today. What is the meaning of this approach and why is it becoming more and more popular?

Let's start a little from afar. Today, the most common type of sites are, of course, dynamic sites, in which pages are generated on the server side. With all the obvious convenience for developers (each request creates a page from scratch), such sites sometimes represent a real headache for customers. This is not a complete list of the inconveniences that they have to face:



Often, the described problems are solved in the following way: pages are still generated on the server side, but on the client side, small JavaScript scripts are executed, with the help of which you can, for example, perform form validation before it is sent to the server. The solution at first glance is not bad, but it also has flaws:



Of course, you can live with all this. But the SPA approach in many cases turns out to be much more effective.

From the point of view of this approach, a site is understood not as a set of pages, but as a set of states of the same HTML page. When the state changes, asynchronous loading of new content occurs without reloading the page itself.

SPA is not a website in the classical sense, but an application that runs on the client in the browser. Therefore, from the user's point of view, there are almost no problems with speed even with a slow or unstable connection to the Internet (for example, when viewing a site from a mobile device). High speed of work is also ensured due to the fact that not the markup now comes from the server to the client, but the data (mainly in JSON format), and their size is small.

Recently, a lot of interesting technological solutions and services have appeared, significantly simplifying the creation and use of SPA. Consider some of them in more detail.

BAAS (Backend as a Service)



Technologies that allow drawing the interface on the client side and interact with the server only by sending requests without reloading the page have been around for a long time. For example, the XMLHttpRequest API appeared back in 2000. But the use of these technologies was difficult: it was necessary to rewrite the backend, which implements the functions of authorizing requests and accessing data.

Today, everything has become much easier thanks to the emergence of numerous BaaS-services. The abbreviation BaaS means Backend as a Service. BaaS services provide web application developers with a ready-made server infrastructure (located, as a rule, in the cloud). Thanks to them, you can save time (and often more money) to write server code and focus on improving the application itself and developing its functionality. Using BaaS, you can connect any backend with any set of functions to an application or website — simply add the appropriate library to the page.

An example is the MongoLab service, which allows you to connect a MongoDB cloud database to web applications and sites.

Another interesting example is FireBase . This service is a cloud database and API for realtime applications. With it, you can, in particular, organize data exchange between the client and the server in real time: you just need to connect a JavaScript library to the page and configure events for data changes. On the basis of FireBase, it is easy to implement, for example, chat or user activity tape.

Among the interesting and noteworthy BaaS-services is also worth highlighting:



You can also find a brief overview of BaaS services here .

Our cloud storage can also be used as an external backend. With it, you can, for example, integrate file management functionality into web applications and sites.

When using storage as an external backend, special attention should be paid to two key points: authentication and work with content. The authentication key (token) can be obtained using a request to auth.selcdn.ru .

Then it will need to be specified as the value of the X-Auth-Token header in all requests for working with data. Answers to these requests will include an Access-Control-Allow-Origin header with a value of "*", allowing access to the repository from any external domain.

As an example of a web application using the repository API, we can cite our photo gallery (we already wrote about it; see also the repository on GitHub ).

HTML5 History API



Each page of a dynamic site has its own URL. SPA is arranged so that they can change the state of the page without changing the URL. But in this case there is a problem: the user will not be able to save the link and then return to the previously visited section. It can be solved in several ways.

First, you can use a hash fragment (the part of the link that comes after the “#” character). In the hash fragment is placed the "virtual" address of the page, which can restore the previous state. If the user reloads the page, the JavaScript code, after reading the hash value, loads the necessary data and displays the corresponding section. This option is used on many sites, but it should be noted that similar URLs (for example, “ example.com/base/# ! / Section1 / page2”) do not look very natural. In addition, they consist of two entities: a “real” address, at which a page is requested from a web server, and a “virtual” one, which denotes a logical partition.

Secondly, you can use the HTML5 History API (see also the article on Habré ). The History API allows you to completely change the URL of a page within the current domain without reloading it. In browsers that support this API, there are no differences between the URLs used when loading the page and the URLs specified from JavaScript.

Calls to the History API functions are also associated with the native browser buttons "Forward" and "Back" and history: when you click the "Back" button, the browser raises the popstate event, which can be processed in JavaScript code and display the previous section. See how it works, for example, here .

In order for the site to use the URL scheme described, the web server must be properly configured. It is necessary to make so that instead of non-existent pages the main SPA page is given - usually it is index.html. In this case, the client browser will load JavaScript, which already draws the necessary site file based on the current page address.

In the nginx settings, this is written as:

 location / {rewrite. * /index.html;  }


If the SPA is hosted on services like GitHub Pages or our repository, then the settings should be set via the control panel.

Search engine optimization



SPA indexing by search engines is a separate issue. If the site is completely generated on the client side, then it will be poorly indexed, although recently there have been improvements in this regard: bots gradually begin to perform JavaScript when indexing.

One of the ways to solve this problem is the following: pages snapshots are generated specifically for bots. Generate pages should be different depending on whether the HTML5 History API is used or not.

In the case of using hash fragments, Google and Yandex offer the same approach: to separate the “real” and “virtual” addresses, use “#!” Instead of “#”; Search bots, having seen the link with this delimiter, will use the special query parameter “_escaped_fragment_” in the URL and place in it the part of the address following after the hash.

The web server must process such requests in a special way and return full HTML pages so that bots can index them. (The need for this arises due to the fact that the part of the URL after the “#” according to the standard is not part of the HTTP request.) It is also recommended to use a special meta tag (see the links above) because Some pages may not contain links with "#!".

If full-fledged URLs are used for addressing, then making the site indexed is even simpler: it is enough to generate a page on the server corresponding to the specified address. A bot visiting the site will receive a page with content and successfully index it.

If the site is opened in a browser, the page will first be displayed in accordance with the HTML markup, and then JavaScript will enter into action; with further links, the page will not be reloaded. This behavior can be realized by intercepting the events of clicking on links and canceling their native behavior. In this case, the bot will follow the link (the “href” attribute), and we will be able to control all the transitions, processing the event as we need.

Note also that this approach allows you to optimize the site loading speed: modern browsers render HTML from the server much faster, and loading JavaScript scripts, their parsing and page rendering through the DOM usually takes longer.

How to generate an HTML page with only JavaScript code that works directly with the DOM? This can be done in several ways.

First, you can install PhantomJS (this is the so-called “headless” WebKit-based browser, managed via an API) and configure it to generate snapshots of pages (see the practical example here ).

Secondly, you can use the prerender tool or the Prerenderer.io service, which are also based on PhantomJS.

Thirdly, in some modern frameworks (for example, DerbyJS and React ) this function is already implemented (see also the example here: react-server-example ).

SPA accommodation



In the modern Internet there are many sites where you can place SPA. Consider the most popular ones.

Dropbox



The easiest option is to place the SPA in Dropbox . To do this, you need to create a directory for the SPA in the Dropbox public directory, place all the necessary files into it, then select the index.html file and open the context menu by clicking the right mouse button. In the menu, select the item “Dropbox → Share link.” After that, the link will be created and copied to the clipboard, on which the application will be available through the browser.
Recently, attempts have been made to expand the possibilities for placing sites on Dropbox (you can read about this, for example, here ). However, they do not solve the main problem: Dropbox has quite severe (up to complete blocking) traffic restrictions on public links. Therefore, the described option can be recommended except for demonstration of SPA to friends and colleagues.

Github pages



GitHub Pages is a free platform for hosting static sites and SPA. To place the SPA on GitHub Pages, you need to create a repository for it on GitHub and place the static files in the gh-pages branch for Project Pages or in the master branch for User / Organization Pages. All changes will need to be committed to this repository. More help is available in the official documentation .

Bit balloon



Bit Balloon is a new service, but already quite popular.
Each registered user is provided with 10 MB of free disk space. To place a SPA on it, simply download all the necessary files. The service will automatically minify JS, HTML and CSS, as well as connect the CDN.

Premium account costs $ 5 per month. For owners of paid accounts, various additional options are available - in particular, attaching your own domains and connecting various external services.

Selectel storage



Our cloud storage is a convenient place for hosting SPA. In general, the procedure for placing SPA almost does not differ from the procedure for placing static sites about which we have already written in one of the previous posts. It includes the following steps:
  1. Creating a public container and attaching a domain: by the link above, everything is described in detail, we will not discuss this in detail.
  2. Customization of special pages: the customization procedure was recently improved by us. We have added another option to customize the processing of non-existent pages (“Error 404: page”). Now you can specify a file that will be displayed when a non-existing page is requested, and you can also set a response code (200 or 404) for it, without redirecting to another URL:


Selectel cloud storage

This allows you to use full URLs (see the section on the History API).

The undoubted advantages of our storage over other sites (including those described above) include low cost and flexible payment system (no fixed tariffs; payment is charged only for the amount of stored data and outgoing traffic - you can count here ), as well as the presence of CDN and flexible system of settings for container parameters and exported files.

Conclusion



In this article, we talked about another aspect of using our repository as a platform for hosting single-page sites. We hope that it will be useful to you.
If you already use our repository to host the SPA, share your experience and impressions. All your wishes and suggestions will be taken into account in future work.

Readers who for one reason or another can not leave comments here are invited to our blog .

Source: https://habr.com/ru/post/246019/


All Articles