Build a Mini Netflix with React in 10 Minutes

By Prosper Otemuyiwa

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

In this tutorial, we’ll quickly build out a Mini Netflix in 10 minutes. In fact, I think we might build it less time.

MVP Challenge

An excited entrepreneur just approached you to build a video service. A service where users can quickly upload short videos and share on twitter for their friends to view. Let’s list out the features of this app.

Features

  • Users should be able to sign up and log in.
  • Registered/Logged-in users should be able to upload short videos of about 20 – 30 seconds.
  • Registered/Non-registered users should be able to view all uploaded videos on the platform on a dashboard.
  • Users should be able to share any of the videos on twitter.

Now, here’s the catch! T’challa of Wakanda wants to invest in some startups today, so the entrepreneur needs to demo the MVP of the video service in 10 minutes from now.

http://cloudinary-res.cloudinary.com/video/upload/v1497373918/T_challay.mp4

I know you are screaming your heart right now. It’s totally okay to cry and let the world know about your problems and challenges, but after much ado shedding tears, will the app be ready in 8 minutes? Well, sorry – tears can’t build an app!

Solution

It’s possible to build the MVP our entrepreneur is asking for. Let me show you how! Ready your editor, your command line and anxious fingers. Let’s get to work!!!

1) Flesh Out The App

We’ll use React to build out the app. Facebook has a tool, create-react-app that can scaffold a progressive web app out of the box in less than a minute. If you don’t have it installed, please install and run the command below in your terminal:

create-react-app miniflix
cd miniflix

Go ahead and open up public/index.html. Pull in bootstrap and add it just after the link to the favicon.

…
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
…

2. Set up Authentication & Views

Go ahead and install the following packages from your terminal:

npm install auth0-js react-router@3.0.0 jwt-decode axios

auth0-js – For authentication
react-router – For routing within our app
jwt-decode – For decoding the JSON Web Token in our app
axios – For making network requests.

Open up your src directory and create a components and utils folder. In the utils folder, create a file, AuthService.js and add the code here to it. I explained how to handle the authentication in this tutorial, so check it out to ensure you are on the right track.

We’ll create 4 components in the components folder. Callback.js, Display.js, Nav.js and Upload.js

The Callback component basically stores our authentication credentials and redirects back to the upload route in our app.

The Display component will be dashboard for viewing all videos.

The Nav component will be the navigation that all pages in the app will share.

The Upload component will handle uploading of videos by registered users.

Add this piece of code below to components/Callback.js :

import { Component } from 'react';
import { setIdToken, setAccessToken } from '../utils/AuthService';

class Callback extends Component {

  componentDidMount() {
    setAccessToken();
    setIdToken();
    window.location.href = "/";
  }

  render() {
    return null;
  }
}

export default Callback;

Add this piece of code to components/Nav.js :

import React, { Component } from 'react';
import { Link } from 'react-router';
import { login, logout, isLoggedIn } from '../utils/AuthService';
import '../App.css';

class Nav extends Component {

  render() {
    return (
      <nav className="navbar navbar-default">
        <div className="navbar-header">
          <Link className="navbar-brand" to="/">Miniflix</Link>
        </div>
        <ul className="nav navbar-nav">
          <li>
            <Link to="/">All Videos</Link>
          </li>
          <li>
            {
             ( isLoggedIn() ) ? <Link to="/upload">Upload Videos</Link> :  ''
            }
          </li>
        </ul>
        <ul className="nav navbar-nav navbar-right">
          <li>
           {
             (isLoggedIn()) ? ( <button className="btn btn-danger log" onClick={() => logout()}>Log out </button> ) : ( <button className="btn btn-info log" onClick={() => login()}>Log In</button> )
           }
          </li>
        </ul>
      </nav>
    );
  }
}
export default Nav;

In the Nav component, you must have observed that we imported a css file. Open the App.css file and add this code here to it.

Add this piece of code to components/Display.js:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';
import { isLoggedIn } from '../utils/AuthService';
import axios from 'axios';

class Display extends Component {

  render() {

    return (
      <div>
        <Nav />
        <h3 className="text-center"> Latest Videos on Miniflix </h3>
        <hr/>

        <div className="col-sm-12">

        </div>
      </div>
    );
  }
}

export default Display;

Add this piece of code to components/Upload.js:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';

class Upload extends Component {

  render() {

    return (
      <div>
        <Nav />
        <h3 className="text-center">Upload Your 20-second Video in a Jiffy</h3>
        <hr/>

        <div className="col-sm-12">
          <div className="jumbotron text-center">
            <button className="btn btn-lg btn-info"> Upload Video</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Upload;

Lastly, open up index.js and add replace it with the code here to set up your routes.

Now, when you run your app with npm start, you should have views like this:

3. Upload Videos

We need a storage space for the videos our users will upload. Cloudinary is a cloud-based service that provides an end-to-end image and video management solution including uploads, storage, administration, manipulation and delivery. Head over to Cloudinary.com and create an account for free.

Let’s make use of Cloudinary’s Upload Widget. This widget allows you to upload videos or any type of file from your local computer, facebook, dropbox and Google Photos. Wow, very powerful. And the integration is seamless.

Go ahead and reference the cloudinary widget script in your index.html:

 <script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>

Note: You can add it just after the links.

Now in Upload.js, modify the code to look like this:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';

class Upload extends Component {

  uploadWidget = () => {
    window.cloudinary.openUploadWidget(
      { cloud_name: cloud_name',
        upload_preset: 'unsigned-preset',
        tags: ['miniflix'],
        sources: ['local', 'url', 'google_photos', 'facebook', 'image_search']
      },
      function(error, result) {
          console.log("This is the result of the last upload", result);
      });
  }

  render() {
    return (
      <div>
        <Nav />
        <h3 className="text-center">Upload Your 20-second Video in a Jiffy</h3>
        <hr/>

        <div className="col-sm-12">
          <div className="jumbotron text-center">
            <button onClick={this.uploadWidget} className="btn btn-lg btn-info"> Upload Video</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Upload;

In the code above, we added a third argument, tags. Cloudinary provides this for automatic video tagging. Every video that is uploaded to this app will be automatically tagged, miniflix. In addition, you can provide as many tags as you want. This feature is very useful when you want to search for videos too!

In the uploadWidget function, we called the cloudinary.openUploadWidget function and attached it to the “Upload Video” button. When the user clicks the button, it opens the widget. Replace the cloud_name & upload_preset values with your credentials from Cloudinary dashboard.

Sign in to your app, head over to the upload videos route and try uploading a video.


Upload Widget


Uploading the video…

It uploads the video straight to Cloudinary and returns a response object about the recently uploaded video that contains so many parameters such as the unique publicid, secureurl, url, originalfilename, thumbnailurl, createdat, duration and so many others.

4. Display Videos

We need a dashboard to display all the videos uploaded for users to see at a glance. Here, we will make use of Cloudinary’s react component. Install it:

npm install cloudinary-react

Now, open up components/Display.js and modify the code to be this below:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';
import { isLoggedIn } from '../utils/AuthService';
import { CloudinaryContext, Transformation, Video } from 'cloudinary-react';
import axios from 'axios';

class Display extends Component {

  state = { videos: [] };

  getVideos() {
    axios.get('http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json')
          .then(res => {
            console.log(res.data.resources);
            this.setState({ videos: res.data.resources});
    });
  }

  componentDidMount() {
    this.getVideos();
  }

  render() {

    const { videos }  = this.state;

    return (
      <div>
        <Nav />
        <h3 className="text-center"> Latest Videos on Miniflix </h3>
        <hr/>

        <div className="col-sm-12">
          <CloudinaryContext cloudName="unicodeveloper">
            { videos.map((data, index) => (
                <div className="col-sm-4" key={index}>
                  <div className="embed-responsive embed-responsive-4by3">
                    <Video publicId={data.public_id} width="300" height="300" controls></Video>
                  </div>
                  <div> Created at {data.created_at} </div>

                </div>
              ))
            }
          </CloudinaryContext>
        </div>
      </div>
    );
  }
}

export default Display;

In the getVideos code above, we take advantage of a very slick Cloudinary trick that helps grab all videos with a particular tag, when using just one tag. Check it out again:


http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json

So we if had a tag like vimeo, our url will end up with …/vimeo.json. So in the code below, we got all the videos and stored in the videos state.

axios.get('http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json')
          .then(res => {
            console.log(res.data.resources);
            this.setState({ videos: res.data.resources});
    });

The Cloudinary React SDK has 4 major components: Image, Video, Transformation and CloudinaryContext. We are interested in the Video and CloudinaryContext for now. Christian explained how these components work here.

In the render method, we simply just looped through the videos state and passed the public_id of each video into the Cloudinary Video component. The Video component does the job of resolving the public_id from Cloudinary, getting the video url, and displaying it using HTML5 video on the webpage. An added advantage is this: Cloudinary automatically determines the best video type for your browser. Furthermore, it allows the user have the best experience possible by choosing the best from the range of available video types and resolutions.

Run your app, and try to see the list of all videos. It should be similar to this:

You can also manipulate your videos on the fly, with the help of Cloudinary via the Transformation component.

5. Share on Twitter

Go ahead install the react twitter widget component:

npm install react-twitter-widgets

In the components/Display.js file, import the component at the top:

import { Share } from 'react-twitter-widgets'
…
…

Now, add this piece of code just after the div that shows the time the video was created.

…
…
<Share url={`http://res.cloudinary.com/unicodeveloper/video/upload/${data.public_id}.mp4`} />

Check your app again. It should be similar to this:

Now, try to tweet.

Simple! It’s really not that hard. The source code for this tutorial is on GitHub.

Conclusion

Our MVP is ready. Our entrepreneur. Now sit back, relax and watch your account become flooded with investor money! Wait a minute, there is a 90% probability that you’ll called to add more features to this app. Well, I think Cloudinary can still help you with more features such as:

  • Automatic Subtitles and translation
  • Video briefs – short video, based on few gif images that will extract from the uploaded video.
  • Automatic and/or manual video markers – marking specific locations in the video so the user can wait patiently to watch them, or jump directly to these points
  • Find Similar videos by automatic video tagging

Cloudinary provides many options for uploading, transforming and optimizing your videos. Feel free to dive in and explore them.

Source:: scotch.io

Getting Started With Vue Router

By Ed Zynda

Vue is already a great Javascript library that allows you to create some really cool, dynamic, front-end applications. Vue is also great for single page applications (SPA). SPAs work a little differently that your standard backend web application built in something like PHP. Instead of making requests to different routes on the backend and getting a fully rendered page as a response, a SPA does all the page rendering on the front-end and only sends requests to the server when new data is needed or needs to be refreshed or saved.

This can improve the responsiveness of your web application because you can render the pages once and display them dynamically based on the current context of the application. In order to make this work, you need a way to distinguish the different views or pages from eachother. In SPAs this is done with a router. Luckily Vue has a fully supported first-party router library called vue-router.

In this tutorial we’ll setup a simple SPA that will show some information about popular cryptocurrencies. We’ll call it “Crypto Info”. It will have a few pages and link those pages using vue-router. You should already be familiar with Vue as well as creating and using Vue components. Having experience with .vue files is helpful but not required.

Setup

To get started, let’s use the handy Vue command line installer. Open a terminal and run the following.

# install vue-cli
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack router-app

When prompted, answer the questions displayed on the screen like so. Make sure to answer “yes” for installing vue-router.

 This will install Vue 2.x version of the template.

 For Vue 1.x use: vue init webpack#1.0 router-app

? Project name router-app <Enter>
? Project description A Vue.js project  <Enter>
? Author  <Enter>
? Vue build standalone  <Enter>
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Setup unit tests with Karma + Mocha? No
? Setup e2e tests with Nightwatch? No

Once the app is setup, install all the dependencies and start up a dev server.

# install dependencies and go!
$ cd router-app
$ npm install
$ npm run dev

You should now be able to point a browser at http://localhost:8080 and see something like this.

Digging In

The great thing about the Vue command line tool is that it will wire up vue-router for us. To get a better understanding of how it works, we can take a look the boilerplate that was created. Open /src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
  ]
})

The first two lines are importing vue and vue-router. The third line is importing a component called Hello. We will discuss why in a bit. The @ is just a nice alias for the /src directory that was setup in webpack by the Vue command line tool.

Next we tell Vue to use the vue-router plugin. Finally the router is configured with a single route. The router uses Vue components as pages. In the above example we want to render the Hello component whenever a user navigates to the / route.

Next open /src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

The first line is importing Vue again. The second line is bringing in a component called App. This will serve as the root component for the application. The third line is importing the router setup we looked at earlier. The next line tells Vue whether or not to show tips and warnings in the developer console of your browser. In this case it is set to false.

Finally a new Vue instance is created and mounted to the #app div in our html and then it instantiated the App component. We also inject the router configuration from earlier.

Now open /src/App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

This, like I mentioned before, is the root component. It will serve as the point from which our page components will be rendered. Note that all the components we will use are in .vue files which allows us to save the template, javascript and styling into a single file.

Within the tag we just have some simple markup. The important piece though is the tag. The router uses this tag as a container for rendering the different components tied to the different routes. Just think of it as a placeholder.

The tag just contains a simple Vue component object that does nothing. The tag just contains some nice styling boilerplate provided by the Vue command line tool.

Now open /src/components/Hello.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
      <li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
      <li><a href="https://gitter.im/vuejs/vue" target="_blank">Gitter Chat</a></li>
      <li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
      <br>
      <li><a href="http://vuejs-templates.github.io/webpack/" target="_blank">Docs for This Template</a></li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
      <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
      <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
      <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
      <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

This is very similar to the App component. Again, within the tag there is the HTML markup for the component. In this case it’s all the links and text shown when we pointed our browser to http://localhost:8080. This is because in our router config, we specified that / or the root path of our application should point to Hello.vue.

Now let’s get rid of the default content and create a simpler home page. Edit Hello.vue to look like the following:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
  export default {
    name: 'Hello',
    data () {
      return {
        msg: 'Welcome to Crypto Info'
      }
    }
  }
</script>

If you reload, you should now see a page like this.

Creating and Linking to Routes

Now let’s create a new page and add some links for navigating between the two. Open /src/router/index.js and edit it to look like the following.

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import About from '@/components/About'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/about',
      name: 'About',
      component: About
    }
  ]
})

We’ve added a new route /about that points to a new component called About. We’ve also imported the new component at the top. We will create this shortly.

Now open /src/App.vue and edit the section to look like this.

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-link :to="{ name: 'Hello' }">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-view></router-view>
  </div>
</template>

As you can see, we added two tags using two different methods. The router uses to create html links to routes you created. The first method uses a named route. If you recall, in /src/router/index.js we added the name parameter to our routes. In this case the name of the route is Hello just like the component it points to. The second method is the standard method and just specifies the path we want to link to.

If you refresh the browser, you should see the original welcome page but with two links added.

If you click the About link, you will get a blank page. This is because we haven’t created the component yet. Let’s fix this be creating /src/components/About.vue.

<template>
  <div class="about">
    <h1>What is a Crypto-Currency?</h1>
    <p>
      It's a digital currency in which encryption techniques are used to regulate the generation of units of currency 
      and verify the transfer of funds, operating independently of a central bank.
    </p>
  </div>
</template>

<script>
export default {
  name: 'About'
}
</script>

Now if you refresh the browser and click About you should see the new page.

Dynamic Routes

So we can create a new page and a route to point to it but what about passing parameters? We’ll need a page that displays some useful info about various crypto currencies based on a string id passed in the URL. Let’s make that happen. Open /src/router/index.js again and add a third route.

...
import Users from '@/components/Coins'

...

export default new Router({
  routes: [
    ...
   {
      path: '/coins/:id',
      name: 'Coins',
      component: Coins
    }
  ]
})

In order to display up-to-date information on the various currencies, we’ll use the popular axios http client to fetch data from the free Coin Market Capitalization API. We’ll accept a string parameter in the URL called :id. This will be passed to the API to retrieve the relevant data.

First we need to install axios.

npm install --save axios

Next create a file called /src/components/Coins.vue

<template>
  <div>
    <p>Name: {{ coin.name }}</p>
    <p>Symbol: {{ coin.symbol }}</p>
    <p>Price (USD): {{ coin.price_usd }}</p>
  </div>
</template>
<script>
  import axios from 'axios'

  export default {
    name: 'Coins',

    data() {
      return {
        coin: {}
      }
    },

    created() {
      this.fetchData()
    },

    watch: {
      '$route': 'fetchData'
    },

    methods: {
      fetchData() {
        axios.get('https://api.coinmarketcap.com/v1/ticker/'+this.$route.params.id+'/')
        .then((resp) => {
          this.coin = resp.data[0]
          console.log(resp)
        })
        .catch((err) => {
          console.log(err)
        })
      }
    }
  }
</script>

You’ll notice that in the data object of our component, we declare an empty object called coin. This will store our coin information after it is fetched. In the section we have some markup to display the name, symbol and US dollar price of the coin. The created method is a special hook used by Vue that is called before the component is rendered. In this case we are calling the fetchData method which is making a GET request with axios to the Coin Market Capitalization API and passing the :id parameter at the end.

We get the parameter from the $route object params property. This object is auto injected by VueRouter. The paramater we want is the :id parameter which we defined in our router file. On success, as defined in the the then promise method, we save the data returned into our coin object. This is then rendered on in the template.

One other thing we need is to add a watch hook for the $route object. VueRouter components are only rendered once for speed. If you need to rerender, you need to do that manually so in this case we want to rerender when the :id parameter in $route changes and then fetch new data.

Now lets create a few more links in /src/App.vue to see how this new page might be used.

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-link :to="{ name: 'Hello' }">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/coins/ethereum">Ethereum</router-link>
    <router-link to="/coins/bitcoin">Bitcoin</router-link>
    <router-view></router-view>
  </div>
</template>

If you refresh the browser and click on Ethereum you should see something like this.

Now click on Bitcoin and you should see relevant information for that coin as well. If you want to try out other coins, have a look at https://api.coinmarketcap.com/v1/ticker/ and paste a few ids from the list into the URL of our app.

Conclusion

That’s how easy it is to get started with Vue Router. There are a bunch of other great features as well and you can read about them in the official documentation. I hope this tutorial is enough to get you started making some cool SPAs in Vue!

Source:: scotch.io

Deploying Angular to Azure

By John Papa

Deploying Angular to Azure

The Angular CLI makes it easy to build a production ready Angular app. The next step is getting that app up and in the cloud. This is where a CI process helps take that code from Github, build it properly, and the deploy it to Azure. I outlined the detailed steps below if you want to try this for yourself.

If you want to learn how to build your Angular app using the Angular CLI, check out my course on Pluralsight.

You can also watch these steps in this 3 minute video.

Prerequisites

Create an account (consider the free trial) with Azure and create and Web App Service.

If you have not already done so, go to https://www.visualstudio.com and sign up/in to your account. Then create a team and project.

Start from your project’s home page.

Deploying

  1. Go to the Build and Release menu and select Builds
  2. Click the New button to create a new build
  3. Start with an empty process

Get Your Code

  1. Under Process, click on Get Sources
  2. Select Github, enter your authorization, and select your repository and branch

Install the Angular CLI

  1. Click Add Task, on the left, search for npm on the right
  2. Select npm (run an npm command) and click Add
  3. Enter a name such as install the angular cli
  4. Enter the npm command as install
  5. Enter the arguments as @angular/cli -g

Install the Project’s NPM Packages

  1. Click Add Task, on the left, search for npm on the right
  2. Select npm (run an npm command) and click Add
  3. Enter a name such as install packages via npm
  4. Enter the npm command as install

Build the Project with the Angular CLI

  1. Click Add Task, on the left, search for command line on the right
  2. Select Command Line and click Add
  3. Enter a name such as build the angular app
  4. Enter the tool as ng
  5. Enter the arguments as build --prod

Install the Express Server’s NPM Packages

  1. Click Add Task, on the left, search for npm on the right
  2. Select npm (run an npm command) and click Add
  3. Enter a name such as npm install in the dist folder for express
  4. Enter the working folder as dist/
  5. Enter the npm command as install

Deploy to Azure

  1. Click Add Task, on the left, search for azure app service deploy on the right
  2. Select Azure App Service Deploy and click Add
  3. Enter a name such as Azure App Service Deploy: my-app
  4. Select your Azure subscription
  5. Select your app service name
  6. Set the package or folder to dist/
  7. Select the checkbox for Generate Web.config
  8. Enter the Web.config parameters as -Handler iisnode -NodeStartFile index.js -appType node
  9. Select the checkbox for Publish using Web Deploy
  10. Check the box for Remove additional files at destination

Run this Process on all Commits/Merges to Github

  1. Go to triggers in the upper left and enable continuous integration
  2. Press the Save and Queue button

Then you can queue it and go watch the build’s progress!

Source:: johnpapa

Node.js Weekly Update - 16 June

By Ferenc Hamori

Node.js Weekly Update - 16 June

Below you can find RisingStack‘s collection of the most important Node.js updates, projects, tutorials & Node related conferences from this week:

Two-Factor Authentication with Node.js

Passwords can be guessed, phone numbers can be spoofed, but using two-factor authentication essentially requires that user be in possession of a physical device with an app like Google Authenticator, loaded with a secret key for the given app, which provides an extra layer of security.

Node.js Weekly Update - 16 June

Since I use 2FA so often, I wanted to see how the process is managed by a developer for its users. That would include generating the secret key, creating its QR code representation, scanning the code into Google Authenticator (done by the user), and then validating that GA-given code against the user’s key. I found an easy to use Node.js library, speakeasy, to do so!

Habits of a Happy Node Hacker 2017

Here are 8 habits for happy Node hackers updated for 2017. They’re specifically for app developers, rather than module authors, since those groups have different goals and constraints.

  1. Lock Down Your Dependency Tree
  2. Hook Things Up
  3. Modernize Your JavaScript
  4. Keep Your Promises
  5. Automate Your Code Formatting with Prettier
  6. Test Continuously
  7. Wear Your Helmet
  8. HTTPS all the things

Build a “Serverless” Twilio SMS + Call Forwarding Bot in 7 Minutes using Node.js + StdLib

Learn how you can build a Twilio Messaging Hub in only 7 Minutes with StdLib!

Node.js Weekly Update - 16 June

What You’ll Need Beforehand:

  • 1x Twilio Account

  • 1x Command Line Terminal

  • 7x Minutes (or 420x Seconds)

Survey: Node.js Developers Struggle with Debugging & Downtimes

In this article we summarize the insights we learned from our latest survey on developers problems with Node.js Debugging, Downtimes, Microservices & other pain-points.

Node.js Weekly Update - 16 June

Key Findings of the Node.js Survey:

  • 29,27% of Node.js developers experience downtimes in production systems at least once a week, 54,02% at least once a month.

  • 27,50% of Node developers responding to the survey never experience downtimes.

  • 42,82% of the respondents spend more than 2 hours a week with debugging their Node.js applications, including the 17,09% who spends more than 5 hours.

  • The developers building a microservices architecture with Node spend more time with debugging. The advantage of microservices + Node manifests in the form of fewer downtimes.

Nodevember 2017 Tickets are available

Nodevember is a two-day conference touching on all aspects of Node and JavaScript. The conference includes seminars, workshops, tutorials, code sprints, and lightning talks.

Node.js Weekly Update - 16 June

The fourth annual conference will be held November 27th and 28th, 2017 in Nashville, TN.

Node Core Changes:

⬢ Node v8.1.1 (Current)

  • Child processes
    • stdout and stderr are now available on the error output of a failed call to the util.promisify()ed version of child_process.exec.
  • HTTP
    • A regression that broke certain scenarios in which HTTP is used together with the cluster module has been fixed.
  • HTTPS
    • The rejectUnauthorized option now works properly for unix sockets.
  • Readline
    • A change that broke npm init and other code which uses readline multiple times on the same input stream is reverted.

⬢ Node v8.1.2 (Current)

Fix broken process.release properties in 8.1.1 causing failure to compile native add-ons on platforms other than Windows. This is a fix in the Node.js build process so there are no additional code commits included on top of 8.1.1.

Node.js Related Conferences

Open CFP’s

Upcoming Events

Source: The Node Foundation Newsletter

Vulnerable npm Packages Discovered:

Cross-Site Scripting (XSS)

Directory Traversal

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read about Node 8’s util.promisify(), handling 100 gigabytes of data with MySQL & Node.js, understanding lock files in npm 5 and a comaprison of Node 6 & 8.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Alpha Testers Wanted for Progressive Web App Tools for VS Code

By John Papa

Alpha Testers Wanted for Progressive Web App Tools for VS Code

I love the Web and I love tools that make creating awesome things for the Web easier! When creating Progressive Web Apps (PWAs) there are a lot of options. So it just makes sense to create an extension for VS Code to help design PWAs. As the title mentions, this is an alpha.

I’d love some of your help to test this extension. Give it a run through and see what we might want to change, add, remove, or document further. My first cut at this extension can be found here. Please refer to the GitHub repo to create any issues. I will iterate on this extension a few times, til I have something that is useful to the wider audience creating PWAs.

Alpha Testers Wanted for Progressive Web App Tools for VS Code

A few words about this extension’s goals. The extension’s snippets should:
1. Create the code we know we need and only that code.
2. Omit any code that we “might” need in the future. If we need it, add it later.
3. Work for Angular, React, Vue, pain old JavaScript
4. Provide simple and functional steps to create a PWA on the major platforms listed above

Note that some of these are open issues in the GitHub repo. So feel free to help contribute to any issues that are marked “help wanted”.

Thanks for your help in advance!

Source:: johnpapa

The Ultimate Guide to Progressive Web Applications

By Matt Raible

Progressive Web Apps, aka PWAs, are the best way for developers to make their webapps load faster and more performant. In a nutshell, PWAs are websites that use recent web standards to allow for installation on a user’s computer or device, and deliver an app-like experience to those users.
Twitter recently launched mobile.twitter.com as a PWA built with React and Node.js. They’ve had a good experience with PWAs, showing that the technology is finally ready for the masses.

Twitter Lite sees 75% increase in tweets with new PWA and reduces Data usage. Read all about it https://t.co/ihi3N0cIAN

— Chrome Developers (@ChromiumDev) May 17, 2017

In this guide, you’ll learn about the essential ingredients in a PWA, how to install one, why you should build one, and how they stack up against hybrid and native applications.

A Deeper Dive – What is a PWA?

A PWA is a web application that can be “installed” on your system. It works offline when you don’t have an internet connection, leveraging data cached during your last interactions with the app. If you’re on a desktop, using Chrome, and have the appropriate flags turned on, you will be prompted to install the app when you visit the site.

For example, enable the following flags in Chrome by copying and pasting the following URLs into Chrome.


chrome://flags/#enable-add-to-shelf

chrome://flags/#bypass-app-banner-engagement-checks

Click the blue “Relaunch Now” button at the bottom of your browser after enabling these flags. Now if you visit a site like https://hnpwa.com, you’ll see an installation prompt at the top of the page.

Click the “Add” button and you’ll see a dialog to name the app, populated with information from the app’s manifest.

This adds the application to a “~/Applications/Chrome Apps” directory on a Mac. If you launch the apps, they will run in Chrome rather than having their own icon. On an Android phone, their icon and launch behavior will resemble that of a native application.

You can use Chrome’s Developer Tools > Network tab to toggle “Offline” and reload the application. You’ll notice it still loads the data rather than saying it can’t reach the server.

Why Should You Build a PWA?

You should make your webapp into a PWA because it’ll reduce the time it takes for your app to load and it’ll give your users a better experience. Having it load over HTTPS is a good security practice and adding icons (using a web app manifest) is something you’d do anyway. Having a cache-first service worker strategy will allow your app to work offline (if the user has already loaded data), alleviating one of the biggest issues with webapps.

There are a number of other performance recommendations you can implement in your webapp. While the following list is not required for PWAs, many PWAs employ these elements:

  • Implement the PRPL pattern:

    • Push critical resources for the initial URL route.

    • Render initial route.

    • Pre-cache remaining routes.

    • Lazy-load and create remaining routes on demand.
  • Use to tell your browser to load a resource you know you’ll eventually need. This is a W3C Standard specification.

  • Use HTTP/2 and server push to “push” assets to the browser without the user having to ask for them.

  • Use code-splitting and lazy-loading for granular loading of application pages/features.

Mariko Kosaka created some drawings to show the difference between HTTP/1 and HTTP/2. I think it illustrates the performance gains provided by HTTP/2 nicely. Note that HTTP/2 requires HTTPS, just like PWAs do.

HTTP 2

Dynamic Caching and Your PWA

If you’re going to build a PWA and leverage service workers, you should become familiar with Chrome Developer Tools’ Application tab. This tab provides the ability to manipulate service workers so they update on reload.

If you don’t check this box, developing a PWA will be a frustrating experience. The reason is because everything will be cached in your browser and when you update files in your editor, they won’t be reloaded in your browser.

For a great resource on Chrome’s Developer Tools, I recommend Umaar Hunsa’s Dev Tips.

Developing PWAs can be painful because it will cause your application to do aggressive caching in your browser. Web developers have been fighting for ages to get the browser to not cache assets, so PWAs kinda go against the grain for web developers. One workaround is to comment out your service worker registration until you package for production. This can be done by simply commenting out registration of a service worker in your index.html. For example:


<!-- un-comment this code to enable service worker in production

<script>

    if ('serviceWorker' in navigator) {

     navigator.serviceWorker.register('service-worker.js')

      .then(() => console.log('service worker installed'))

      .catch(err => console.error('Error', err));

}

</script>-->

If your app is so dynamic that you don’t want anything cached, a PWA might not be right for you. However, you should still look into serving it over HTTPS and using HTTP/2 for better security and faster performance.

PWAs and Hybrid Apps vs. Mobile Apps

Adding PWA support is important so people with slow connections and affordable smart phones can use your webapp more easily. If your app is large and you can’t load parts of it lazily (meaning loading it on-demand rather than at the beginning), bundling it all up in a hybrid app with Cordova might make sense. If your app does intense tasks or is highly interactive (like a game), coding it with native SDKs is likely a good option.

If you’re interested in learning more about using Cordova with Ionic and Spring Boot, you can check out my recent tutorial.

PWAs are useful for apps like Twitter and news sites because they have a lot of text that you’ll read, but not necessarily interact with. Having it as a PWA allows you to open the app, load its data, then read its contents later when you’re offline. This should work in a normal web application, but I’ve noticed that some browsers will try to reload the page when you open them, resulting in a dreaded “server not found” error.

However, neither of these techniques will help your users with slow connections and less powerful smartphones. Even if you choose to create a native app, it’s still wise to create a lightweight PWA app that can load in seconds and give your users something to work with.

PWAs are the way of the future, and the now. Most browsers support it, with notably absent support in Safari. It’s funny to see that Apple is blocking PWA support on iOS when they only supported web apps on the first iPhone. However, they do list service workers as “under consideration” in WebKit. Meanwhile, Google is championing the effort, with vast amounts of documentation on PWAs, dedicated developer advocates for PWAs, and many conference sessions on the subject at Google I/O 2017.

Sam Delgado believes “If it weren’t for Apple, hybrid app development would be the clear winner over native”. In this article, he laments that there’s one major disadvantage to the hybrid approach for iOS: you still have to go through Apple’s complicated setup for Xcode, provisioning profiles, needing a Mac to compile, using TestFlight for betas, and the app review process. The iOS WebView is another reason the experience isn’t great. WKWebView offers a better experience, but requires some hacky workarounds. He ends the article noting that the “Hybrid vs Native” debate will likely continue until Apple provides a pleasant development experience for hybrid applications.

Matt Asay thinks that Apple has many reasons to say no to PWAs, but they won’t allow Android to offer a better web experience.

Jason Grigsby writes, “Despite the fact that iOS doesn’t support the full feature set of Progressive Web Apps, early evidence indicates that Progressive Web Apps perform better on iOS than the sites they replace.”

Not only that, but PWAs offer a lower cost mobile presence.

Yes, there are some additional cons like some native APIs not being available and that you can’t find PWAs in the App Store or Google Play. The native API issues might be around for awhile, but the ability to locate an app by URL (versus searching a store) seems easier to me.

Chrome and Android have deep integration for PWAs. According to the Chromium Blog:

When installed, PWAs appear in the app drawer section of the launcher and in Android Settings, and can receive incoming intents from other apps. Long presses on their notifications will also reveal the normal Android notification management controls rather than the notification management controls for Chrome.

Developers have pondered if PWAs should be findable in Google Play. So far, Google has not released any plans to do so.

Another thing to consider is how much WebStorage on the device your application will need. Eiji Kitamura conducted research on quotas for mobile browsers in 2014 and found that most browsers support up to 10MB of LocalStorage. More storage is typically available in Application Cache, IndexedDB, and WebSQL, but only on desktop browsers. For example, Firefox on Android allows the Application Cache to use up to 500MB on desktop, but only 5MB on mobile. Users can change this quota on their device, but the application developer cannot control this setting. You can see the quotas for your browser by visiting Browser Storage Abuser.

So, what do you need to know to start building?

PWA Requirements: HTTPS, Service Workers, and Web App Manifest

The requirements for a PWA can be quickly added to almost any web application. All you need to do is the following:

  1. Deploy it to a public web server and force HTTPS.

  2. Create and include a JavaScript file with code to cache network requests.

  3. Create and include a web app manifest.

To see how to add these features to an Angular application, see my Build Your First Progressive Web Application with Angular and Spring Boot blog post on Okta’s developer blog. This article shows you how to add a service worker, a manifest with icons, and deploy it to CloudFoundry with HTTPS. Not only that, but it scores a 98/100 using the Lighthouse Chrome Extension.

Lighthouse Report

Scott Domes has a similar tutorial that will walk you through the basics of building a PWA in React.

Angular will soon have built-in service worker support. Create React App (a popular starter tool for React) now has PWAs by default as one of its features.

PWA Reference Apps and Stats

HN PWA is a reference for how to build efficient PWAs with different frameworks. It’s similar to TodoMVC, but for progressive web apps. For each framework, it includes its Lighthouse score and time to interactive over a slow connection, as well as a faster 3G connection.

PWA Stats is a website with statistics about the cost savings and improved performance gained by implementing progressive web apps. Some examples:

  • Google found that Progressive Web App install banners convert 5-6x more often than native install banners.

  • The Forbes Progressive Web App’s homepage completely loads in just 0.8 seconds.

  • The Weather Channel saw a 80% improvement in load time after shipping Progressive Web Apps in 62 languages to 178 countries.

CSS Tricks notes that two other PWA galleries exist:

Framework Support in React, Angular, and Vue.js

Support for PWA features already exist in some of the more popular JavaScript framework application generators. However, you don’t need to have these features created for you, you can also add them to an existing application.

HTTPS has gotten much easier with free certificates from Let’s Encrypt and AWS Certificate Manager. Deploying static web apps that access dynamic data has been vastly simplified by CDNs, AWS, CloudFoundry, and Heroku. Heroku also has support for automated certificate management using Let’s Encrypt.

You can generate a manifest.json file and icons for your PWA using http://realfavicongenerator.net and http://preview.pwabuilder.com.

For online/offline data syncing, you can use solutions like IndexedDB, PouchDB, or roll your own with the Background Sync API. This feature is available in Chrome desktop and Android since version 49.

Angular

You can add service worker support and app shell for offline Angular 2+ applications. With native service worker support headed to Angular soon, you can tell the Angular team is taking the PWA challenge to heart.

Maxim Salnikov’s Progressive Web Apps using the Angular Mobile Toolkit workshop from Angular Summit 2017 shows how this new support will look using Angular CLI. You will need to run a command:


ng set apps.0.serviceWorker=true

If you don’t have @angular/service-worker installed, you will see a message:


Your project is configured with serviceWorker = true, but @angular/service-worker is not installed.

Run `npm install --save-dev @angular/service-worker`

and try again, or run `ng set apps.0.serviceWorker=false` in your .angular-cli.json.

Ionic is a framework that leverages Angular to create native apps with web technologies. It leverages Cordova to run the app on phones but also has built-in service worker and manifest support if you want to deploy your app to the web.

See my tutorial about developing mobile applications with Ionic and Spring Boot to learn more. Below is a screenshot of the completed application in the tutorial.

Mmmmm, Guinness

NativeScript is another option for developing mobile apps with Angular. The big difference between it and Ionic is that it uses the native platform’s rendering engine instead of WebViews. NativeScript does not support building PWAs.

React

When you create a React application using Create React App (version 1.0+), a manifest is generated, and an offline-first caching strategy service worker. If you already have a React application, Create React App’s 1.0 release notes tell you how to turn your app into a PWA.

Preact is an alternative implementation of React that’s built for speed. It’s a much smaller library (~3KB) that implements the same ES6 API, components, and Virtual DOM support as React. Using it instead of React means your application will have less JavaScript to download, parse, and execute.

Vue.js

Vue.js has a command line tool called Vue-CLI. Addy Osmani recently added a PWA template, so you can generate a new Vue.js PWA app with the following commands:


npm install -g vue-cli

vue init pwa my-pwa-project

If you already have a Vue.js application, see Charles Bochet’s article on creating a PWA with Vue.js.

Learn More

I love apps that work when I’m offline, especially when flying and traveling. Internet connectivity can be spotty when you’re moving and apps that don’t require connectivity are great. For instance, I wrote the first draft of this article on my phone using Google Docs, without service. Although Google Docs isn’t a PWA, it demonstrates the allure of making your web app work offline. Native apps have been caching data and providing offline access for years. Now that web apps have similar features, we should embrace them and use them! It’s a great time to be a web developer; we can make the web better together.

If you’re interested in staying up to date on what’s happening in the PWA world, I recommend following Alex Russell (@slightlylate), Addy Osmani (@addyosmani), and Sean Larkin (@thelarkinn) on Twitter.

Or, you can check out any of these great resources:

Example Applications

Ready to get your feet wet building an app? You can find some interesting PWA tutorials here:

This post was sponsored via SyndicateAds.

Source:: scotch.io