<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Cochrane on Medium]]></title>
        <description><![CDATA[Stories by Ben Cochrane on Medium]]></description>
        <link>https://medium.com/@bencochrane?source=rss-6b68f4428cb8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h2wN5QhWpcNVc197UnNJrw.jpeg</url>
            <title>Stories by Ben Cochrane on Medium</title>
            <link>https://medium.com/@bencochrane?source=rss-6b68f4428cb8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bencochrane/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to add fast realtime search to your Firebase app with Algolia]]></title>
            <link>https://itnext.io/how-to-add-fast-realtime-search-to-your-firebase-app-with-algolia-2491f7698d52?source=rss-6b68f4428cb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2491f7698d52</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[algolia]]></category>
            <dc:creator><![CDATA[Ben Cochrane]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 04:25:53 GMT</pubDate>
            <atom:updated>2018-10-01T07:54:27.845Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the nicest ways to improve a users experience within your app is to provide full text search across a variety of lists or collections.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGLba63UJtsQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGLba63UJtsQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGLba63UJtsQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/298e7f6e566db7da9dcaca50f497fd3f/href">https://medium.com/media/298e7f6e566db7da9dcaca50f497fd3f/href</a></iframe><p>In this tutorial, I will run through how to implement realtime full-text search with <a href="http://algolia.com/">Algolia</a>, <a href="http://firebase.com/">Firebase</a> functions and <a href="http://firebase.com/">Firestore</a> (Firebase’s new realtime database).</p><p>You might be thinking, hang on — you just said Firestore is a realtime database — why would I need another realtime database to handle full-text search. Good question! The answer is Firestore is great at updating changes to a collection as they happen as it sets up listeners on whatever collection or single object you like. Firestore however isn’t designed to provide super-fast pre-indexed search results using free-text input. That’s where Algolia shines though.</p><p><a href="http://algolia.com/">Algolia is search-as-a-service</a>. In short — it gives your app Google-quick full text search results. Anything you add to Algolia can be searched (even with spelling mistakes like I showed in the video above).</p><p><strong>Overall, the steps to implement Algolia search are:</strong></p><ol><li>Create an Algolia account algolia.com</li><li>Create an index in Algolia (this just means what is the name of the database you would like to search that already exists in your app — in my Firestore database I had an “equipment” collection so I created an “equipment” index in Algolia.</li><li>Create a firebase function that listens for creates and updates in your collection and copy them to Algolia</li><li>Add some items to a Firestore collection to test it out</li><li>Call Algolia on the front end of your app to display the search results</li></ol><p>Let’s go through each of these steps shall we?</p><h3><strong>Step 1: Create an Algolia account</strong></h3><p>Not much else to say here just go to algolia.com and create a free account</p><h3><strong>Step 2: Create an index in Algolia</strong></h3><p>Once you’ve created your account, click Indices on the left hand panel then click “New Index”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ariC67CzJ19tAVj-1f5NIA.png" /><figcaption>Create a new index from the Indices page in Algolia</figcaption></figure><p>Name this index whatever you like, but I keep the index name the same as my Firestore collection name for simplicity.</p><h3><strong>Step 3: Create Firebase functions that listen for create and edits to the collection you want to search on</strong></h3><p>In my case, I want to know when a new piece of equipment gets added or edited. To do this these are the firebase functions I wrote.</p><p><em>Listen to CREATE and EDIT actions on the “equipment” collection in Firestore:</em></p><pre>// this the firebase functions setup code</pre><pre>const functions = require(&#39;firebase-functions&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br>let Promise = require(&#39;promise&#39;);<br>const cors = require(&#39;cors&#39;)({ origin: true });<br>const auth = require(&#39;basic-auth&#39;);<br>const request = require(&#39;request&#39;);<br>const algoliasearch = require(&#39;algoliasearch&#39;);<br>admin.initializeApp(functions.config().firebase);<br>const db = admin.firestore();<br></pre><pre>// listen for creating a piece of equipment in Firestore</pre><pre>exports.addEquipmentToAlgolia = functions.firestore.document(&#39;equipment/{document}&#39;)<br>.onCreate(event =&gt; {</pre><pre>console.log(&#39;ADD EQUIP EVENT IS&#39;, event);</pre><pre>const active = event.data.data().active === true ? &quot;true&quot; : &quot;false&quot;</pre><pre>const data = {<br>  objectID: event.params.document,<br>  description: event.data.data().description, <br>  category: event.data.data().category,<br>  category_id: event.data.data().category_id,<br>  flat_fee: event.data.data().flat_fee,<br>  group: event.data.data().group,<br>  hourly: event.data.data().hourly,<br>  active: active,<br>  daily: event.data.data().daily,<br>  weekly: event.data.data().weekly,<br>  monthly: event.data.data().monthly,<br>  bulkItem: event.data.data().bulkItem <br> };</pre><pre>return addToAlgolia(data, &#39;equipment&#39;)<br> .then(res =&gt; console.log(&#39;SUCCESS ALGOLIA equipment ADD&#39;, res))<br> .catch(err =&gt; console.log(&#39;ERROR ALGOLIA equipment ADD&#39;, err));<br>});</pre><pre>// listen for editing a piece of equipment in Firestore</pre><pre>exports.editEquipmentToAlgolia = functions.firestore.document(&#39;equipment/{document}&#39;)<br>.onUpdate(event =&gt; {</pre><pre>console.log(&#39;edit event&#39;, event.data.data())</pre><pre>const active = event.data.data().active === true ? &quot;true&quot; : &quot;false&quot;</pre><pre>const data = {<br>  objectID: event.params.document,<br>  description: event.data.data().description, <br>  category: event.data.data().category,<br>  category_id: event.data.data().category_id,<br>  flat_fee: event.data.data().flat_fee,<br>  group: event.data.data().group,<br>  hourly: event.data.data().hourly,<br>  active: active,<br>  bundleItem: event.data.data().bundleItem,<br>  daily: event.data.data().daily,<br>  weekly: event.data.data().weekly,<br>  monthly: event.data.data().monthly,<br>  bulkItem: event.data.data().bulkItem <br> };</pre><pre>console.log(&#39;DATA in is&#39;, data)</pre><pre>return editToAlgolia(data, &#39;equipment&#39;)<br> .then(res =&gt; console.log(&#39;SUCCESS ALGOLIA EQUIPMENT EDIT&#39;, res))<br> .catch(err =&gt; console.log(&#39;ERROR ALGOLIA EQUIPMENT EDIT&#39;, err));<br>});</pre><pre>// listen for a delete of a piece of equipment in Firestore</pre><pre>exports.removeEquipmentFromAlgolia = functions.firestore.document(&#39;equipment/{document}&#39;)<br>.onDelete(event =&gt; {<br> const objectID = event.params.document;<br> return removeFromAlgolia(objectID, &#39;equipment&#39;)<br> .then(res =&gt; console.log(&#39;SUCCESS ALGOLIA equipment ADD&#39;, res))<br> .catch(err =&gt; console.log(&#39;ERROR ALGOLIA equipment ADD&#39;, err));<br>})</pre><pre>// helper functions for create, edit and delete in Firestore to replicate this in Algolia</pre><pre>function addToAlgolia(object, indexName) {<br> console.log(&#39;GETS IN addToAlgolia&#39;)<br> console.log(&#39;object&#39;, object)<br> console.log(&#39;indexName&#39;, indexName)<br> const ALGOLIA_ID = functions.config().algolia.app_id;<br> const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key;<br> const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);<br> const index = client.initIndex(indexName);</pre><pre>return new Promise((resolve, reject) =&gt; {<br>  index.addObject(object)<br>  .then(res =&gt; { console.log(&#39;res GOOD&#39;, res); resolve(res) })<br>  .catch(err =&gt; { console.log(&#39;err BAD&#39;, err); reject(err) });<br> });<br>}</pre><pre>function editToAlgolia(object, indexName) {<br> const ALGOLIA_ID = functions.config().algolia.app_id;<br> const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key;<br> const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);<br> const index = client.initIndex(indexName);</pre><pre>return new Promise((resolve, reject) =&gt; {<br>  index.saveObject(object)<br>  .then(res =&gt; { console.log(&#39;res GOOD&#39;, res); resolve(res) })<br>  .catch(err =&gt; { console.log(&#39;err BAD&#39;, err); reject(err) });<br> });<br>}</pre><pre>function removeFromAlgolia(objectID, indexName) {<br> const ALGOLIA_ID = functions.config().algolia.app_id;<br> const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key;<br> const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);<br> const index = client.initIndex(indexName);</pre><pre>return new Promise((resolve, reject) =&gt; {<br>  index.deleteObject(objectID)<br>  .then(res =&gt; { console.log(&#39;res GOOD&#39;, res); resolve(res) })<br>  .catch(err =&gt; { console.log(&#39;err BAD&#39;, err); reject(err) });<br> });<br>}</pre><p>The above code is located in your functions/index.js file in your firebase app.</p><p><strong>Important:</strong> You will notice that there are references to <strong>functions.config().algolia.app_id</strong> — we configure this in the command line like this:</p><p>Inside of your app in the terminal, do the following commands (replacing YOUR_ALGOLIA_APP_ID with the <strong>Application ID</strong> in Algolia and YOUR_ADMIN_API_KEY with the <strong>Admin API Key</strong> in Algolia.</p><pre>$ firebase functions:config:set algolia.app_id=&quot;YOUR_ALGOLIA_APP_ID&quot; algolia.api_key=&quot;YOUR_ADMIN_API_KEY&quot;</pre><p>To find your keys, go to API Keys on the left hand panel in Algolia, and copy them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVfGg1brPnGYnImIOsZ6Jg.png" /></figure><p>Once you’ve added your keys to Firebase, you will now be able to access the keys to create, update and delete index objects in Algolia.</p><p><strong>Important also: </strong>You will see in the top of the code snippet above, we are using the <a href="https://www.npmjs.com/package/algoliasearch">algoliasearch</a> npm module. We will need to install this locally for our functions to deploy so let’s do that now. From the root of your app in the terminal:</p><pre>$ cd functions</pre><pre>$ yarn add algoliasearch</pre><p>(To have the code working as shown above make sure you install the other packages shown too)</p><h3>Step 4: Add some items to a Firestore collection to test it out</h3><p>Let’s test make sure our function is now working. We first need to deploy our function:</p><pre>$ firebase deploy --only functions</pre><p>Next, go to the Firestore section of firebase and manually add an item into your collection, matching the payload that it expects in the function you just wrote from above.</p><p>Once you’ve added this new item in your Firestore collection, go to the Functions section of Firebase to view the logs to ensure a successful execution on the Firebase side (then we’ll go take a look in Algolia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQ1TWTrZMRjBn7VSON1gEg.png" /><figcaption>Successful function execution to copy a new Firestore item into Algolia</figcaption></figure><p>You might see something like above, showing Success in the console.log’s we added. I’ve opened up the DATA object to inspect the collection item just added.</p><p>Now let’s check Algolia to make sure that item is also there.</p><p>With some luck, our equipment item is also now copied into Algolia:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JT_uvHfATbpBFqoJyzuz6Q.png" /><figcaption>Our Firebase function has copied a firestore object into Algolia successfully</figcaption></figure><p>Now we have this working (and assuming our update and delete functions are also working, we are ready to search on the front end — yew!</p><h3><strong>Step 5: Call Algolia on the front end of your app to display the search results</strong></h3><p>First, let’s pull in the script tag giving us access to the client-side algolia methods. In index.html add:</p><pre>&lt;script src=&quot;<a href="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js">https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js</a>&quot;&gt;&lt;/script&gt;</pre><p>The front-end of this particular app was written in Angular 1, so please ignore the “vm.” and “$scope” syntax for now as the function is largely identical for React etc.</p><pre>// search algolia for equipment name<br>  function doSearch() {<br>    $scope.results = [];</pre><pre>const client = algoliasearch(&#39;Application ID&#39;, &#39;Search-Only API Key&#39;);<br>    index = client.initIndex(&#39;equipment&#39;);</pre><pre>vm.newQuery = { query: vm.querySearch };</pre><pre>index.search(vm.newQuery)<br>    .then(res =&gt; {<br>      if (vm.querySearch.length === 0) {<br>        $scope.results = []<br>        vm.currentFilter.description = &#39;&#39;;<br>        vm.currentFilter.category = &#39;&#39;;<br>        vm.showDropdown = false;<br>      } else {<br>        lodash.map(res.hits, item =&gt; item.name = item.description);<br>        $scope.results = res.hits;<br>        vm.currentFilter.category = &#39;&#39;;<br>        vm.showDropdown = true;<br>      }<br>      $scope.$apply();<br>    })<br>    .catch(err =&gt; console.error(err));</pre><pre>}</pre><p>Above, we call the <strong>algoliasearch</strong> method (accessible from the script tag added above this snippet) which takes in our Application ID used earlier. The Search-Only API Key can be found in the API Keys section in Algolia above the Admin API Key — it’s important to use this key and to not expose your Admin API Key here.</p><p>Algolia is a super powerful tool. We haven’t even scratched the surface on how we would improve the ranking of results depending on your industry, customer requirements or any other factors we might like to add — maybe for a future tutorial.</p><p>Great work! We are all set up. You should now be able to call the Algolia database which is a live, and self-updating replica of your Firestore collection. And your users now have Google-fast search in your app!</p><p>If you have any questions on Algolia, Firebase Functions or Firestore I’m happy to help.</p><p>Ben :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2491f7698d52" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-add-fast-realtime-search-to-your-firebase-app-with-algolia-2491f7698d52">How to add fast realtime search to your Firebase app with Algolia</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build a React, Firebase and Google Cloud Vision machine learning API app]]></title>
            <link>https://itnext.io/tutorial-build-a-react-firebase-and-google-cloud-vision-machine-learning-api-app-in-1-hour-e7eb7584aed4?source=rss-6b68f4428cb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7eb7584aed4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-vision]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ben Cochrane]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 05:51:36 GMT</pubDate>
            <atom:updated>2018-12-14T21:44:32.625Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What technologies/libraries will I learn?</strong></p><ul><li>Firebase (Firestore, Functions, Storage, Google Authentication, Hosting, database security, storage security)</li><li>Google Cloud Vision machine learning API</li><li>Google authentication with Firebase</li><li>React (create-react-app)</li><li>Serverless functions (using Firebase Functions)</li><li>Async/await</li></ul><p><strong>What will I build?</strong></p><p>Demo: <a href="http://doppelganger-app.firebaseapp.com/">http://doppelganger-app.firebaseapp.com/</a></p><p>Code: <a href="https://bitbucket.org/bochrane/doppel-app">https://bitbucket.org/bochrane/doppel-app</a></p><p>Designs: <a href="https://drive.google.com/file/d/1H_c7IBZG5Ggvns1MmPPQn5Tqik5w3Cfb/view?usp=sharing">https://drive.google.com/file/d/1H_c7IBZG5Ggvns1MmPPQn5Tqik5w3Cfb/view?usp=sharing</a></p><p>This video below shows what we will be building</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH3N6ME_ufVY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH3N6ME_ufVY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH3N6ME_ufVY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8e8c37a9b0a923c19aad60e2b65a7ab/href">https://medium.com/media/d8e8c37a9b0a923c19aad60e2b65a7ab/href</a></iframe><p>You will make a react app using firebase functions that uploads a photo of yourself then returns a list of images of people that look just like you — according to who Google thinks you look like anyway :)</p><p><strong>How long is this tutorial? </strong>1–2 hours if you code along, about 20–30 minutes if you just want to read along</p><p>Having just built an enterprise app that books construction equipment for a building company using Firebase, I am so impressed with what it has to offer that I want to showcase some things Firebase has made possible that a few years ago would have taken months to build.</p><p><strong>Note: If you wish you see the full working serverless functions talking to the Google Cloud Vision API you will need to enter later in the tutorial a valid credit card to Firebase — don’t worry though you won’t get charged until you use huge amounts of function calls which we won’t get anywhere near in this tutorial.</strong></p><p>So how are we building this app and where do these doppelgänger images come from?</p><p><strong>Here’s what we will use:</strong></p><ul><li>Google Cloud Vision API (machine learning API for images) will provide a pre-trained model, analysing any image we upload and provide a list of images that look just like the one we upload — pretty neat!</li><li>Firebase functions (yep we will be learning about serverless functions in this tutorial too — we’ll get to what they are shortly if you haven’t come across them yet)</li><li>Firebase Storage (for storing our images we upload) and Firebase Firestore (the new realtime, no-sql database from Firebase)</li><li>React for the front end app</li><li>Google login (using Firebase’s built in authentication with Google)</li></ul><p>I’ve also included the Sketch Design files as well as the Invision clickable prototype — I find it’s much easier working with these 2 tools to design and prototype out what I want to build ahead of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/67/1*-3uAZ1kgLFYxCmyf0Ch4uQ.png" /><figcaption><a href="https://drive.google.com/file/d/1H_c7IBZG5Ggvns1MmPPQn5Tqik5w3Cfb/view?usp=sharing">Sketch Files</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/55/1*XvAbh8WXSwYhllmJ26YuHg.png" /><figcaption><a href="https://projects.invisionapp.com/share/W2JK3G9AZXP#/299468172_My_Doppels">Invision Clickable Prototype</a></figcaption></figure><p><a href="https://projects.invisionapp.com/share/W2JK3G9AZXP#/screens/299468172_My_Doppels">Click here to view the project `Doppels`</a></p><p>So there are a lot of things we get to cover in this tutorial and I’m excited to share them with you. After making this app, my biggest realisation is that the ability to create high scale apps using machine learning APIs just got a whole lot simple. Now to the tutorial…</p><p><strong>We’ll split the tutorial up as follows:</strong></p><ol><li>Set up the react app (we’ll use create-react-app)</li><li>Configure our Firebase app</li><li>Set up Google Authentication</li><li>Setting up Firebase Storage, Firestore and Add An Image</li><li>Setting up Firebase Functions to allow serverless functions to fire whenever we upload a new image</li><li>Set up Google Vision API in Firebase functions to request similar images from it’s API</li><li>Test our Google Vision API with our app</li><li>Deploy to Firebase for a live working app — woo!</li></ol><h3><strong>1. Set up the react app</strong></h3><p>Firstly, make sure you have <a href="https://nodejs.org/en/download/">Node installed</a> (at least version 6)</p><p>We’ll be using Facebook’s <a href="https://github.com/facebook/create-react-app">create-react-app</a> a nice starter kit for building react apps.</p><pre>npm install -g yarn<br>npx create-react-app my-doppelganger-app<br>cd my-doppelganger-app<br>yarn start</pre><p>After running `npm start` you should see this screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jb4vw9KKy74inoiTmT3ojQ.png" /><figcaption>After running npm start you should see this screen</figcaption></figure><p>Next, make 3 folders inside of your src folder as follows:</p><pre>mkdir src/features src/config src/helpers</pre><p>Then lets set up some dummy components for Login, Home and Album</p><pre>cd features</pre><pre>touch Login.js Home.js</pre><p>Then in src/features/Login.js add a dummy component for now:</p><p><strong>src/features/Login.js</strong></p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>export default class Login extends Component {<br> render() {<br>  return (<br>   &lt;div&gt;this is my Login component&lt;/div&gt;<br>  );<br> }<br>}</pre><p>And do the same for the Home component:</p><p><strong>src/features/Home.js</strong></p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>export default class Home extends Component {<br> render() {<br>  return (<br>   &lt;div&gt;this is my Home component&lt;/div&gt;<br>  );<br> }<br>}</pre><p>Next, lets set up the routes for the app. First we will install <a href="https://github.com/ReactTraining/react-router/tree/master/packages/react-router">react-router</a> and <a href="https://github.com/ReactTraining/react-router/tree/master/packages/react-router-dom">react-router-dom</a>:</p><pre>yarn add react-router react-router-dom</pre><p>In src/index.js we will add them and set up our routes:</p><p><strong>src/index.js</strong></p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import &#39;./index.css&#39;;<br>import registerServiceWorker from &#39;./registerServiceWorker&#39;;</pre><pre>import { Redirect, Route, Switch } from &#39;react-router&#39;;<br>import { Router } from &#39;react-router-dom&#39;;<br>import createBrowserHistory from &#39;history/createBrowserHistory&#39;;</pre><pre>import Login from &#39;./features/Login&#39;;<br>import Home from &#39;./features/Home&#39;;</pre><pre>const customHistory = createBrowserHistory();</pre><pre>const Root = () =&gt; {<br> return (<br>  &lt;Router history={customHistory}&gt;<br>   &lt;Switch&gt;<br>    &lt;Route path=&quot;/login&quot; component={Login} /&gt;<br>    &lt;Route path=&quot;/app/home&quot; component={Home} /&gt;<br>    &lt;Redirect from=&quot;/&quot; to=&quot;/login&quot; /&gt;<br>   &lt;/Switch&gt;<br>  &lt;/Router&gt; <br> )<br>}</pre><pre>ReactDOM.render(&lt;Root /&gt;, document.getElementById(&#39;root&#39;));<br>registerServiceWorker();</pre><p>We should now see the Login component in our browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*eMEL-WykE5EsCwqvSxcboA.png" /></figure><p>Next, we can test our routing works by manually going to the home route to make sure they are working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*dReJK2Hnn2x0y4e7bySPDA.png" /></figure><p>Now that our routes are working, we can begin styling up our Login component:</p><p>We will <a href="https://firebasestorage.googleapis.com/v0/b/doppelganger-app.appspot.com/o/google-icon-white.png?alt=media&amp;token=ff891c5f-f2a4-441e-b457-d71b9b21762f">use this png</a> for the button.</p><p>We will upload this png file to Firebase Storage. So first, we will need to sign into firebase with a google account, then create a new Firebase app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Tvs83Q2shrvM4PgpPT89g.png" /></figure><p>Then go to Storage on the left navigation and press Get Started. You will then be shown the default security rules for your Storage bucket — below shows that the default security is to allow access to any document as long as the user is logged in. For our purposes we want to allow some images to allow logged out users to view our Google login button and background image the signin page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yngPYuohoqRrji1AbqHD7w.png" /></figure><p>Let’s change these rules to allow anyone to view any image for now (we will lock this down later).</p><p>In the Rules tab in Storage, change your rules as follows:</p><pre>service firebase.storage {<br>  match /b/{bucket}/o {<br>    match /{allPaths=**} {<br>      allow read, write;<br>    }<br>  }<br>}</pre><p>Next, upload your button image to your Storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oApp0knTCEkqtNvwK63aVA.png" /><figcaption>Click Files in Storage then press Upload File</figcaption></figure><p>Next, copy the Download URL of the image you just uploaded by clicking the File location dropdown after clicking the image row</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*LavVzX8s1ZH0J2l7UK5IRw.png" /></figure><p>Now we can set our background image of the div we are about to make to the Google image like this:</p><p><strong>src/features/Login.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb198c905a152cc6e80f53bdc2bea789/href">https://medium.com/media/cb198c905a152cc6e80f53bdc2bea789/href</a></iframe><p>Above, we have included a loginWithGoogle helper method which uses the firebaseAuth().signInWithRedirect(googleProvider) method firebase gives us out of the box, and the googleProvider passed into this method is found in config.constants.js which is just a new instance of firebase.auth.GoogleAuthProvider().</p><p>We also show a simple loading screen while we are logging into Google using localStorage.</p><p><strong>index.css</strong></p><pre>html {<br> margin: 0;<br> width: 100%;<br>}</pre><pre>body {<br>  margin: 0;<br>  padding: 0;<br>  font-family: sans-serif;<br>  max-width: 768px;<br>  margin: 0 auto;<br>  height: 100vh;<br>  width: 100%;<br>}</pre><pre>.login-button {<br> height: 100px;<br> width: 100%;<br> position: fixed;<br> bottom: 0;<br> background: black;<br> max-width: 768px;<br> margin: 0 auto;<br>}</pre><pre>.login-container { <br> background: #FFC107;<br> width: 100%;<br> height: 100vh;<br>}</pre><pre>.button-text {<br> position: relative;<br> font-size: 25px;<br> color: white;<br> line-height: 50px;<br> left: 90px;<br>}</pre><pre>.google-logo {<br> height: 50px;<br> float: left;<br> background-size: contain;<br> background-repeat: no-repeat; <br> margin: 25px 20px;<br>}</pre><pre>#root {<br> width: 100%;<br> height: 100vh;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaeCyK8KXoGPP_k2D0mQsQ.png" /><figcaption>We should now see something like this for the Login component</figcaption></figure><p>Next, we will create dummy data in the Home route to show what our doppelgänger feed will look like</p><p>First, we will make use of react-bootstrap for our grid system</p><pre>yarn add react-bootstrap</pre><p>Then add the following to src/features/Home.js</p><p><strong>src/features/Home.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9717b3ea12f92d3ac313cd63ecfa65d/href">https://medium.com/media/f9717b3ea12f92d3ac313cd63ecfa65d/href</a></iframe><p>In Home.js above, you will see we have added React Bootstrap including Image, Grid, Row and Col components. We have also added a set of dummy images for now, and set it as our initial state of ‘allPhotos’.</p><p>Before our final return statement, we loop through the allPhotos we set in the initial state using the built it javascript “map” method. Each time we loop through a photo, we create a piece of html which dynamically includes the details about that image.</p><p>And add this css to index.css (this will be all the css we need for the app)</p><p><strong>index.css</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9dea3dde25efaeb57d6e0bf23a30d56/href">https://medium.com/media/b9dea3dde25efaeb57d6e0bf23a30d56/href</a></iframe><p>For the icons and react-bootstrap to work, we need to add the material icons cdn as well as the react-bootstrap css files.</p><p><strong>index.html</strong></p><pre>&lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot;&gt;<br>&lt;link rel=&quot;shortcut icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot;&gt;</pre><pre>...</pre><pre>&lt;link href=&quot;https://fonts.googleapis.com/icon?family=Material+Icons&quot; rel=&quot;stylesheet&quot;&gt;</pre><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css</a>&quot; integrity=&quot;sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u&quot; crossorigin=&quot;anonymous&quot;&gt;</pre><pre>...</pre><p>We should now see our dummy list of photos as well as our bottom nav bar like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34B1WfAr_BZAIEf6JaOYUA.png" /><figcaption>After adding our dummy images we should see this in the /app/home route — Don’t worry — we will get rid of Phil Murray’s face shortly with our own photos</figcaption></figure><p>Our index.html should now look like this:</p><p><strong>public/index.html</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b36eaa21eaac515e5a7f2184f0ab2a23/href">https://medium.com/media/b36eaa21eaac515e5a7f2184f0ab2a23/href</a></iframe><h3>2. Configure our Firebase app</h3><p>Next, let’s set up our Firebase app inside of our React app.</p><p>First, go to your firebase console and click “Project Overview” in the top left navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*55_1VUcQI-XeW5Mr-I3wiA.png" /><figcaption>Your Firebase console</figcaption></figure><p>Then click the “Add Firebase to your web app” button and copy the code that pops up in the modal popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YVhugQRwcDSGPmar2B0dw.png" /><figcaption>Press “Add Firebase to your web app” copy and paste your Firebase details into your React app</figcaption></figure><p>Create a config file in src/config/constants.js</p><p><strong>src/config/constants.js</strong></p><pre>import firebase from &#39;firebase&#39;;</pre><pre>const config = {<br>    apiKey: &quot;AIzaSyBBaJIkRtF3jgzFF7BC83G6nI9joZKxezg&quot;,<br>    authDomain: &quot;doppelganger-app.firebaseapp.com&quot;,<br>    databaseURL: &quot;https://doppelganger-app.firebaseio.com&quot;,<br>    projectId: &quot;doppelganger-app&quot;,<br>    storageBucket: &quot;doppelganger-app.appspot.com&quot;,<br>    messagingSenderId: &quot;115334021919&quot;<br>};</pre><pre>firebase.initializeApp(config);</pre><pre>export const googleProvider = new firebase.auth.GoogleAuthProvider();<br>export const firebaseAuth = firebase.auth;<br>export const db = firebase.firestore().settings({ timestampsInSnapshots: true });</pre><p>Above, we have used the config details from our firebase app. We have also added the Google Auth provider from firebase that will allow us to log in via Google. And lastly we have set up our Firebase database — in this case we will be using Firestore which is the new realtime document store. There is a setting we append to the firestore setup which saves create_at timestamps as a firestore timestamp instead of a regular date object.</p><p>We will also need to install firebase as well as the firebase CLI (firebase-tools) as follows (I’ve chosen a specific version of Firebase tools to ensure the app works for you as it did for me but feel free to use the latest version if you’d like):</p><pre>npm install -g firebase-tools@3.17.4</pre><p>We will also install firebase locally into our app:</p><pre>yarn add firebase@5.0.2</pre><p>Next, let’s set up firebase locally in our terminal:</p><p>(note: I’m using <a href="https://github.com/robbyrussell/oh-my-zsh">Oh-My-Zsh</a> for my terminal which makes the syntax a bit nicer and I’m using the Green theme for the standard Terminal app on Mac, just go to Terminal -&gt; Preferences -&gt; select Grass and click Default to use this theme)</p><pre>firebase login</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*NffAGX0mHtDZ0rNshZbuSA.png" /></figure><p>You will then get a Google login popup in a new browser — go ahead and authenticate with the gmail account you used to sign up for Firebase.</p><p>Once you are logged in via the terminal, we can set up that this app is a Firebase app as follows:</p><pre>firebase init</pre><p>You will be prompted to answer a few questions, use these answers:</p><ol><li>You will see 5 options, to tick the ones we want press the spacebar and up and down to move to the options we want. Press space bar for Firestore, Functions, Hosting and Storage (we won’t be needing Database as that is the old realtime database and we will be using the Firestore database)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*SGS26SdgSq0Prnq5Srd-Hw.png" /><figcaption>Press spacebar on the options selected above to choose them.</figcaption></figure><p>2. Given we are logged in, we can now find the project we created in Firebase in the list on the next question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*1pgmEQLeEwNN4pDkbCXk4A.png" /><figcaption>Arrow down to the project in Firebase you would like to use and press Enter</figcaption></figure><p>3. Press Enter to accept the default for the following steps (these images below look similar but are different setup questions for our Firebase app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ior_E3onqGLuQ9jQ1nrhrQ.png" /><figcaption>Press Enter to accept this default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*lbie2MdmD-OBQFU2S1CEpg.png" /><figcaption>Press Enter to accept this default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*fHcCnmY5etDsxTcT5DzwDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*VEaWuMa5G3uMLBtM6994wQ.png" /><figcaption>I won’t be using ESLint so I’ll choose n and press Enter but you are welcome to use it by pressing Y and pressing Enter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*G0q2Cvta7gS4sn1pWF1laQ.png" /><figcaption>Y and Enter to install the packages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*xMOCxxRTjRus4SpuqDJ0tA.png" /><figcaption>Type build to send our app to a directory called build which firebase will look to deploy for us</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*-5DyLpclif1u7_n8g5EVpQ.png" /><figcaption>Press Enter to accept the default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*e8I66qUvd3snfjhf24oQ8w.png" /><figcaption>Press Enter to accept the default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*EMRZNuXV6hxKHyVzPUOy2g.png" /><figcaption>And we are set up as a Firebase app!</figcaption></figure><p>And finally we are set up as a Firebase app — woohoo!</p><p>You’ll notice a bunch of new files and folders have been added. Very briefly and overview of these files is a follows:</p><p>a. .firebaserc file — this allows firebase to know which app to use and will give a name like default that will point to the firebase app you named in your firebase console</p><p>b. firebase.json — this lets firebase knwo where to find the rules files we can define in our app, and database indexes we create (firebase an pre-index our datebase for to make filtering quicker — we will go through this later in the tutorial) and also where the build folder exists that firebase will deploy to the web — with create-react-app we will run a command later of npm run build which will generate a build folder using webpack.</p><p>c. firestore.indexes.json — as mentioned this is where we can define our database indexes to make filtering on various collections pre-indexed and much quicker</p><p>d. storage.rules — we have changed our storage rules in the firebase console online, but once we deploy this app they will get overridden by the storage rules in this file, so for now lets change the file to reflect what we did in the firebase console. Just make sure your storage.rules file looks like this:</p><p><strong>storage.rules</strong></p><pre>service firebase.storage {<br>  match /b/{bucket}/o {<br>    match /{allPaths=**} {<br>      allow read, write;<br>    }<br>  }<br>}</pre><p>e. You will also see a new folder called functions. This is where our serverless functions will go — exciting times! We will get to these later in to the tutorial also.</p><p>So that’s the new files and folders, now we’ll go set up Firebase Storage to allow us to save some images.</p><p>IMPORTANT: Before we continue, if you are using git source code control like Github or Bitbucket to save your work, please ensure you add /functions/node_modules to your .gitignore file like below:</p><p><strong>.gitignore</strong></p><pre>...</pre><pre># dependencies<br>/node_modules<br><strong>/functions/node_modules</strong></pre><pre># testing<br>/coverage</pre><pre>...</pre><h3>3. Set up Google Authentication</h3><p>Next we will set up being able to log in and log out of our app with Google using Firebase’s built in <a href="https://firebase.google.com/docs/auth/web/google-signin">Google auth provider</a>.</p><p>First, we will set up our auth.js helper file:</p><pre>touch src/helpers/auth.js</pre><p><strong>src/helpers/auth.js</strong></p><pre>import { firebaseAuth, googleProvider } from &#39;../config/constants&#39;;</pre><pre>export function loginWithGoogle() {<br> return firebaseAuth().signInWithRedirect(googleProvider);<br>}</pre><pre>export function logout() {<br> return firebaseAuth().signOut();<br>}</pre><p>The auth.js file above will create 2 methods for logging in to Firebase’s Google auth provider and also logging out too.</p><p>Next, we will update our Login.js file as follows:</p><p><strong>src/features/Login.js</strong></p><pre>import React, { Component } from &#39;react&#39;;<br>import { loginWithGoogle } from &#39;../helpers/auth&#39;;<br>import { firebaseAuth } from &#39;../config/constants&#39;;</pre><pre>const firebaseAuthKey = &#39;firebaseAuthInProgress&#39;;<br>const appTokenKey = &#39;appToken&#39;;</pre><pre>export default class Login extends Component {</pre><pre>constructor(props) {<br>        super(props);<br>        this.state = { splashScreen: false };<br>        this.handleGoogleLogin = this.handleGoogleLogin.bind(this);<br>    }</pre><pre>handleGoogleLogin() {<br>     loginWithGoogle()<br>     .catch(err =&gt; {<br>      localStorage.removeItem(firebaseAuthKey)<br>     });</pre><pre>// this will set the splashscreen until its overridden by the real firebaseAuthKey<br>     localStorage.setItem(firebaseAuthKey, &#39;1&#39;);<br>    }</pre><pre>componentWillMount() {</pre><pre>// checks if we are logged in, if we are go to the home route<br>        if (localStorage.getItem(appTokenKey)) {<br>            this.props.history.push(&#39;/app/home&#39;);<br>            return;<br>        }</pre><pre>firebaseAuth().onAuthStateChanged(user =&gt; {<br>         if (user) {<br>          localStorage.removeItem(firebaseAuthKey);<br>          localStorage.setItem(appTokenKey, user.uid);<br>          this.props.history.push(&#39;/app/home&#39;)<br>         }<br>        })<br>    }</pre><pre>render() {</pre><pre>if (localStorage.getItem(firebaseAuthKey) === &#39;1&#39;) <br>   return &lt;Splashscreen /&gt;;<br>  return &lt;LoginPage handleGoogleLogin={this.handleGoogleLogin} /&gt;;</pre><pre>}<br>}</pre><pre>// this is the URL we copied from firebase storage<br>const loginButtonUrl = &#39;<a href="https://firebasestorage.googleapis.com/v0/b/doppelganger-app.appspot.com/o/google-icon-white.png?alt=media&amp;token=ff891c5f-f2a4-441e-b457-d71b9b21762f&#39;">https://firebasestorage.googleapis.com/v0/b/doppelganger-app.appspot.com/o/google-icon-white.png?alt=media&amp;token=ff891c5f-f2a4-441e-b457-d71b9b21762f&#39;</a>;</pre><pre>const styles = {<br> backgroundImage: `url(https://medium.com/$%7BloginButtonUrl%7D)`<br>}</pre><pre>const LoginPage = ({ handleGoogleLogin }) =&gt; (</pre><pre>&lt;div className=&quot;login-container&quot;&gt;<br>  &lt;div onClick={handleGoogleLogin} className=&quot;login-button&quot;&gt;<br>   &lt;div style={styles} className=&quot;google-logo&quot;&gt;<br>    &lt;span className=&quot;button-text&quot;&gt;Sign In With Google&lt;/span&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;</pre><pre>)</pre><pre>const Splashscreen = () =&gt; (&lt;p&gt;Please Wait Loading...&lt;/p&gt;);</pre><p>We’ve added a lot of code here so let’s step through it.</p><ul><li>we imported the loginWithGoogle helper method</li><li>in our constructor, we are hiding the splashscreen initially, and we are also binding out handleGoogleLogin function so we can use it in the component without the need to bind it from within the component</li><li>the handleGoogleLogin function calls out to the pre-built loginWithGoogle function we imported (we aren’t interested in the success result, as it will go through to the home page on success anyway, so we are just catching the error for now)</li><li>we are using the componentDidMount React lifecycle method to listen for when our component mounted, as we need to know if we have a logged in user. We are also using Firebase’s built onAuthStateChanged method which checks when things like a page reload occurs, and returns the currently logged in user</li><li>we are using localStorage to check if the login is loading, in which case show the Splashscreen component, otherwise show the Login component</li><li>we are using a functional component for the LoginPage and we are also passing in an argument to this component which is the handleGoogleLogin method for use when we click the login button so it has access to that method</li></ul><p>Before we test this out, we need to go to our Firebase console and switch on Google as an authentication option for the app.</p><p>If you have already tried the Google auth in the app and it gets stuck on the Splashscreen, go into the console in your browser and remove the localStorage item that was just set:</p><p><strong>In your browser console run this if it’s stuck on the Splashscreen:</strong></p><pre>localStorage.removeItem(&quot;firebaseAuthInProgress&quot;)</pre><p>In Firebase console, go to Authentication and click Set Up Sign In Method</p><p>Firebase console &gt; Authentication &gt; Sign-In Method &gt; Google</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iedv6yeaLPxOFjRMA9t97Q.png" /><figcaption>Firebase Authentication area for allowing authentication methods</figcaption></figure><p>Then click Google and toggle enable to on, then <strong>press Save</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwigFL9fT8RZw783lZ1BAw.png" /><figcaption>Enable Google auth from the Authentication area in Firebase</figcaption></figure><p>You should now get a Google authentication screen on pressing your Google Login button — woo hoo!</p><p>Let’s now get Sign Out working too.</p><p>In src/features/Home.js add the following throughout the code:</p><p><strong>src/features/Home.js</strong></p><pre>...<br>import { logout } from &#39;../helpers/auth&#39;;<br>...</pre><pre>// inside of the constructor<br>constructor() {</pre><pre>   ...<br>   this.handleLogout = this.handleLogout.bind(this);<br>   ...</pre><pre>}</pre><pre>handleLogout() {<br>        logout()<br>        .then(() =&gt; {<br>            localStorage.removeItem(appTokenKey);<br>            this.props.history.push(&quot;/login&quot;);<br>            console.log(&quot;user signed out from firebase&quot;);            <br>        }.bind(this));<br>}</pre><pre><br>// then in the logout icon (the final Col in the Grid of icons) add a logout method like this:</pre><pre>...<br>&lt;Col onClick={this.handleLogout} xs={4} className=&quot;col-bottom&quot;&gt;<br>          &lt;i className=&quot;bottom-icon material-icons&quot;&gt;assignment_return&lt;/i&gt;<br>&lt;/Col&gt;<br>...</pre><p>So Home.js should look like this:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Image, Grid, Row, Col } from &#39;react-bootstrap&#39;;<br>import { Link } from &#39;react-router-dom&#39;;<br>import { logout } from &#39;../helpers/auth&#39;;</pre><pre>const appTokenKey = &quot;appToken&quot;;<br>export default class Home extends Component {</pre><pre>constructor(props) {<br>        super(props);</pre><pre>const allPhotos = [<br>         {<br>          id: &#39;randomstringimadeup43454356546&#39;,<br>          url: &#39;<a href="http://fillmurray.com/200/200&#39;">http://fillmurray.com/200/200&#39;</a><br>         },<br>         {<br>          id: &#39;randomstringimadeup43523526534565&#39;,<br>          url: &#39;<a href="http://fillmurray.com/200/200&#39;">http://fillmurray.com/200/200&#39;</a><br>         },<br>         {<br>          id: &#39;randomstringimadeup433245234534&#39;,<br>          url: &#39;<a href="http://fillmurray.com/200/200&#39;">http://fillmurray.com/200/200&#39;</a><br>         }                  <br>        ]</pre><pre>this.state = {<br>          allPhotos<br>        };</pre><pre>this.handleLogout = this.handleLogout.bind(this);</pre><pre>}</pre><pre>handleLogout() {<br>        logout()<br>        .then(() =&gt; {<br>            localStorage.removeItem(appTokenKey);<br>            this.props.history.push(&quot;/login&quot;);<br>            console.log(&quot;user signed out from firebase&quot;);            <br>        });<br>    }</pre><pre>render() {</pre><pre>// our doppelganger images<br>        const allImages = this.state.allPhotos.map(photo =&gt; {</pre><pre>return (<br>            &lt;div key={photo.id}&gt;<br>              &lt;div style={{minHeight: &#39;215px&#39;}}&gt;<br>                &lt;i className=&quot;bottom-icon material-icons main-close&quot;&gt;close&lt;/i&gt;<br>                &lt;Image style={{ width: &#39;100%&#39; }} src={photo.url} responsive /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          );<br>        })</pre><pre>return (<br>   &lt;div&gt;<br>    {allImages}</pre><pre>&lt;Grid className=&quot;bottom-nav&quot;&gt;<br>      &lt;Row className=&quot;show-grid&quot;&gt;<br>        &lt;Col xs={4} className=&quot;col-bottom&quot;&gt;<br>            &lt;Link to=&quot;/app/album&quot;&gt;&lt;i className=&quot;bottom-icon material-icons&quot;&gt;collections&lt;/i&gt;&lt;/Link&gt;<br>        &lt;/Col&gt;<br>        &lt;Col xs={4} className=&quot;col-bottom&quot;&gt;<br>            &lt;i className=&quot;bottom-icon material-icons&quot;&gt;camera_alt&lt;/i&gt;<br>        &lt;/Col&gt;<br>        &lt;Col onClick={this.handleLogout} xs={4} className=&quot;col-bottom&quot;&gt;<br>          &lt;i className=&quot;bottom-icon material-icons&quot;&gt;assignment_return&lt;/i&gt;<br>        &lt;/Col&gt;<br>      &lt;/Row&gt;<br>    &lt;/Grid&gt;</pre><pre>&lt;/div&gt;<br>  );<br> }<br>}</pre><p>Now you should now be able to log in and log out of your app with Google auth — nice work — and you know what…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*kkykhuqe_iC7kM3TsimnoQ.png" /><figcaption>Phil Murray said so :)</figcaption></figure><h3>4. Setting up Firebase Storage, Firestore and Add An Image</h3><p>In this section, we will middle button in our bottom nav bar, when pressed to prompt us to upload an image which will get saved to Firebase Storage. Let’s go!</p><p>We will now use a file uploader package called <a href="https://github.com/fris-fruitig/react-firebase-file-uploader">react-firebase-file-uploader</a>, so let’s first install it:</p><pre>yarn add react-firebase-file-uploader</pre><p>Once we have this installed, add in the FileUploader JSX into Home.js where your middle nav bar button sits as follows:</p><p><strong>FileUploader JSX snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/479028b482d1be7deeab4496b7ae085d/href">https://medium.com/media/479028b482d1be7deeab4496b7ae085d/href</a></iframe><p>We will also create the “handleUploadSuccess” function (which we can see is a function that gets executed in the FileUploader snippet above when the file has successfully uploaded. It will return a bunch of details about the image that it just uploaded to Firebase Storage, and we will save this image url to a new collection we are about to create called ‘photos’ in our Firebase Firestore database (also called a document store).</p><p>The handleUploadSuccess function will look like this:</p><p><strong>handleUploadSuccess.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffc91a60f8a8c68c57f8d40fa9296b44/href">https://medium.com/media/ffc91a60f8a8c68c57f8d40fa9296b44/href</a></iframe><p>Our Home.js file should now look like this after the 2 changes above:</p><p><strong>src/features/Home.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e46b378e2f01cf3050b989d02ec1d12/href">https://medium.com/media/1e46b378e2f01cf3050b989d02ec1d12/href</a></iframe><p>Let’s explain the “handleUploadSuccess” method (or function — which ever way you would like to call it) as well the FileUploader JSX snippet too.</p><ol><li>HandleUploadSuccess</li></ol><ul><li>The handleUploadSuccess method gets kicked off from the prop on the FileUploader jsx snippet called “onUploadSuccess”</li><li>We are using the ES7 async-await syntax, which does is a nicer way of doing promises. Instead of “then-ing” and “catch-ing” everything, we can now add the word “async” to the front of our functions, and put the word “await” in front of anything we would have usually wanted to add “.then” to. This is great to cleaning up our code and not have promises all over the place</li><li>With the async-await syntax, we can now check for errors using a try-catch block. The try block wraps all of our async-await code, and if there is an error on any of the await pieces of code, it will throw that into the catch block with the error that occurred, which in this example I’ve called “err”</li><li>I’ve also using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring syntax</a> from ES6 which allows me to pull out specific parts of an object which you can see I’ve used to get the <strong>bucket</strong> and <strong>fullPath</strong> values in the snippet above. (the bucket and fullPath are metadata on the photo that describe where the photo is in our storage bucket — this is important to know where to access our photo from to display it in our app)</li><li>With the photo info and the user info, we then create a “newPhoto” object to save into our Firestore collection which is called “photos”</li></ul><p><strong>Action required:</strong></p><p>In order to get our app working and saving this new photo to not only the Firestore Storage, but also add this as an entry into our photos collection in our database, we need to set up Firestore from the Firebase console like this:</p><p>Go to Firebase console &gt; Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duAiZZvVBhrw4-0hncL9tg.png" /><figcaption>Click Get Started for Cloud Firestore Beta on the left (the Realtime Database is Firebase’s older document store and Firestore is a significant improvement on speed and ability to query documents)</figcaption></figure><p>You will be asked what database security settings you would like — choose Start In Test Mode and press Enable. This will allow reads and writes from non-authenticated users — but given this is a test app we will leave it like this for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N36cE-Wnvw1wW3T3WgIYwQ.png" /></figure><p>Now that we have enabled the database, let’s test out uploading a photo to the app by pressing the middle button in the bottom nav.</p><p>If successful, you should see some console logs as well as being able to look into both the storage and database in Firebase and see something like the following:</p><p>Browser console logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5RGR6o4JZdzMu-0x1tjgA.png" /><figcaption>These are the console.log’s you might see if you kept the console logs from the example snippet above showing we successfully added the photo to storage and used the url of that photo in our database list of photos</figcaption></figure><p>Storage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8DtfuFNnWq7ooTLk_D59g.png" /><figcaption>You should be able to see the name of the photo you just uploaded in this list in Storage</figcaption></figure><p>Firestore photos collection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdyvmeBHCciNYMdomUWOTg.png" /><figcaption>You should be able to see the details of the new photo you added into the photos collection in Firestore</figcaption></figure><p>Nice work!</p><p>The last part of this section is to get the list of photos we have saved in our database and show them on the screen. We are currently using a mock set of images (thanks Phil Murray — but your time in our app is up).</p><p>Let’s now used the componentDidMount React lifecycle method to ask for the images from our Firebase Firestore photos collection.</p><p>To get an initial set of photos, we will use the .get method (later for realtime updates, we will also include the onSnapshot method from Firestore too)</p><p><strong>componentDidMount method:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497d54c5377914336fe579b8dac0d1ed/href">https://medium.com/media/497d54c5377914336fe579b8dac0d1ed/href</a></iframe><p>Now our app should be able to show the images we upload like this (after a reload of course which is what we will fix next):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-zXIvBo7_EU1C6YGS61Vg.png" /><figcaption>This is our app so far — we can upload images, but then still need to refresh to see them — let’s fix that next</figcaption></figure><p>You’ll notice in out componentDidMount method we reach out to another method called getInitial which will get all of the photos for us. The nice part about getInitial is it’s a listener rather than a one time get of the photos. So any time we make changes to the photos collection it will automatically update our front end list of photos too. We are using Firestore’s built in <a href="https://firebase.google.com/docs/firestore/query-data/listen?authuser=2"><strong>onSnapshot</strong></a> method to allow realtime updates — woo!</p><p>You’ll also notice in the getInitial method we are ensuring we have a logged in user before we ask for photos. We do this with the built in Firebase auth method <a href="https://firebase.google.com/docs/auth/web/manage-users"><strong>onAuthStateChanged</strong></a> to make sure someone is signed in.</p><p>Try adding another — and this time it should appear in the app once it hits the database — nice!</p><p>Great work! We are getting close to having a working doppelganger app. Let’s now get the serverless functions working, then hook them up to the Google Vision API — then we are done.</p><p>You Home.js file should now look like this:</p><p><strong>src/features/Home.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700dc93c2c6bf90182043c1f0be928db/href">https://medium.com/media/700dc93c2c6bf90182043c1f0be928db/href</a></iframe><h3>5. Setting up Firebase Functions to allow serverless functions to fire whenever we upload a new image</h3><p>We are now going to use serverless functions to allow us to write server side code which will connect into the Google Vision API to check who looks like us.</p><p>If you haven’t looked into the serverless movement yet, there are some great starters over at <a href="https://serverless.com/learn/">https://serverless.com/learn/</a> to help you get started.</p><p>In a nutshell, the serverless movement is more than just writing serverless functions, it’s about allowing developers to focus more on business logic and less on infrastructure and setup. Serverless is a bit of a misleading name, because there are still servers that power your app. It’s just that as a developer a lot of that setup and scaling is taken care of (in the early days anyway — serverless has a lot of power but also comes with it’s own hidden gotchas like monitoring and cold starts which are improving every day).</p><p>I like to think about serverless functions being like any back end function we might write. It’s just each of these functions has their own little server underneath them that is waiting to be run.</p><p>When you run these functions, they will spin up their own mini container of sorts, usually for between a few milliseconds and up to 6 seconds and sometime longer depending on your function. Once you are done with that function executing, the mini container is shut back down. You are charged for the amount of memory used and milliseconds of execution time. You might hear people talk about serverless functions as Lambdas too given AWS Lambda was one of the first offerings (although not the first) to make serverless functions mainstream to developers).</p><p>Firebase functions are another serverless function offering using the Google Cloud Platform.</p><p>Ok, enough about serverless functions Ben, let’s just write some…</p><p>Hang on, why are we writing a serverless function again?</p><p>Because we want to talk to the Google Vision API to give us a list of images that look like whatever image it is we upload to our photos collection.</p><p>So here we go…</p><p><strong>Firebase functions</strong></p><p>If you can’t already see a functions folder in your main app, then let’s get you set up with a functions folder as follows from the firebase functions docs <a href="https://firebase.google.com/docs/functions/get-started">https://firebase.google.com/docs/functions/get-started</a> (if you followed along much earlier in this tutorial and asked for functions in the setup this won’t apply)</p><pre>firebase init functions</pre><p>Next, we should see a folder called <strong>functions </strong>and inside of it a file called <strong>index.js</strong></p><p>We won’t see much in this index.js file yet, but this is where we can write all of our serverless functions that will get deployed to the Google Cloud platform.</p><p>Our app has a package.json. Our function folder also has it’s own package.json which is separate again and are node modules we will need for our server side code we are about to write. Let’s set up the node modules we will need for our serverless functions:</p><pre>cd functions</pre><p>Next, add the necessary node modules, including <a href="https://github.com/googleapis/nodejs-vision">Google Cloud Vision API node module</a></p><pre>yarn add firebase-functions firebase-admin promise <a href="http://twitter.com/google">@google</a>-cloud/vision</pre><p>Then install all modules that were already there with the new ones:</p><pre>yarn</pre><p>We will add the <a href="https://github.com/then/promise"><strong>promise</strong></a><strong> </strong>library as all functions require them to be promisified (that’s a word I swear?).</p><p>Then in functions/index.js we will set up our serverless functions file:</p><p><strong>functions/index.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/957369b282a403af69f5b2bcfbc554ae/href">https://medium.com/media/957369b282a403af69f5b2bcfbc554ae/href</a></iframe><p>Above, we see we’ve imported the modules we just installed an also initiated our Firestore database which we will need to update the images we get back from the Google Vision API.</p><p>Next, let’s write a function called <strong>addSimilarImages </strong>which will add similar images from Google Vision API into a list of image urls that we will save against the photo we just saved in Firestore.</p><p>Firestore has a great feature which allows for listening to events to the database. Below, you will see this in use through the <strong>functions.firestore.document(‘photos/{document}’)<br>.onCreate</strong> method as follows:</p><p><strong>functions/index.js </strong>(the full version with setup and the function in it)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a2b3077cbfdbbcbb77963e919b7da7/href">https://medium.com/media/27a2b3077cbfdbbcbb77963e919b7da7/href</a></iframe><p>You can see above the following:</p><ul><li>Firestore uses an <strong>onCreate</strong> listener which allows for a function to be invoked when an event like adding a new photo to the collection happens</li><li>The syntax allows us to check for any document in the photos collection by adding .document(‘photos/{document}</li><li>snap gives back a snapshot of the data that was added, in this case the photo document that was added to the database, and context let’s us know what type of method is was, e.g. create, read, update destroy amongst other metadata</li><li>we create a full photo url that the Google Vision API understands by recreating a google storage style url called <strong>photoUrl</strong></li><li>we then return a promise after going out to the google vision instance (visionClient) and using the <strong>webDetection</strong> method (there are a bunch more methods on this API such as labelDetection, faceDetection to name a couple that you might like to use instead which you can find here <a href="https://cloud.google.com/vision/docs/all-samples">https://cloud.google.com/vision/docs/all-samples</a></li><li>In this tutorial we are using the webDetection method, which picks up images that have similar attributes to the one uploaded (which we called <strong>photoUrl</strong>)</li><li>We put this photoUrl through the Vision API and it returns a list of image urls — we are interested in the visually similar images</li><li>We create an array of these visually similar images and update the document in the photos collection with the <strong>similarImages</strong> images</li></ul><p><strong>NOTE:</strong> Before the function above will work for us, we now need to enable the Google Cloud API on our account</p><h3><strong>6. Set up Google Vision API in Firebase functions to request similar images from it’s API</strong></h3><p>Now we are getting to the really exciting part where we will be using a machine learning service to help us figure who else in the world looks similar to us, according to Google anyway.</p><p><strong>Step 1: Go to the Google Cloud console here </strong><a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a> and login (don’t worry — you already have an account — you just need to log in using the same gmail account as your Firebase account)</p><p><strong>Step 2: Click select a project then click New project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TOhxhu86xEJB9snylriXg.png" /></figure><p><strong>Step 3: Name your project (I just chose the same name as my firebase project but it’s ok if it’s different)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9tGoAI7nV7p7he1eR6Nuw.png" /></figure><p><strong>Step 4: Select the project you just made (there’s a trick here)</strong></p><p>Once you’ve created the project, we are placed back into the main console page again, but in the top left, the project isn’t selected that we just create — so we need to select it.</p><p>You would think this is easy, but clicking Select a project, if you already have previous project may not show your newly created project in the list — you will need to click the <strong>All Projects</strong> tab next to the Recent Projects tab to find it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zD5GCxvA7FWcICAkog-Wxg.png" /><figcaption>We might need to tab to the All tab to find our project we just created</figcaption></figure><p><strong>Step 5: Enable Google Vision API</strong></p><p>Go to the APIs &amp; Services Dashboard — from the console go APIs &amp; Service &gt; Dashboard like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sy5U7AZ8O3--NR5DRtVadg.png" /></figure><p>Then click Enable APIs and Services like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QL8wOGfwa0f1IfffjuhpAA.png" /></figure><p>Then type “vision” in the search in this page below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGOBJiaRzPP8fK8GEyHkA.png" /></figure><p>And click the Vision API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4XuitXrl3bLb7srdp9UGA.png" /></figure><p>Lastly, click Enable like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0s8GNml3JCILbVwvVsz-g.png" /></figure><p>Wowsa — there was bit in that! We are now ready to get into actually using a pre-trained machine learning API — woo!</p><h3>7. Test our Google Vision API with our app and add the lookalike images to our app</h3><p>This is it — the moment we’ve been working toward for however long you’ve been reading this on the bus, on the train, at home on the couch or at work :)</p><p>To test if this worked, we will need upload an image, then look at the logs on the Firebase function to see if we got some success. You will notice I’ve intentionally left in a bunch of console logs in the function so that we can see what data we are getting back.</p><p>Let’s go!</p><p>First, we need to deploy our functions to firebase in order for it to recognise the functions we’ve just written. We won’t deploy the front-end just yet, only our server side code.</p><p><strong>To deploy the Firebase functions:</strong></p><p>From your home directory of the app in your terminal:</p><pre>firebase deploy --only functions</pre><p>This will <strong>only </strong>deploy the functions folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7n1A6wxmjApdLg4nZWd7A.png" /></figure><p>And hopefully you see a confirmation like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OH7zQjwZpJ_Kr_U8i5DLfg.png" /><figcaption>Sometimes I get an error like the top part of this image, all I can say is try, try again :)</figcaption></figure><p>If you get any errors, just make sure you are logged in to firebase by using firebase logout, then firebase login (then log in with the correct gmail account) and run firebase use default (which is found in your .firebaserc file — it’s most likely you haven’t changed this so you should see a default key in there). Make sure also that you’ve run yarn in your functions folder too as the module must be installed before deploying to Firebase. And if you get an error like the top part of the image above, just try it again. Magic.</p><p><strong>Allowing Cloud Vision to work requires billing to be added</strong></p><p>Now as I mentioned at the start of the tutorial, if you want to see your functions work, we will need to include a valid credit card into your Firebase console. Don’t worry however, the free tier has huge monthly usage before Google start charging you a cent. You can check out the <a href="https://firebase.google.com/pricing/">Firebase pricing here</a> and the <a href="https://cloud.google.com/vision/#cloud-vision-api-pricing">Cloud Vision pricing here</a>. <strong>In short we would need to have more than 125 thousand function calls per day, or be hosting more than 5GB of photos, or do more than 20 thousand write operations to the photos collection per day or analyse more than 1000 images per month on Google Cloud Vision to start getting charged.</strong></p><p>In the bottom left of your Firebase console, click Upgrade then select the Blaze Pay as you go plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJbiEPI4WMDu7aKOfSe_eA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4lvuEvtBj8kHVN_9fFgVg.png" /></figure><p>Lastly, let go to our functions page in our Firebase console and check everything went through ok…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xA3bKd1JaSVxSAatbKjHjw.png" /><figcaption>Our first serverless function deployed. Nice!</figcaption></figure><p>You can see above, our function which we called addSimilarImages is now in the list of functions in our firebase console.</p><p>Great — next let’s test out our function by uploading an image and then we will check the logs on this serverless function to see what happened…</p><p>I just uploaded a photo. Now let’s click View Logs like below in the Firebase Functions console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbOUCnffQGjHjcbYynkvrw.png" /><figcaption>View logs on the right hand side</figcaption></figure><p>If all goes well with our photo upload, in your function logs, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncNnSqy9ksYsGABTQozltQ.png" /></figure><p>You can see above that the function took 5553ms to execute and fetched a list of similar images from the Google Cloud Vision API — if you look closely in the logs above Google is suggesting I look like someone called Edwin from the Stripe team!</p><p>The last part of the tutorial is to show these similar images in the front end of our app. Let’s see who we look like according to Google…</p><p>First, we are going to add some loading spinners to let the user know we are waiting for some doppelganger images to come back from the Google Vision API. We will use react-spinners:</p><p>From the root of your app, in your terminal, run:</p><pre>yarn add react-spinners</pre><p>We will then import this at the top of Home.js as well as import the Modal from react-bootstrap. We will use the modal for when someone clicks on an image of the doppelganger which will open up a modal with the image in it.</p><pre>...</pre><pre>import { Image, Grid, Row, Col, Modal } from &#39;react-bootstrap&#39;;</pre><pre>...</pre><pre>import { ScaleLoader } from &#39;react-spinners&#39;;</pre><p>We are going to make a heap of small changes which I will run through below. At the end of the changes, here is what your Home.js file should look like:</p><p><strong>src/features/Home.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9b45f8147368e147a4a2e5c6dda3953/href">https://medium.com/media/c9b45f8147368e147a4a2e5c6dda3953/href</a></iframe><p>Let’s run through the additions we made:</p><ul><li>We’ve added in a row of loaders to show when we have just uploaded an image and are waiting for the doppelganger images to return from Google Cloud Vision. We loop through an array of “similarImages” which is attached to the photo document in the firebase function in index.js we made earlier</li><li>We’ve also now added a list of doppelgangers below each image that has similarImages on it, and we’ve used some css to create a horizontal scroller for these images</li><li>We’ve also added a modal, so that when a doppelganger image is clicked we can see an enlarged view of the image</li><li>We also have a remove handler in the top left of each image to allow us to delete each image</li><li>We added a where statement to our list of images, so that we only see the images we uploaded. In firebase, we can do this on the front end using .where(‘userId’, ‘==’, user.uid) in our collection call. In the next section we will also add Firestore rules on the backend which will add security to replicate what we have on the front end.</li><li>We also added a small helper function to check if we are on mobile as I haven’t got around to fix a rotation issue when uploading from a mobile device — the workaround is to turn your device to landscape which allows the image to show up correctly when viewing it back on a desktop</li><li>We’ve also added an imageRef piece of state — this becomes important for setting security rules on the Firebase Storage later on — it will allow us to match the user uploading an image to a specific file location</li></ul><p>We have now got a working app — locally anyway. Let’s get this thing deployed to the web and finish this tute!</p><h3><strong>8. Deploy to Firebase for a live working app — woo!</strong></h3><p>The final part — deployment!</p><p><strong>Step 1: Add security rules before we deploy</strong></p><p>In your firestore.rules file, we will add the following to ensure only you can read, write and delete your photos.</p><p><strong>firestore.rules</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf0654899e1528d214fcf16a555941b5/href">https://medium.com/media/bf0654899e1528d214fcf16a555941b5/href</a></iframe><p><strong>storage.rules</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e69cfe5a4672816554324f08415b405/href">https://medium.com/media/2e69cfe5a4672816554324f08415b405/href</a></iframe><p>Each time we upload an image, we save the path to include the user’s auth id (aka userId).</p><p>If we try to request to upload an image without being logged in or another logged in user attempts to upload photos that reference your userId, it will deny the upload like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CG7RY55-RqKdi01D8t1Dwg.png" /></figure><p>The rules above are a nice way of achieving attribute based access control — in simple terms being able to define what types of actions (create, read etc) users are allowed to do, and in what collections (e.g. photos collection). The rules are also functional, that is you can create functions outside of the service cloud.firestore block and refer to them inside of it too.</p><p>For our purposes, we are saying above that only the photos collections is given any access, and for any photo in the photos collection, we will allow a read or delete if your user id from firebase authentication is the same as the userId attribute on the photo document that we saved.</p><p>Similarly for writing objects, you can only save documents to the database is your user id is the same as the userId attribute on the payload of the photos collection document. Pretty nice I thought.</p><p><strong>Step 2: Create a build version of our react app</strong></p><p>In your terminal, run:</p><pre>yarn build</pre><p>If it built correctly you should see a message like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNoFkvfxpjKS5n4Iawlpag.png" /></figure><p><strong>** Important **</strong></p><p>In your firebase.json file in the root of your app, we will tell firebase which folder to find the react app in. You will notice a build folder has been created to house our react app, so we need to change “<strong>public</strong>” to “<strong>build</strong>” like this:</p><p><strong>firebase.json</strong></p><pre>{<br>  &quot;firestore&quot;: {<br>    &quot;rules&quot;: &quot;firestore.rules&quot;,<br>    &quot;indexes&quot;: &quot;firestore.indexes.json&quot;<br>  },<br>  &quot;hosting&quot;: {<br>    &quot;<strong>public</strong>&quot;: &quot;<strong>build</strong>&quot;,<br>    &quot;rewrites&quot;: [ {<br>      &quot;source&quot;: &quot;**&quot;,<br>      &quot;destination&quot;: &quot;/index.html&quot;<br>    }],    <br>    &quot;ignore&quot;: [<br>      &quot;firebase.json&quot;,<br>      &quot;**/.*&quot;,<br>      &quot;**/node_modules/**&quot;<br>    ]<br>  },<br>  &quot;storage&quot;: {<br>    &quot;rules&quot;: &quot;storage.rules&quot;<br>  }<br>}</pre><p>Step 2: Deploy the full app to Firebase</p><p>In your terminal, run:</p><pre>firebase deploy</pre><p>This will deploy both your front end app as well as the firebase functions folder.</p><p>With any luck your app is deployed and you have a working doppelganger app! Woo!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH3N6ME_ufVY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH3N6ME_ufVY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH3N6ME_ufVY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8e8c37a9b0a923c19aad60e2b65a7ab/href">https://medium.com/media/d8e8c37a9b0a923c19aad60e2b65a7ab/href</a></iframe><p><a href="https://doppelganger-app.firebaseapp.com/">React App</a></p><p>Well done on making it this far! We have covered a lot.</p><p>To summarise, you’ve just learnt how to:</p><ul><li>create a react app and use react-router-dom</li><li>security rules for Firebase Firestore database, and Firebase Storage</li><li>deployment of a react and firebase app</li><li>interacting with a machine learning API with Google Cloud Vision</li><li>serverless functions using Firebase Functions to talk to the Google Cloud Vision API</li><li>and most importantly……</li><li>You’ve found out who Google thinks you look like!</li></ul><p>Please feel to leave any comments, questions and any improvements you’d like to see in this tutorial.</p><p>For any further questions, feel free to <a href="https://au.linkedin.com/in/benjamincochrane">reach out to me on LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7eb7584aed4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/tutorial-build-a-react-firebase-and-google-cloud-vision-machine-learning-api-app-in-1-hour-e7eb7584aed4">Tutorial: Build a React, Firebase and Google Cloud Vision machine learning API app</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide To The Sydney Startup Community: 8 Lists To Get You Started]]></title>
            <link>https://medium.com/@bencochrane/guide-to-the-sydney-startup-community-8-lists-to-get-you-started-c970c9ee4be7?source=rss-6b68f4428cb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c970c9ee4be7</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Ben Cochrane]]></dc:creator>
            <pubDate>Sun, 19 Apr 2015 08:42:13 GMT</pubDate>
            <atom:updated>2015-06-03T05:40:15.202Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide To The Sydney Startup Community: 8 Lists To Get You Started</h3><blockquote>The startup journey can be lonely, but ensuring you’re involved in the community will make it far more enjoyable and ultimately increase your chances of success.</blockquote><p>These eight lists are designed to provide you with the best support in town, depending on which part of the journey your startup is at.</p><p>If you’re in the idea stage it may be worth considering hackathons, meetups and networking events.</p><p>It your startup is just getting going you might like to check out the list of incubators.</p><p>Or if you’re looking for further growth, check out the accelerators and venture funding.</p><h3>1. Meetups and Networking</h3><p>There are various technology and startup related meetups going on most nights in Sydney. Depending on whether you’re looking for a co-founder, or capital, these meetups are a great avenue to meet these folk. If you want to go even further, message the owner of certain meetup groups to see if they need speakers for their upcoming events.</p><p><a href="http://www.meetup.com/sydney-tech-startup/">Sydney Tech Startup meetup</a></p><p><a href="http://www.meetup.com/Silicon-Beach/">Silicon Beach meetup</a></p><p><a href="http://www.meetup.com/Fishburners-Meetup/events/215667802/">Fishburners’ Friday Pitches</a></p><p><a href="http://headsoverheels.com.au/">Heads over Heels</a></p><p><a href="http://www.sydjs.com/">SydJS (Javascript developer meetup)</a></p><p><a href="http://www.meetup.com/Ruby-On-Rails-Oceania-Sydney/">Ruby on Rails Oceania (Ruby on Rails developer meetup)</a></p><p><a href="http://www.meetup.com/ixda-sydney/">IxDA (User Experience Design meetup)</a></p><p><a href="http://www.meetup.com/Product-Mavens/">Product Mavens (Product management meetup)</a></p><h3>2. Conference and Camps</h3><p>Conferences are another excellent way to understand the state of the tech and startup community, showcasing the best of what’s to come. Technology camps are usually designed for those with a specific interest in the technology the camp is about and usually run for 2 nights over a weekend in various locations around Sydney.</p><p><a href="https://sydstart.wordpress.com/">SydStart (Tech startup showcase)</a></p><p><a href="http://www.cebit.com.au/">CeBIT (Business technology conference)</a></p><p><a href="http://tiecon.org.au/">TieCon (Global technology conference)</a></p><p><a href="http://www.adtechaustralia.com/">ad:tech (Advertising technology conference)</a></p><p><a href="http://yowconference.com.au/">Yow! (Developer conference)</a></p><p><a href="http://v.campjs.com/">Camp JS (Javascript developer camp</a></p><p><a href="http://railscamps.com/">Rails Camp (Ruby on Rails developer camp)</a></p><h3>3. Hackathons and Pitch Competitions</h3><p>If you are looking for a co-founder, be it technical, marketing, design, or sales, hackathons are a great way to understand who could be right for your business. In case you haven’t been to one, a hackathon involves usually between 50 and 100 participants who will form groups of 3 to 4 and will build a product over a weekend. For tech-based hackathons, this will usually involve a teaming up with coders, sales people, marketers and designers to create a real life tech product over the course of a weekend. On the final afternoon or night, each group will pitch their product and winners are announced.</p><p><a href="http://www.seedstarsworld.com/event/seedstars-sydney-2015/">Seedstars</a></p><p><a href="https://2015.battlehack.org/">Battlehack</a></p><p><a href="http://www.govhack.org/">GovHack</a></p><p><a href="http://www.ecohack.org/">EcoHack</a></p><p><a href="http://angelhack.com/events/">AngelHack</a></p><p><a href="http://sydneyappiness.com/">Appiness</a></p><p><a href="http://www.nswcodeworks.com/">Code Works</a></p><p><a href="https://www.facebook.com/hackathon">Facebook Hackathon</a></p><p><a href="http://girlgeeksydney.com/">She Hacks</a></p><p><a href="http://hackagong.com/">Hackagong</a></p><h3>4. Incubators</h3><p>Incubators exist to assist entrepreneurs in forming a complete team around a product or concept they are looking to build. Typically, an incubator will be able to provide mentoring, technical development of the product, design, marketing and sales depending on what skillsets you can already bring to the table. In exchange, you will most often pay a combination of cash for the technical development costs as well as a portion of the equity of your business to the incubator.</p><p><a href="http://atp-innovations.com.au/">ATP Innovations</a></p><p><a href="https://www.bluechilli.com/">Blue Chilli</a></p><p><a href="http://pollenizer.com/">Pollenizer</a></p><p><a href="http://fi.co/">Founder Institute</a></p><h3>5. Accelerators</h3><p>Accelerators exist to assist startups who have had some traction to really ‘accelerate’ the growth of their business. They startup has proven there is at least some sort of product-market fit, and will typically have some customers or even revenue being generated. An accelerator, will assist with mentoring and introduction to drive significant growth typically in a short timeframe, between 12 weeks and 6 months.</p><p><a href="http://www.slingshotters.com/">Slingshot</a></p><p><a href="http://incubate.org.au/">Incubate</a></p><p><a href="http://www.innovyz.com/">ANZ Innovyz</a></p><p><a href="http://sb.co/">Springboard Enterprises</a></p><p><a href="https://muru-d.com/">Muru-D</a></p><p><a href="http://www.elevate61.com.au/">Elevate 61</a></p><p><a href="http://25fifteen.com/">25fifteen</a></p><h3>6. Angel / Seed / Venture Funding</h3><p>There are various forms of funding depending on where your startup is at right now. For concepts and ideas it is typical to take angel funding (up to $100k) to assist with developing a minimum viable product that help prove a market exists. Often the next form of funding will be seed funding, typically in the range of $100k — $500k which gives the opportunity for increasing growth. Lastly Venture Capital, which typically looks to fund businesses with large market potential and generate returns in excess of 10 times their initial investment, will invest amounts of $500k plus. They will take a seat at the board typically and can have an active say in the trajectory and decision making of the company and provide valuable mentoring and introductions.</p><p><a href="http://www.one-ventures.com.au/">One Ventures</a></p><p><a href="http://sydneyangels.net.au/">Sydney Angels</a></p><p><a href="http://www.tankstream.vc/">Tank Stream Ventures</a></p><p><a href="http://www.sxvp.com/">Southern Cross Ventures</a></p><p><a href="http://www.rightclickcapital.com/">Right Click Capital</a></p><p><a href="http://www.greenlanedigital.com.au/">Green Lane Digital</a></p><p><a href="http://www.blackcitrus.com.au/">Black Citrus</a></p><p><a href="http://optusinnov8seed.com.au/">Optus Innov8 Seed</a></p><p><a href="http://airtreevc.com/">Airtree Ventures</a></p><p><a href="http://blackbird.vc/">Blackbird Ventures</a></p><p><a href="http://mhcarnegie.com/">MH Carnegie</a></p><p><a href="http://www.innovationcapital.net/">Innovation Capital</a></p><p><a href="http://innovationbay.com/">Innovation Bay</a></p><p><a href="http://www.sydneyseedfund.com.au/">Sydney Seed Fund</a></p><h3>7. Education</h3><p>Startups are a marathon, not a sprint. Having proper education combined with applying this in real life situations is the best way to ensure success. Building a business without the fundamental understanding of technology, user experience design, product mangement, marketing and sales and business development can be difficult without a strong network of mentors and previous experience. Often times, entrepreneurs in addition to their learnings in their startup will want to understand the best practices without need to commit too much time away from their business. Fortunately there are a number of edication opportunities open to you. I won’t go through the plethora of online learning opportunites as they aren’t specific to Sydney but I will mention a few face to face education institutions targeted at helping entrepreneurs becoming successful.</p><p><a href="https://generalassemb.ly/">General Assembly (Web Development, User Experience Design, Product Management, Digital Marketing)</a></p><p><a href="http://thecoderfactory.com/">Coder Factory (Web Development)</a></p><p><a href="https://www.brainmates.com.au/">Brainmates</a></p><h3>8. Co-working spaces and offices</h3><p>Working from home can be a tough challenge if you have entered into a new business, particularly if you’ve come from an environment of having people around all the time. Co-working spaces are great alternative to your own office and keep the costs down in the early stages of your business. (typically costs range between $400 and $700 per month for a desk at one of these co-working spaces).</p><p><a href="http://fishburners.org/">Fishburners</a></p><p><a href="http://www.commonroomsyd.com.au/">Common Room</a></p><p><a href="https://startsoc.wordpress.com/icentral/">iCentral</a></p><p><a href="http://tankstreamlabs.com/">Tank Stream Labs</a></p><p><a href="http://theworkben.ch/">Workbench</a></p><p><a href="http://www.hubaustralia.com/location/sydney/">Hub Sydney</a></p><p><em>This story is part of the “DeMinds | Startup Tales” publication on Medium. DeMinds | Startup Tales is a destination for everybody who is interested in reading from people in startup ecosystems around the world. If you wanna read more Startup Tales, subscribe to the DeMinds publication here:</em><a href="https://medium.com/deminds-startup-tales">https://medium.com/deminds-startup-tales</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c970c9ee4be7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>