1.1 Introducing Google's Firebase - leveraging basic skills to deliver powerful IT systems
Tags: beginners, programming, javascript, firebase
Published: 2021-10-11 13:20:00

Last reviewed : Sep 2022

### Introduction ###

This post is intended for complete IT beginners. It covers all the things I'd have liked to know myself when I first started to tinker with websites and databases. If you have a bit more experience and just want to see why I'm so enthusiastic about Firebase, you might find it useful to have a look at the more technical links in the [Index](https://ngatesystems.com/waypointsindex) to this post series.

But if you're new to the IT world and eager to find out what it has to offer, please read on. Perhaps you're still at school, or older and considering a change of career, or maybe retired and just curious -  whatever -  I imagine that you may be feeling rather confused by what you've found. Modern IT practices are a perfect jungle of tools, technologies and techniques. Worse still, this is a jungle that is evolving at a dizzying rate. Where on earth should you start?

Amidst this swirling chaos however, three heavyweight IT services stand out -  Google's Cloud Platform (GCP), Amazon's Web Services (AWS) and Microsoft's Azure system. 

All of these provide general-purpose facilities that you can use to develop systems at any conceivable scale. But of the three, the Google Cloud platform and its Firebase application development system are the services that I want to concentrate on.

The main reason is that this allows you to get started for free! (in fact none of the tools and techniques I describe here require financial outlay)! Google will certainly charge you if your system becomes wildly popular, but their budget allowances are extremely generous and by that time you won't care! [For a cross-sight on my recommendation, see [Andrew Didinchuk's](https://appliedarchitect.medium.com/google-cloud-platform-gcp-vs-amazon-web-services-aws-for-the-hobbyist-e79326a8177) comparison between GCP and AWS]

What you **will** need to invest, however, is quite a lot of your personal time because getting your head around even the basic technologies can be intellectually demanding. IT is a serious engineering discipline and, as a developer, you carry a lot of responsibility. However, I think you'll find that this post and its follow-ups take things at a very gentle pace and I hope it should be possible for anyone to follow it with nothing more than a modicum of determination. 

### Objectives ###

Let's start by clarifying the end goal of this post and the reasoning behind the approach I'm going to recommend. 

The assumption is that you want to do something useful rather than just learn a bag of new tricks, so let's agree that your aim is to develop software that will read some information into a computer, process it in some purposeful way and then display the results on a screen. Oh, and additionally, you'd like anyone, anywhere to be able to use your handiwork. Should be easy enough...

In the world of IT, there are currently myriad ways of achieving this simple task and we'd all be exhausted if I tried to go through these in detail. Let me simply state, therefore, that in my experience the simplest option is to use an internet browser such as Chrome or Safari as the "launchpad" for your application. This may seem odd - isn't everybody using freestanding "apps" on their mobile phones?  Here's the reason: you want your application to be available to users anywhere in the world, not just on their phones but on every other conceivable device as well - laptop, tablet, desktop computer, or whatever. Browsers provide an excellent way of insulating your application from differences in hardware and operating systems. Additionally, they give you a sophisticated and highly practical environment to support the logic of your application. Finally, when it comes to sharing the application and its data with your users, browsers are already positioned on the internet, whose whole purpose after all is to facilitate the sharing of information. Let me remind that you that major operations such as Amazon and Facebook are very happy to use web browsers as platforms for their systems.

So, the route that I suggest is one that leads to what is now generally known as a "webapp", a piece of software that is activated by simply entering the webapp's "name" into a web-browser. This webapp will be capable of maintaining persistent data stores ("databases") and will provide security for this data via a signon feature. 

What skills will you need in order to use Firebase to develop a webapp? In this initial post. I can only sketch out the elements in general terms. But each component is chosen to deliver positive returns and is designed to help you build unerringly towards your goal. Be assured that I will be taking care that at each stage you'll only have to learn what you strictly need to know.  Here's the list:

* HTML : Hypertext Markup Language - the "language" used to tell a browser how to format a webapp's output on a computer screen
* An IDE - Interactive Development Environment - the editing tool you'll use to create your code - Microsoft's VSCode is the IDE I recommend.
* Javascript - the programming language used to add logic to an HTML webapp.
* Browser System Tools - the tools used to debug an HTML/Javascript webapp.
* Google Firebase - a component of Google Cloud Platform - an environment that lets you share your webapp and its data over the Internet.

Each of these technologies deserves a post (or maybe a book) in its own right. But for now, I'm only going to fully document the Google Firebase bit - see the list of links at the bottom of this post. For now, because subjects like HTML and Javascript are all well-described elsewhere, I think it's sufficient for me just to provide simple introductions to get you on the right track. You'll find that these introductions all contain pointers on where you should go to find more information.

OK, buckle up, here we go ....

###  HTML (Hypertext Markup Language) ###

You're developing software to run in a web browser. Web browsers run on simple "markup" codes giving directions on how to display text - a simple arrangement, but one that is capable of delivering immensely powerful results. The markup codes surround your text and specify both position and appearance. You can create a sample by simply typing the instructions into a text file in a simple editor such as Microsoft's Notepad. Try this simple exercise:

Type the following line into your favourite text editor (eg Microsoft's Notepad utility) and then save it as a file with an HTML extension (eg "myfirstapp.html"):
```HTML
<p>Hello there</p>
```
Now use your computer's file-storage tool (eg Microsoft's File Explorer) to locate the file and launch it in your computer's default web browser. The browser should respond by displaying a screen displaying the words "Hello there". Congratulations, you've written your first webapp (albeit one that nobody but you can see, but we'll fix that later). 

The `<p>` and `</p>` codes (or "tags" to give them their technical name) in the example above are HTML instructions that tell the browser that the text they enclose is to be displayed as a paragraph (ie it will be displayed on a fresh line in the page).  Now google for information about `<p>`. You'll find a mountain of tutorials and advice about learning HTML (an excellent place to start would be Mozilla.org's [Getting started with the web](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web) site. The w3schools sites are also particularly useful because they allow you experiment on-line). Great - you're on your way to becoming a software engineer.

###  The IDE (Interactive Development Environment) ###

You may just be getting the sense that developing your webapp is going to involve a lot of typing. Your webapp will, indeed, require you to enter hundreds, perhaps thousands, of lines of "code". You could, as in the example above, just type these lines into a simple text-editor but this would be a bad idea. Browsers are unforgiving beasts and any spelling errors in your code will result in the spectacular failure of your intentions. You need a text editor that will keep an eye on code as you enter it, that will format and highlight it in ways that assist your control of its structure, and perhaps will even save you some of the typing by making helpful suggestions. Numerous IDEs are available, but the one I recommend is Microsoft's VSCode - free to install and very widely used. I've used a few others in my time, but overall this has been the best and it has saved me endless trouble. Once again there's a lot to learn, but Microsoft provides excellent online documentation

###  Javascript ###

You're going to need a language to represent the logic of your webapp - the instructions that receive information from your users and then process and deploy it in useful ways. The native language that drives a webapp is called Javascript and you will find that this is both easy to learn and immensely powerful in action. Its special ability as a browser language is that it is able to both read and write to the data structures described in the HTML sections of your webapp - in plain terms, it can both read and write directly to the screen. This is possible because the rigorous nature of an HTML script means that a browser can construct a "model" of the screen layout. This takes the form of a tree structure called the Domain Object Model (DOM). Within the DOM, the various branches and leaves are all individually addressable by Javascript. Here's an example. Take the myfirstapp.html file introduced above and edit it as follows:
```javascript
<p id="test">Hello there</p>
<script>
let hourOfDay = (new Date()).getHours(); // 0-23
if (hourOfDay < 11) {
    document.getElementById('test').style.color = "blue";
} else {
    document.getElementById('test').style.color = "red";
}
</script>
```
If you now rerun the file before you've had your lunch (to be specific, before 12 noon on any given day), the output will now appear in blue rather than default black as in the original version. After lunch, output will appear in red. Congratulations, you've coded your first "intelligent" webapp. 

The lines between the HTML `<script>` and `</script>` tags are your first bit of Javascript code. The line starting `hourOfDay =` creates a "variable" containing a "Date" "object" for the run time (actually, the precise time in milliseconds since 1 January 1970 UTC). The `.getHours` reference is a "method" that extracts from the Date object a number between 0 and 23 representing the hour of the day of your particular run. 

You'll probably have noticed that the `<p>` tag in the first line of the original version of the file has been altered by the addition of an `'id='` section. This has "labelled" the tag with a unique string ("test" in this instance). The clever bit is the `document.getElementById('test')` instruction that enables Javascript to alter the "style" of the 'test' `<p>` tag. 

"Style" has lots of "properties". In this case, we change the "colour" style of the text. However, other styles are available to do much more useful things. We could for example use "style" to change the position of the paragraph on the page. The web will give you lots of advice about all of this. 

But since a good grasp of Javascript and programming technique generally is going to be the key to your success as a system developer, this is one area where I think you need to turn your back on the web as a source of information. Googling at random in this area will tend to increase your confusion (and I speak from personal experience). What you need here is a good book. The one I recommend is Marijn Haverbeke's "Eloquent Javascript". 

Read this online if you must (and actually this is quite handy for copying code samples - you can find the latest edition at https://eloquentjavascript.net/), but there's nothing like a well-written book with physical pages upon which you can scribble for grounding your education. Secondhand is fine at this stage and will probably be the best (and only) investment you can make at present. Haverbeke will do a far better job at explaining the "object", "method", "function", "style" concepts introduced above than anything I can hope to achieve. 

###  Browser System Tools ###

Inevitably, your HTML and Javascript code will contain errors - screen layouts will not deliver the effects that you intended (to put it mildly!) and your logic will be faulty. You need a tool to help you investigate these problems.

The good news is that almost every browser comes with a built-in "debugger" that enables you to inspect the browser's interpretation of screen layout definitions and to check the results of the execution of Javascript instructions. In the case of Google Chrome, for example, the debugger is called "Developer Tools" and is accessed by simply right-clicking on the browser screen and selecting "inspect" from the popup thus revealed. The bad news is that on first acquaintance, the debugger window appears to be quite incomprehensible. Let me assure you, however, that once you've got the hang of it, this tool is probably the finest piece of user-interface design you will ever encounter. It makes debugging a webapp a positive delight. Describing it in detail would take me some time - and this just isn't the right moment - but perhaps I can quickly give you a taste of its power. 

The debugger is capable of inspecting many aspects of a webapp's internals -  layout, network activity, performance and so on - but the easiest area to demonstrate is its ability to monitor the operation of Javascript code. So, launch your myfirstapp.html script again and start the debugger as above. Now click the tab labelled "Sources" and note how the code of the application is displayed in the centre panel. 

Now create a "breakpoint" on the first line of code (`hourOfDay =  ...`) by clicking just to the left of the line - a blue highlight should now be displayed here. What this has done is "instrument" the application, ready for debugging. When you re-run the file, the browser will watch out for your breakpoint and will halt execution when it reaches it. You can then start inspecting the values that have been assigned to the program's variables. 

To see this in action, rerun the file and note how the browser now displays a "paused for debugging" message and observe how the whole debug point is now highlighted in blue. See screenshot below:

![Chrome debugger screenshot](https://bablite.web.app/assets/images/postpics/pic1.png)

At this point, you're probably most interested in the value that's been assigned to the "hourOfDay" variable, but note that, while the application has paused at the `hourOfDay = ..` line, it hasn't actually executed it yet, so click the "step over next function" icon in the "paused for debugging" message (the one at the extreme rhs of the message) and observe the blue highlight in the source advance to the `if (hourOfDay < 11 ....` line. Now, if you mouse over the `hourOfDay` field, you will see a tooltip appear, displaying its value. Click the "step over next function" icon again and you will see control pass to the appropriate `document.getElementById(..` line as selected by the `if` test. Click again and you will see the colour of the "Hello there" message (presently displayed in default black) change to the appropriate colour. 

When I first saw this in action I was almost speechless - it was just like opening the back of a Swiss watch and seeing, for the first time, the intricate workings within! These days I almost look forward to getting errors in my code because it's such fun tracking them down with the "Inspector". To find out more about this tool I suggest you have a look at the [Google devtools](https://developer.chrome.com/docs/devtools/overview/) overview documentation.

###  Google's Firebase ###

This is the "big one". So far, everything I've described has been related to development in a "local" environment using code and tools on your own computer. But as promised, the aim is to make your webapp available to anyone anywhere. In principle, you could turn your own computer into a device that would achieve this end but the process would be expensive and extremely complicated. In the past, you would normally have moved your webapp onto the web by opening an account with an "Internet Service Provider" (ISP) - a commercial operation such as Hostpapa or 123Reg. Your ISP, in exchange for a certain amount of your hard-earned cash, would provide storage on a "server" computer to "host" your webapp and enable you to assign it a unique "url" by means of which your users could access it.

In the past, there was little or no alternative, but with the development of the Firebase, Google (and to be fair, other competitors) have blasted a hole through this whole complex and expensive arrangement. Firebase enables you to "deploy" a locally-developed webapp to the cloud under a url that Google will provide for free. 

But there's much more to Firebase than just a free url. I've not talked much about data so far, but it's almost certain that your webapp will need to be associated with some sort of "database" - a reliable store where users can safely deposit their data and from which they can also access public data maintained by your webapp. In the past, your ISP would have again been happy to provide these database facilities as part of their service package. But at this point, you would have found that this was just the beginning of a whole new chapter of misfortune. For a start you'd have had to learn the language used to specify and access a database - most likely something called SQL (Structured Query Language). Then, as if this wasn't enough, you'd find that you also needed to learn a new programming language to launch SQL commands. SQL can only be accessed directly from software running on a server and so you're likely to find yourself steered towards a language like PHP or Python rather than the Javascript that you've been learning. Many people would give up at this point.

A bit of history here - but it's relevant because it sets what I have to say next into context. If I'd decided to write a webapp even as recently as 10 years ago, I might have written **the whole thing** in PHP (which stands for "Personal Home Pages"). PHP was originally conceived as a way of generating the HTML for the browser's input/output function. Combining this with server-based processing tasks seemed like a good idea, so, instead of launching an.html file in your browser, you'd have launched a PHP file whose job was to "echo" HTML back to your browser. Fine in theory but, in practice, things didn't work too well. Complex local interaction such as input validation or the navigation of a hierarchy of screens becomes fiendishly complex when it has to be performed using remotely-hosted logic. So it was at this point that Javascript logic, running directly in the browser, started to come more forcefully into the picture. The story since has been the inexorable rise of Javascript.

Google's Firebase service has brought this story to its logical conclusion. When using Firebase you can simply forget about all those PHP and SQL-server technologies. A key component of Firebase is a data management service called Firestore and, wonder of wonders, the commands you use to read and write data to/from a Firestore "database" can be launched directly from a browser using pure Javascript. When I discovered this, I honestly thought all my birthdays had come at once! Certainly, the task of learning to use Firestore itself isn't easy (just initialising a Firebase project and deploying it into the Cloud itself introduces some curious and taxing novelties), but at least you will generally be building on skills you've already acquired.

A particular challenge (and one that you'd have had to face up to whatever server database arrangements you might have used) is that reading from and writing to a database in Javascript is intrinsically difficult. This is because input and output from remote devices via Javascript is handled "asynchronously". In plain speak, this means that when you start such an operation, control passes on to the rest of your program without waiting for the result. The idea is to ensure that programs can be written in a way that ensures that users of a Javascript application don't find their program "freezing". But this arrangement requires the program designer to structure things carefully so that instructions only fire when things are ready for them. In the past, this would have entailed some considerable complication (we used arrangements known as "callbacks" which had the effect of making code rather difficult to follow). With growing recognition of the advantages of using Javascript as a mainstream development platform, however, new syntax has been added to the language and callbacks are now a thing of the past. Here's a sample of firestore database interaction code:
```javascript
async function buildTextTypesArray() {
  let textTypesSnapshot = await db.collection("textTypes").get();
  textTypesSnapshot.forEach((doc) => {
    textTypes[doc.data().textType] = { 
      textColor: doc.data().textColor, 
      textHeader: doc.data().textHeader };
  });
}
``` 
In the above snippet, `buildTextTypesArray()` is a function that creates a local copy of Text documents stored in a Firestore database. Texts are associated with characteristics like "color" and "header" and, because these details are referenced frequently, it's convenient to hold them locally. To build my local store at program-initiation time, all I have to do is launch the instruction `buildTextTypesArray()`. Inside this function, the Firestore request is launched by a request to a Firestore library function called `get()`. As indicated above, however, when `get()` is called, its results return asynchronously, so how can I arrange things so that the succeeding `.forEach((doc) => { instruction` - whose purpose is to chew its way through the list of Text documents returned by the .get() - doesn't run before the result of the `get()` actually turns up? 

The answer is provided by the "await" keyword sitting in front of the `get()` call (one of those recent additions to the Javascript language).  At this point please accept my assurances, if you're not yet familiar with Javascript syntax that all those weird brackets, => symbols and so on will one day become second nature to you. The whole point I'd like you to take away from this example is that the code produced to deliver a Javascript and Firestore project is concise, readable and, courtesy of the browser system tools, easily debugged.

A word of warning here. The technologies I'm describing here are still very raw and subject to ongoing development - in some senses, modern IT technology resembles a sort of Darwinian struggle set on "fast forward". Once again "Eloquent Javascript" is likely to be a great help. Sadly, at the time of writing, the definitive book on Firestore remains to be written. But Google's own documentation at https://cloud.google.com/firestore/docs/client/get-firebase should at least get you started.

You might also wonder if there are limitations or drawbacks to the Firebase system. My own experience so far has been "only if your requirements are exceptionally taxing" and you may be assured that I've given things a pretty good test. Because your webapp is anchored inside a browser, you're subject to the general problems attached to a browser, namely that a piece of code may work differently depending on which browser you choose (though this is much less of a concern than it used to be) and some hardware features (eg geo-location) may be unavailable. Also, while Firebase enables you to avoid having to learn SQL and server-based programming languages, there will be times when old hands will miss the precision and elegance of SQL and the flexibility and power of PHP. Overall, however, I'm happy to live with these irritations in order to have my codebase concentrated in controllable Javascript rather than spread across a number of different platforms and languages. 

I think I should also just say that I've really only scratched the surface as regards the facilities available through Firebase. For example, I've not mentioned the arrangements for securing data within a Firestore database. The first element of this in conventional applications is always to provide some sort of "logon" facility. In my experience, this has always been a major, troublesome, time-consuming task. Firebase reduces the whole tedious business to a simple configuration exercise. Likewise, you may be wondering how your application might be organised to perform heavyweight background tasks without a server. In the Firebase system, these can be assigned to "functions" operating in the Google cloud and programmed, once again, in Javascript. Also, I've not described how you would amend and test an application after it has gone "live". Firebase provides an "emulation" mode of operation in which the whole Firebase setup runs locally on your own equipment. I could say more, but you've probably heard quite enough already.... 

If you'd like to see an example of a Firebase webapp in operation, try out my own testbed development at https://bablite.web.app. Use a dummy email address to register for this if you don't want me to see your real address. I hope you find Scottish Gaelic entertaining!

If you'd like to find out more about Firebase and create a sample webapp yourself, follow the "Beginners Guide" links in the [Index](https://ngatesystems.com/waypointsindex) to this post series.