Dzone Guidetowebdevelopment 2016

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

BROUGHT TO YOU IN PARTNERSHIP WITH

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DEAR READE R ,

TABLE OF CONTE NTS

Welcome to the first edition of the DZone Web Developer Guide


and our 12th DZone Research Guide of 2016. At the end of each

EXECUTIVE SUMMARY
BY MATT WERNER

KEY RESEARCH FINDINGS


BY G. RYAN SPAIN

FUNCTIONAL REACTIVE UI PROGRAMMING


BY MICHAEL HEINRICHS

year I often reflect on the past months. The rate of change around
web development has been increasing. Hardly a day goes by where
we dont see a new framework, or a new technique. Methods that
seemed advanced when we overhauled DZone.com just 1.5 years
ago, seem much more commonplace now. And who remembers
Web 2.0? That seems like ancient history today, when in truth it
was just a few short years ago.
The world of Web Development is growing. JavaScript, and other
front-end technologies, are by far the most popular languages
on Stack Overflow. The DZone Web Dev portal has been steadily
growing, and is now our second most popular portal. Modern-day
web development spans both the front-and the back-end. Today,
the full-stack developer often reaches into their toolbox and pulls
out JavaScript, as tools like Node.js allow the developer to leverage
a single language across the entire stackallowing for focus and
productivity. The number of developers familiar with JavaScript
ensures that your projects will have an easier time finding qualified
people as well.
With a low barrier to entry, many new developers (and experienced
ones as well) are building web applications. Looking back to our
recent Application Security Guide, XSS (Cross-Site Scripting)
and other front-end attacks are the most prevalent. How will we
enforce security in this fast-moving and fast-growing world where
new frameworks appear nearly daily? As we begin to rely more and

10 TOTALLY MODULAR, DUDE!


BY BILL SOUROUR
13 CHECKLIST: DEBUGGING JS WITH THESE 10 TIPS
BY FREYJA SPAVEN & DANIEL WYLIE
14 INFOGRAPHIC: SURVIVAL INSTINCTS: MOST TRUSTED
TECH FOR THE WEB DEV JUNGLE
16 ADDING AUTHENTICATION TO A WEB APPLICATION
WITH AUTH0, REACT, AND JWT
BY JOS AGUINAGA
19 DIVING DEEPER INTO WEB DEV
22 EXECUTIVE INSIGHTS ON WEB APPLICATION DEVELOPMENT
BY TOM SMITH
24 EMBRACING SIMPLICITY WITH STATIC SITE GENERATORS
BY RAYMOND CAMDEN
27 WEB DEV SOLUTIONS DIRECTORY
31 GLOSSARY

more on third-party APIs, how do we ensure that those services are


following the best practices to secure our data? Are we up to the
task of training this next generation of developers on the security
requirements of the modern web?
This guide attempts to answer some of these questions and more,
starting by walking you through some of the research findings that
we discovered while talking to our audience and then diving into
some great articles by industry experts. It is to-the-point and one

MARKETING
KELLET ATKINSON

EDITORIAL
CAITLIN CANDELMO

BUSINESS
RICK ROSS

DIRECTOR OF MARKETING

DIRECTOR OF CONTENT +
COMMUNITY

CEO

MATT WERNER

PRESIDENT & CTO

CONTENT + COMMUNITY MANAGER

JESSE DAVIS

LAUREN CURATOLA
MARKETING SPECIALIST

KRISTEN PAGN
MARKETING SPECIALIST

NATALIE IANNELLO
MARKETING SPECIALIST

topics from arranging your projects more effectively and tips

MIKE GATES

DIRECTOR OF PRODUCTION

SARAH DAVIS

ANDRE POWELL

handle user management and authentication all without running

SR. PRODUCTION COORDINATOR

a server. Some in the industry will say that this is the way of the

G. RYAN SPAIN

telland given the rate of change lately, I imagine that time will
be soon!

NICOLE WOLFE

PRODUCTION
CHRIS SMITH

for debugging your JavaScript, to being able to host sites or even

futureeverything delegated to third-party services. Time will

CONTENT + COMMUNITY MANAGER

CONTENT COORDINATOR

of the most technically deep guides that we have published.


The articles are filled with code snippets and examples on

MICHAEL THARRINGTON

CONTENT COORDINATOR

CONTENT COORDINATOR

TOM SMITH
RESEARCH ANALYST

PRODUCTION PUBLICATIONS EDITOR

ASHLEY SLATE
DESIGN DIRECTOR

MATT SCHMIDT

EVP & COO

MATT OBRIAN

DIRECTOR OF BUSINESS
DEVELOPMENT
sales@dzone.com

ALEX CRAFTS
DIRECTOR OF MAJOR ACCOUNTS

JIM HOWARD
SR ACCOUNT EXECUTIVE

JIM DYER
ACCOUNT EXECUTIVE

ANDREW BARKER
ACCOUNT EXECUTIVE

CHRIS BRUMFIELD
ACCOUNT MANAGER

ANA JONES
ACCOUNT MANAGER

Thank you for reading the first edition of The DZone Guide to Web
Development, and thank you to all our sponsors and contributors
who helped make this years series be the best one yet. Happy
Holidays to everyone and I hope you enjoy reading this guide as
much as we enjoyed making it!

BY MATT SCHMIDT
PRESIDENT & CTO AT DZONE
RESEARCH@DZONE.COM

WANT YOUR SOLUTION TO BE FEATURED IN


COMING GUIDES?
Please contact research@dzone.com for submission
information.
LIKE TO CONTRIBUTE CONTENT TO COMING GUIDES?
Please contact research@dzone.com for consideration.
INTERESTED IN BECOMING A DZONE RESEARCH
PARTNER?
Please contact sales@dzone.com for information.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

SPECIAL THANKS
to our topic experts,
Zone Leaders, trusted
DZone Most Valuable
Bloggers, and dedicated
users for all their
help and feedback in
making this report a
great success.

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Executive
Summary
BY M AT T W E R N E R
C O N T E N T A N D C O M M U N I T Y M A N AG E R , DZO N E

DOMINANT TECHNOLOGIES EMERGE


DATA

Across several questions, clear technological favorites

emerged. For instance, Chrome was the most popular browser


to develop for vs. second-place Firefox (96% to 77%). For package
management, npm is used more than bower (59% to 37%), for
testing, Selenium is used more than Jasmine (64% to 31%), and
for real-time streaming apps, WebSocket API (77%) was used far
more than the next most popular method: polling (32%).
IMPLICATIONS

While there may be debates over the quality of

one tool or framework versus another, tools like jQuery, used


by 84% of respondents, and AngularJS can quickly become

While the launch of smartphones has truly changed


the world, most of us interact with the online world

the dominant technology in a particular category. This can


be due to the strength of the community, documentation, or
familiarity with older tools, such as jQuery or MySQL.

through web apps rather than mobile apps. JavaScript


Keeping up with whats considered

in particular has been one of the most important

RECOMMENDATIONS

technologies in modern web development, allowing

the most popular language or technology is essential for

web apps to have similar capabilities as native


mobile apps. In our first annual web dev survey, 97%
of respondents said they wrote JavaScript for the

web developers in the market, as these are skills that will


be easily transferable between projects or jobs. However,
as demonstrated by the statistically significant number of
respondents who were unhappy with Angular 1, the most

browser, compared to 39% for mobile-only or 26% for

popular JavaScript framework, the most popular tool may not

hybrid mobile apps. The prevalence of responsive

be the best, so it would behoove developers to explore other

design has also kept web apps relevant, as its now

options either at work or in their spare time.

standard practice to design responsive sites to adapt


to any screen or device. To discover what developers

MORE FOCUS ON THE BACKEND

were using for their web development needs, DZone

DATA

surveyed 598 developers and tech professionals across

said they do server side. 56% said they worked on the full

the world, most of whom had extensive experience

stack, and only 8% work mostly on the front end.

working at companies with over 100 people.

97% of developers said they work on the browser, 39%

IMPLICATIONS

More web development is being done on the

backend except in the cases of mobile web development,

IS ANGULAR 1 DEAD?
DATA

where more is done on the frontend. Since more and more

Angular was the most popular framework among

developers have determined that capabilities like business

respondents (69%). 19% of total respondents who have used

logic and enterprise integration should be relegated to the

Angular 1 would not use it again. Less than 1% of users have

backend, more web developers need to have a knowledge of

used either Angular 2 or React and would not use either again.

full-stack development.

IMPLICATIONS

Angular 1 took the development world by

RECOMMENDATIONS

Its clear from the data that most web

storm, but its issues have been well-documented, and there

developers need a knowledge of full-stack development.

is a statistically significant difference between the number of

Continued education into new technologies like Node.

users unhappy with Angular 1 over the next two most popular

js or Express.js will be essential to staying competitive

client-side frameworks: React and Angular 2.

in the job market and adding functionality to web apps.


53% of respondents already deliberately switch frontend

RECOMMENDATIONS

Angular 1 is clearly not without its

and backend development roles to build full-stack skills.

faults. The Angular team has attempted to address them in

In addition, DZone research has found that full-stack

Angular 2, which was released in mid-2016. If developers

developers are more likely to expand their knowledge of web

are finding that they have a lot of issues with their Angular

development. For example, full-stack developers are more

1 applications, Google has extensive documentation on

focused on responsive design than backend developers (95%

how to use Angular 2s migration tools. Based on audience

vs. 89%), and are more likely to use newer JS features such as

responses, the satisfaction with Angular 2 is high, and it may

modules and classes than developers who only work on the

be worth the time to migrate Angular 1 apps.

front or backend.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Key
Research
Findings
BY G . R YA N S PA I N
P R O D U C T I O N C O O R D I N ATO R , DZO N E

598 software professionals completed DZones 2016


Web Development Reesearch Guide survey. Of these
respondents:
38% have a primary role as developers/

FRAMEWORK POPULARITY
The AngularJS framework has had an enormous impact
on web development since its release in 2010. Among our
survey respondents, Angular was the most widely used
framework, with 69% use, well ahead of second- and thirdplace frameworks Node.js (50%) and React (30%). However,
attitudes towards Angular, at least Angular 1, suggest
that developers may be searching for alternatives to the
original Angular framework. 11% of respondents said they
have used Angular 1 and would not use it again, almost
1/5 of the respondents who said they have used Angular at
all. Compared to attitudes about React and Angular 2, the
two next most popular client-side JavaScript frameworks,
each of which having <1% of users saying they would not
use again, this number is not insignificant. And while
React and Angular 2 are not yet as widely used, with
30% of respondents saying they have used each in some
capacity, interest in both of these frameworks is high: 50%
of respondents said they have heard of and want to use
each framework. While the broad interest in Angular 2 likely
means Angular is not going anywhere soon, these results
indicate a move away from Angular 1, and possibly toward
other, non-Angular frameworks.

engineers, and 33% are developer team leads.


60% have 10 years of experience or more as

software professionals, and 37% have 15 years


or more.
40% work for companies headquartered in

Europe, 29% for companies headquartered in


the US, and 12% for companies headquartered
in South America.
17% work for companies with 10,000 employees

or more, 19% for companies with between 1,000


and 10,000 employees, and 24% for companies
with between 100 and 1,000 employees.
HOW FAMILIAR ARE YOU WITH THESE CLIENT-SIDE JAVASCRIPT
FRAMEWORKS?

FRONTEND VS. BACKEND


Almost all survey respondents (97%) said they do some
development for the browser, compared to 39% who said
they do serverside development. When asked if they
worked more on the frontend, backend, or the full stack
of their web applications, 56% of respondents said they
work on the full stack, while only 8% said they work more
on the frontend. Regarding the division of work between
client and server, a large majority of respondents said
they have the serverside integrate between systems like
database, message queues, EIS (74%), expose APIs (80%),
and do the business logic of the application (76%), and
the frontend generates the user interface (69%). These
behaviors change based on whether respondents said they
IN YOUR WEB APPLICATIONS, HOW DO YOU TYPICALLY DIVIDE
WORK BETWEEN CLIENT AND SERVER?
80%

ANGULAR 2

70%
60%
50%

ANGULAR

40%
30%
20%

REACT

10%

Never heard
of it

10%

20%

Heard of it, want


to use

30% 40%

50%

Heard of it, not


interested in using

60%

70%

Have used but


would not again

80% 90% 100%

Have used and


would use again

0%

Serverside does
integration bet.
systems like
database, message
queues, EIS

AVERAGE

Serverside
exposes APIs

Serverside
does business
logic

BACK-END DEVELOPER

Serverside
generates UI

Frontend does
integration bet.
systems like multiple
RESTful services,
message queues,
etc.

FRONT-END DEVELOPER

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Frontend
does
business
logic

Frontend
generates
UI

FULL STACK DEVELOPER

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

worked more on application frontends, as well as what kind

respectively). And full-stack respondents were much more

of apps respondents said they are working on (for example,

likely to frequently use popular JavaScript ES6 features

respondents working on mobile versions of a website

like modules (34% vs. 21% and 20%), classes (30% vs. 21%

were more likely than most to have the frontend rather

and 24%), and arrow functions (36% vs. 17% and 28%) than

than the backend perform business logic). And although

frontend or backend respondents.

respondents may have differing views of frontend vs.


backend work, there seems to be some consensus that the
way work is divided between them is important.

FULL-STACK PREFERENCES
The way respondents answered whether they worked more
on the frontend, backend, or full-stack of web apps often
have changed how they answered other questions. Frontend
and backend respondents generally leaned more towards
options that emphasized their frontend or backend focus,
and the full-stack respondents generally fell somewhere
in between. So it was interesting to learn which way fullstack respondents were leaning. As one example, fullstack respondents leaned much more closely to backend
respondents regarding client/server work division. On the
other hand, full-stack respondents leaned towards frontend
respondents when it comes to responsive design; backend
respondents were about twice as likely (11%) to say they
did not use responsive design as frontend (4%) and fullstack (5%) respondents. But full-stack respondents were
more likely than frontend and backend respondents to say
they would not use Angular 1 again (14% versus 6% and 8%,

WHAT ENVIRONMENTS DO YOU WRITE JAVASCRIPT FOR?

CHROME AND OTHER FAVORITES


Google Chrome was shown to be the most popular browser
to develop for, based on our survey responses. 96% of
respondents said they actively Chrome, a wide margin
above runner-up Mozilla Firefox (77%) and third-place
Microsoft Internet Explorer (51%). Chrome wasnt the only
favorite that stood out in this years survey results, though.
Several different solutions stood well over alternatives
in their field and were used by over half of survey
respondents. For module/package management, npm (59%)
was used much more than next-place Bower (37%). For
testing, Selenium ranked first with 64% of respondents
using the testing tool over others, such as Jasmine (31%)
and PhantomJS (28%). The WebSocket API was favored for
pushing data from server to browser among respondents
whose apps need real-time or streaming communication,
with 77% using this method; polling (32%) and HTTP
streaming (26%) were the next most popular. 84% of all
respondents said they use jQuery in developing their
applications, and 61% said they use MySQL for their web
apps database, over MongoDB and PostgreSQL (both 42%).

ARE YOUR WEB APPS RESPONSIVE?

100%
90%

7.5

80%
70%

YES

60%
50%

92.5

40%
30%

NO

20%
10%
0%

BROWSER

SERVER

HYBRID

MOBILE

(CORDOVA/PHONEGAP)

WHICH FRAMEWORKS OR LIBRARIES DO YOU USE?

WHICH BROWSERS DO YOU ACTIVELY DEVELOP FOR?

90%

100%

80%

90%

70%

80%

60%

70%

50%

60%

40%

50%

30%
20%

40%

10%

30%

0%

REACT

ANGULAR

NODE

jQUERY

SERVER-SIDE DEVELOPMENT

HYBRID MOBILE DEVELOPMENT

MOBILE DEVELOPMENT

AVERAGE/BROWSER DEVELOPMENT

20%
10%
0%

GOOGLE
CHROME

MOZILLA
FIREFOX

INTERNET
EXPLORER

SAFARI

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

EDGE

OPERA

SPONSORED OPINION

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Every great invention and scientific discovery was born

In a world that is changing faster


than ever beforecompanies cant
afford to play it safe or theyll be
surpassed by their competition

from experimentation. Take Marie Curie, who was a


relentless experimenter. Through experimentation, she
became the first woman to be awarded a Nobel Prize, in
1903, for Physics. Further, she was the only person to win
two Nobel Prizes in different sciences when she won the
1911 Nobel Prize for Chemistry. She said, Nothing in life is
to be feared, it is only to be understood. Now is the time to
understand more, so that we may fear less.

Thats why we launched Optimizely X, the worlds first


experimentation platform. Optimizely X empowers
executives, marketing teams, product teams, and
development teams to make better business decisions
and deliver better customer experiences through
experimentation. This represents a quantum leap
forward in what our customers can achieve, by pushing
the boundaries of experimentation and transforming
digital experiences for their customers. With Optimizely
X, you can experiment on any channel and any device
with an internet connection. For more information, visit
optimizely.com/products.

Experimentation is not only a cornerstone of science,


but it is also critical to success in politics, athletics, and
business. Companies often have great ideas, but their
inability to experiment easily leads to the design of safe
and often uninspiring experiences for their customers. In
a world that is changing faster than ever beforea world
where a customer starts a task on one device and finishes
it on another, a world where customers expect companies
to know who they arecompanies cant afford to play
it safe or theyll be surpassed by their competition. As
leaders in this constantly evolving world, our job is not to
have all the answers. Our job is to enable our organization

WRITTEN BY JOHN PROVINE

to be brave and experiment.

DIRECTOR, PRODUCT MANAGEMENT, OPTIMIZELY

Optimizely X Full Stack

By Optimizely

Optimizely X Full Stack lets you quickly and reliably run experiments, learn, and launch
new features anywhere in your technology stack.
CATEGORY

NEW RELEASES

OPEN SOURCE

STRENGTHS

Experimentation
Platform

Monthly

All SDKs

Fast decision engine - Our SDKs bucket users in memory so


experiments have no impact on latency. Feel free to conduct
experiments in performance-critical code paths.

CASE STUDY

Scalable architecture - Our real-time event collection servers

Tripping is the worlds largest search engine for vacation


homes, showcasing about 8 million properties worldwide. A
data-driven organization, Tripping runs iterative A/B tests
to optimize customer experience, and Optimizely X Full
Stack has become the backbone of their test before release
program. When Tripping releases a new product or feature,
the companys development team uses Full Stack to test and
benchmark changes against current metrics to make sure that
there are no unintended consequences post-release. By having
testing integrated on the server-side rather than the frontend, when a feature is already live, Tripping is able to ensure
optimal performance prior to any launch across marketing,
product, and engineering.

BLOG blog.optimizely.com

used by thousands of customers across the globe allow you to get


experiment results immediately.

Traffic splitting - Split traffic to different code paths anywhere


in your technology stack. No network requests needed means no
impact on your apps performance.

Event tracking - Monitor all the conversion metrics and KPIs you
care about.

Open-source SDKs - Install any of our SDKs and run your first
experiment in 10 minutes.

NOTABLE CUSTOMERS
CBS
ADP

TWITTER @optimizely

Clorox
Spotify

HP
LOreal

Microsoft
Adidas

WEBSITE optimizely.com

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Functional
Reactive UI
Programming

QUICK VIEW
01

Using principles of functional


reactive programming for
UI development results in a
straight-forward architecture:
all events and changes move
circular in asingle direction.

02

Data structures are immutable


and the individual components
are purely functional.

03

This allows for simpler testing,


an easy to understand and
follow flow of events, and
great tool support.

BY M ICHAEL HEINRICHS
SOFTWARE ENGINEER AT CANOO ENGINEERING AG

FRONTEND DEVELOPMENT BEYOND THE MVC PATTERN

React.js, Elm, Cycle.js, and other UI frameworks introduced

The DOM-Driver is provided by the framework, while

a new way of building user interfaces. By applying

the other components have to be implemented by the

principles from functional reactive programming to UI

application developer.

development, they even changed how we think about


user interfaces. This article gives a brief introduction
into this new way of building UIs and lists the main

Lets assume our application, a todo list, has already


been running for a while and the user presses a button
to create a new entry in the todo list. This will result in

advantages it has over traditional approaches.

a button-clicked event in the DOM, which is captured


by the DOM-Driver and forwarded to one of our
ActionCreators.

STATE

VIEW()

DOM
DRIVER

UPDATER
ACTION

VIRTUAL DOM

ACTION
CREATOR

The ActionCreator takes the DOM-event and maps it to an


action. Actions are an implementation of the Command

DOM

EVENT

Pattern, i.e. they describe what should be done, but do not


modify anything themselves. In our example, we create
an AddToDoItemAction and pass it to the Updater.
The Updater contains the application logic. It keeps a
reference to the current state of the application. Every
time it receives an action from one of the ActionCreators,

The picture above shows a rough overview of the concepts,


which are shared between pretty much all modern UI

state contains three todo items and we receive the

frameworks that foster reactive programming. The first

AddToDoItemAction, the Updater will create a new state

thing to note is that everythingall changes, events, and

that contains the existing todo items plus a new one.

updatesflow in a single direction to form a cycle.


FUNCTIONAL REACTIVE UI DEVELOPMENT

The cycle consists of four data structures (State, Virtual


DOM, Event, and Action) and four components (View()Function, DOM-Driver, ActionCreator, and Updater).

it generates the new state. In our example, if the current

The state is passed to the View()-Function, which creates


the so-called Virtual DOM. As the name suggests, the
Virtual DOM is not the real DOM, but it is a data-structure
that describes how the DOM should look like. The code
snippet on the top left of the next page shows an example
of a Virtual DOM for a simple <div>.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

{ tagName: div,
attributes: {
class: view
},
children: [
{ tagName: input, ... },
{ tagName: label, ... },
{ tagName: button, ... }
]
}

Functional reactive UI development


has three major advantages over
traditional approaches, all of which
are huge: straightforward testing, a
comprehensive flow of events, and

The Virtual DOM is passed to the DOM-Driver which will


update the DOM and wait for the next user input. With

time travel (yes, seriously).

this, the cycle ends.


ADVANTAGES

Functional reactive UI development has three major


advantages over traditional approaches, all of which are
huge: straightforward testing, a comprehensive flow of
events, and time travel (yes, seriously).

No matter how large your application grows, the flow of


events will never change.
TIME TRAVEL

Functional reactive applications allow you to travel back


and forth in time. If we store the initial state and all

STRAIGHTFORWARD TESTING

actions, we can use a technique called Event Sourcing.

The View()-Function and the ActionCreators are simple

By replaying the actions, we can recalculate every state

mappings, while the Updater performs a fold (also

the application was in. If we replay only the last n-1,

often called a reduce) on the Actions it receives. All

n-2, n-3... actions, we can actually step back in time.

components are pure functions and pure functions are

And by modifying the recorded stream of actions while

extremely easy to test.

applying them, we can even change the past. As you can

The outcome of a pure function depends only on the


input parameters and they do not have any side effects.

imagine this can be very handy during development and


bugfixing.

To test a pure function, it is sufficient to create the input

The first time-traveling debuggers have been built,

parameter, run the function under test and compare

but I think we have only started to understand the

the outcome. No mockups, no dependency injection, and

possibilities, and more amazing tools will be released in

no complex setup are necessary.

the future.

COMPREHENSIVE FLOW OF EVENTS

SUMMARY

The control flow of graphical user interfaces is inherently

So far we have only scratched the surface of functional

event-based. An application has to react to button-clicks,

reactive UI development, but by now it should be clear

keyboard input, and other events from users or servers.

that this approach has tremendous advantages. Most

Applying reactive techniques, be it the Observer Pattern,

people, who have made the switch to functional reactive

data-bindings, or reactive streams, comes naturally.

UI programming, never want to go back.

Unfortunately, these techniques come with a price. If


a component A calls a component B, it is simple to see

MI C HA E L HE I N R I C HS is a user interface creator

the connection in your IDE or debugger. But if both

by passion. He is convinced no matter which technology


and which device, if it has a screen, one can build a truly
amazing experience. And pure magic.Michael works at the
Canoo Engineering AG as a software engineer on next generation
user interfaces. Before that, he was responsible for performance
optimizations in JavaFX Mobile at Sun Microsystems and later
became the technical lead of the JavaFX core components at
Oracle.You can find him on Twitter @net0pyr and occasionally he
blogs at blog.netopyr.com.

components are connected via events, the relationship is


not as obvious. The larger the application becomes, the
harder it gets to understand its internals.
The architecture of a functional reactive application
avoids these problems by defining a simple flow of events
that all components must follow.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

QUICK VIEW

Totally Modular,
Dude!
BY BILL SOUROUR
FOUNDER AT DEVMASTERY.COM

If youre building a web application today, chances are theres a lot

01

Modular programming
leads to better readability,
collaboration, reusability, and
encapsulation. This means
fewer bugs and cleaner code.

02

Start using ES2015 module


syntax today (youll need a
transpiler like Babel, but its
worth it).

03

Favor exporting a single object


or factory function per module
defined near the top of your
code so that your modules
API is immediately apparent.

READABILITY

of JavaScript involved. Keeping that JavaScript properly structured

Suppose that the entire text of this article was presented to you

so that its easy to understand, maintain, and change over time

as a single, extremely long paragraph. No subheadings. No line

is a big challenge. Thats why, since the mid-late 2000s most web

breaks. Just an unending stream of words. Chances are that would

applications have taken a modular approach.

make it very hard and quite unpleasant to read and understand.

JavaScript code went from being written as a long list of functions

divided into sections.

So, instead, this article contains a number of paragraphs all neatly


and variables all contained in a single file and attached to a
single global scope, to being written as a set of independent,

Likewise, separating an application into modules makes the

interchangeable modules that each contain all the code

application easier to understand and reason about.

necessary to deliver only one aspect of an applications complete,


desired functionality.

also to work with legacy code.

The trouble is, until the advent of ES2015, JavaScript didnt


inherently support this kind of separation, so developers had to
rely on a number of clever workarounds and third-party libraries to

COLLABORATION

By breaking an application up into several independent modules,


multiple developers can work together on the same application with

make modules work.

less fear of damaging or interfering with each others code.

Now that Modules are officially here, its worth exploring how best

REUSABILITY

to use them.

Because of the self-contained nature of Modules, Modular

WHAT ARE MODULES?

components. In JavaScript, this is evidenced by the rise in popularity

The concept of Modules comes from Modular Programming.

of package managers like Bower and npm

Modular Programming is a software design technique in which the

ENCAPSULATION

Programming lends itself to the creation of highly re-usable

functionality of an application is separated into interchangeable,

Modules can be selective about what information and functionality

independent components. In Modular Programming each

they make available to other modules. This prevents unintended

component is self-contained; meaning that each component

consequences and bugs by increasing predictability and control.

contains everything necessary to execute a single, particular aspect


of an applications desired functionality. These components are

Specifically in JavaScript, before ES2015, anything declared outside

called Modules.

the scope of a function was automatically added to the global

As of ES2015, JavaScripts definition of a module is far more

collaborating with other developers on a large project, the risk of

broad; any file containing exclusively JavaScript code is considered

name collisions and overwriting values was high.

scope. When working with third-party code or even when simply

a module.

To solve this, developers resorted to building modules using

THE BENEFITS OF MODULAR PROGRAMMING


Modular programming has a number of benefits:

10

This enhanced readability, in turn, makes it easier to find bugs and

complicated patterns like Immediately Invoked Function Expressions


(IIFE), Asynchronous Module Definitions (AMD), Universal Module

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Definitions (UMD), and Common JS (see Appendix A for details).


In ES2015 this paradigm is inverted. Each module creates its own
lexical scope, meaning that nothing declared within a module is
available or visible to any other module unless it is explicitly exported.

earlier is not yet fully supported by most browsers, nor is it


supported in Node.js.
Edge already has experimental support for the import syntax and both

ES2015 EXPORT AND IMPORT SYNTAX

Chrome and Mozilla have announced their intent to support the newly

As part of the formal introduction of modules into the JavaScript

proposed <script type=module> specification which will add

language, the ES2015 Language Specification also introduced syntax

native support for modules in web browsers.

for importing and exporting values to and from modules. The full
details can be found in section 15.2.2 and 15.2.3 of the EcmaScript
2015 Language Specification. Below is a summary of the new syntax.

:: EXPORT SYNTAX
// default exports
export default
export default
export default
export default
export default
export default
export default
export default
export default

Node.js has not yet committed to adopting the ES2015 standard, but
there is a solid proposal in place and a good deal of pressure from the
community.
In the meantime, a transpiler (e.g. Babel) is needed in order to use

42;
{};
[];
(1 + 2);
foo;
function () {}
class {}
function foo () {}
class foo {}

// inline exports
export var foo = 1;
export var foo = function () {};
export var bar;
export let foo = 2;
export let bar;
export const foo = 3;
export function foo () {}
export class foo {}
// named exports
export {};
export {foo};
export {foo, bar};
export {foo as bar};
export {foo as default};
export {foo as default, bar};
// exports from (re-exports)
export * from foo;
export {} from foo;
export {foo} from foo;
export {foo, bar} from foo;
export {foo as bar} from foo;
export {foo as default} from foo;
export {foo as default, bar} from foo;
export {default} from foo;
export {default as foo} from foo;

the ES2015 module syntax consistently across all environments and


in the browser this should be mixed with a module bundler like
Webpack or SystemJS.

BEST PRACTICES
USE THE ES2015 SYNTAX

Despite the current lack of support across browsers and Node.js,


now that there is a standard built into the language, it is likely to
become the most stable, most widely supported way to write and use
JavaScript modules over time.
Use the ES2015 syntax in combination with a transpiler and/or
bundler to make your projects future-ready.
For legacy projects that already use modules with a different
syntax, both SystemJS and Webpack when combined with Babel
support projects with mixed module definitions. On the server-side
Babel provides support for transpiling ES2015 module definition to
CommonJS and also supports mixed module definitions.
STRIVE FOR A SINGLE DEFAULT EXPORT PER MODULE

One of the explicit design goals of ES2015 was to favor default


exports; therefore, ES2015 has the most straightforward syntax for
default exports.
This implies that modules should have a one-to-one relationship
with a self-contained construct such as a function, object, or class.
EXPORT A SINGLE OBJECT THAT REPRESENTS THE MODULES
PUBLIC API

:: IMPORT SYNTAX

Inspired by Christian Heilmanns Revealing Module Pattern, an

// default imports
import foo from foo;
import {default as foo} from foo;

elegant way to write a self-documenting module that makes its API

// named imports
import {} from foo;
import {bar} from foo;
import {bar, baz} from foo;
import {bar as baz} from foo;
import {bar as baz, xyz} from foo;

default export.

// glob imports
import * as foo from foo;
// mixing imports
import foo, {baz as xyz} from foo;
import foo, * as bar from foo;
// just import
import foo;

Source: https://github.com/eslint/espree/pull/43

11

BROWSER AND NODE.JS SUPPORT

At the time of this writing, the export and import syntax described

clear and obvious is to encapsulate all publicly available functions


and values in a single object and then to expose that object as the

The use of ES2015s shorthand declaration syntax for object literals


makes this technique even more powerful.
Consider the following contrived calculator module...
// calculator.js
const api = { add, subtract, multiply, divide };
function add(a,b) {...}
function subtract(a,b) {...}
function multiply(a,b) {...}
function divide(a,b) {...}
function somePrivateHelper() {...}
export default api;

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Defining the API near the top of the module allows anyone reading
the code to immediately understand its interface without the need to
read the entire listing.
Note: One might expect that an ES2015 destructuring syntax would
work when importing this module, but in fact, it does not. Specifically,
the following line will fail to work as expected:
import ( add, subtract } from calculator;

This is because the import syntax treats add and subtract as


named exports, rather than the destructured properties of an
exported object.
EXPORT FACTORIES FOR COMPLEX MODULES

Building upon the aforementioned recommendation, when dealing


with a complex object it is advisable to export a single default
factory function.
This allows for dependency injection and more sophisticated
object construction while respecting the favored, single-defaultexport paradigm.
Consider the following (even more) contrived calculator module...

// calculatorFactory.js
export default function(radix) {
return {

add,

subtract,

multiply,

:: IIFE
(function(){ /* code */ }());
:: AMD
define(myModule, [dep1, dep2], function (dep1, dep2) {

return function () {};
});
:: AMD - Simplified Common JS Wrapping
define([require, dependency1, dependency2], function

(require) {

var dependency1 = require(dependency1),

dependency2 = require(dependency2);
return function () {};
});
:: Common JS
function myFunc(){ /* code */ };

module.exports = myFunc;
:: UMD
(function (global, factory) {

if (typeof define === function && define.amd) {

// AMD

define([jquery], factory);

} else if (typeof exports === object) {

// Node, CommonJS-like

module.exports = factory(require(jquery));

} else {

// Browser globals (global is window)

global.returnExports = factory(global.jQuery);
}
}(this, function ($) {
// methods
function myFunc(){};
// exposed public method
return myFunc;
}));

divide,

};
function add(a,b) {/* code that uses radix somehow */}
function subtract(a,b) {/* code that uses radix somehow */}
function multiply(a,b) {/* code that uses radix somehow */}
function divide(a,b) {/* code that uses radix somehow */}
function somePrivateHelper() {/* code that uses radix somehow */}
}

REFERENCES

ECMAScript 2015 Language Specification


ecma-international.org/ecma-262/6.0/

Mozilla Developer Network - export


developer.mozilla.org/en/docs/web/javascript/reference/statements/export
Mozilla Developer Network - import
developer.mozilla.org/en/docs/web/javascript/reference/statements/import

Here again the modules API is immediately apparent.

ECMAScript 6 Modules: the final syntax


2ality.com/2014/09/es6-modules-final.html

WHAT ABOUT EXPORTING ES2015 CLASSES?

Intent to implement <script type=module> (Chrome)


groups.google.com/a/chromium.org/forum/#!topic/blink-dev/uba6pMr-jec

This author prefers not to use ES2015 classes, but that will have to be
a topic for another day.

Bug 1240072 - Implement milestone 0 <script type=module> (Mozilla)


bugzilla.mozilla.org/show_bug.cgi?id=1240072
HTML Living Standard Script Element
html.spec.whatwg.org/#the-script-element:module-script

CONCLUSION
The ES2015 specification has finally brought real Modules
to JavaScript, further cementing the advocacy of Modular
Programming in the JavaScript community. Using Modular
Programming in JavaScript promotes better readability,
collaboration, reusability, and encapsulation.
While not yet fully supported, third-party libraries make it possible
to start using ES2015 today. Adoption of the ES2015 Module
standard will make applications future-ready. So, start now.

12

APPENDIX A - PRE-ES2015 MODULE PATTERNS

Again with the Module Pattern reveal something to the world


christianheilmann.com/2007/08/22/again-with-the-module-pattern-revealsomething-to-the-world/
JavaScript Design Patterns
addyosmani.com/resources/essentialjsdesignpatterns/book

BI L L S OUR OUR is the founder of DevMastery.com. A 20

year veteran programmer, architect, consultant, and teacher,


he helps individual developers and billion dollar organizations
become more successful every day.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Debugging
JS with
These 10
Tips
BY FREYJA SPAVEN & DANIEL WYLIE, RAYGUN

JavaScript has a reputation of being


not very structured, and it can be hard
to get an overview ofwhathappened
andwhenexactly

4. BENCHMARK LOOPS USING

8. FIND THE IMPORTANT THINGS IN

console.time() AND console.timeEnd()

COMPLEX DEBUGGING

It can be super useful to know exactly how long

In more complex debugging we sometimes want to

something has taken to execute, especially when

output many lines. One thing you can do to keep a

debugging slow loops and such. You can even set up

better structure of your outputs is to use more console

multiple timers by providing a label to the method.

functions

5. GET THE STACK TRACE FOR A FUNCTION


If youre using a JavaScript framework, you know that
it produces a lot of codequickly. Views are created,
events are triggering functions, and in the end you
want to know what caused this function call.

amajor differencewhen it comes to being able

Console.log,

console.debug,

Since JavaScript is not a very structured language


it can sometimes be hard to get an overview
ofwhathappened

andwhen,

especially

etc. You can then filter them in your inspector. But,


sometimes this is notreallywhat you want when you
need to debug JavaScript. Its now that YOU can get
creative and style your messages. Use CSS and make
your own structured console messages when you want
to debug JavaScript.

when

you jump into someone elses code. This is when


console.trace (or just trace in the console) comes
in handy for debugging JavaScript.

By knowing your tools inside out, you can make

like:

console.warn, console.info, console.error,

Even though you think you know your script well, this
can still be useful. Lets say you want to improve your

to efficiently debug JavaScript. Easier said

code. Get the trace and your great list of all related

than done! Luckily, the team at Raygun has

functions. Every single one is clickable and you can

put together this handy list of tips. Most of

now go back and forth between these functions. Its

these are for Chrome inspector, but also there

like a menu of functions just for you.

For example:
In the console.log() you can set%s for a string,%i
for integers, and%c for custom style. You can
probably find better ways to use this. If you use a
single page framework you may want to have one style
for view message and another for models, collections,
controllers, etc. Maybe also name the shorter like
wlog, clog, and mlog.
Its time to use your imagination.

9. QUICKLY ACCESS ELEMENTS IN THE


CONSOLE

are some great ones for Firefox. Many will work


in other inspectors as well. If you find yourself

6. UNMINIFY CODE AS AN EASY WAY TO

in a bind, just refer back to this guide for a

DEBUG JAVASCRIPT

quick and easy debug.

Sometimes you have an issue on production and your


source maps dont quite make it to the server fear

A faster way to do a querySelector in the console is


with the dollar sign. $(css-selector) will return
the first match of CSS selector. $$(css-selector)
will return all of them. If you are using an element more
than once, its worth saving it as a variable.

not. Chrome can unminify your JavaScript files to a


more human readable format. Obviously, the code
1. debugger;
After console.log, debugger is my favorite quick
and dirty debugging tool. Put it in your code, Chrome

wont be as helpful as your real codebut at least you

10. BREAK ON NODE CHANGE

can actually see whats happening. Click the {} Pretty

The DOM can be a funky thingsometimes things

Print button below the source viewer in the inspector.

you need to debug JavaScript, Chrome lets you pause

will automatically stop there when its executing.


Simple as that. You can even wrap it in conditionals so
its only run when you need it.

7. QUICKLY FIND A FUNCTION TO DEBUG


Lets say you want to set a breakpoint in a function.

2. TRY ALL THE SIZES


Whilst having every single mobile device on your desk
would be pretty awesome, its not really feasible in the
real world. How about resizing your viewport instead?
Chrome provides you with everything you need. Jump
into your inspector and click the toggle device mode
button. Watch your media queries come to life!
3. HOW TO FIND YOUR DOM ELEMENTS

to find the line in your inspector and add a


breakpoint.
to add a debugger in your script.
In both of these solutions, you have to click

its attributes. In inspector, right-click on the element


and pick abreak on settingto use.

SUMMARY
These tips should provide you with a starting point
when it comes time to debug JavaScript. You can
access these same tips and more with thorough
examples right here on DZone.

around in your files to find the particular line you


want to debug.
Whats probably less common is to use the console.

Mark a DOM element in the elements panel and use

Use debug(funcName) in the console and the script


will stop when it reaches the function you passed in.

elements in its history, so the last marked element

13

when a DOM element changes. You can even monitor

The two most common ways to do that are:

QUICKLY
it in your console. Chrome inspector keeps the last 5

change and you dont quite know why. However, when

If youd like to speed up your workflow and add to your


toolbox for debugging JavaScript, I also recommend
you read:
Speed Up Your Markup with Zen Coding/Emmet
Emmet and CSS the Forgotten Part

will be displayed with $0, the second to last marked

Its quick, but the downside is it doesnt work on

Chrome Command Line API

element $1, and so on.

private or anonymous functions. But if thats not the

Chrome Developer Tools, Tips, and Tricks

If you mark items in order item-4, item-3, item-2,

case, its probably the fastest way to find a function to

Firefox Edit and Resend a Request

item-1, item-0 then you can easily access the DOM

debug. (Note:theres a function called console.debug

nodes in the console.

which is not the same thing.)

Test Driven JavaScript Development:


An Introduction

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

SURVIVAL INSTINCTS: MOST TRUSTED TECH FOR THE

You find yourself stranded in the web development jungle and need to find your way out. You hear some vague
requirements that you need to 'create a web app.' You don't know how much (or how rich) database access you'll need,
how complicated the business logic will be, what your target devices will be, or really anything that imposes specific
technical constraints. What is your first instinct in regards to which framework or full stack to use? We received over 700
responses as to which server-side or client-side frameworks come to mind first, as well as which full web stack would
be the go-to one. Results are illustrated below. Welcome to the world wild web.

CLIENT-SIDE

REACT. JS

JQUERY

ANGULAR. JS

11% of respondents would use


React.js

11% of respondents would use


JQuery.

49% of respondents would use


Angular.js

React is considered to be simpler and

While jQuery's overall popularity has


fallen a bit in the wake of mobile app
development, it's still very useful for
traditional web development. Because
it was so popular for so long, it's
easy for developers to crank out a
quick project with knowledge they
already have.

AngularJS popularized the use of


custom web components, and
simultaneously is easy enough for
designers to use and for developers to
do almost anything they wanat. While
Angular 1 does have issues with
performance, Angular 2 has made
several improvements.

easier to learn that Angular, as well as


WEB DEV JUNGLE
slimmer. React popularized the concept
of unidirectional flow, and uses JSX to
compile React to JavaScript at compile
time, so bugs are easier to catch.

SERVER-SIDE

FULL STACK

SPRING

NODE . JS

30% of respondents would use


Spring.

11% of respondents would use


Node.js

Spring is the most popular choice


here, because of it's connection to
Java. Spring Core offers IoC and
dependency injection. And, Spring
MVC offers a relatively high-level of
abstraction while still providing tight
coupling to the Servlet API.

Node.js's major strength is that it


enables developers to write
server-side applications purely in
JavaScript. It's highly performant,
highly scalable, and highly
extensibleall traits that make it
highly desirable.

LSAM (LINUX, SPRING,


APACHE, MYSQL)

MEAN

10% of respondents would use


the LSAM stack

15% of respondents would use the


MEAN stack

This is very telling of our Java-heavy


audience! These technologies are likely
used together and favorable because of
their familiarity.

The simplicity, common structure, and


performance offered by this framework
make it the go-to stack for many web
developers. MongoDB's flexibility with data
storage, the ability to use JavaScript for
client and server-side (Angular & Node.js),
JSON format for all datathese are just
some of the pros.

(MONGODB, EXPRESS,
ANGULAR, & NODE.JS)

DZONE.COM 2016

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Adding Authentication
to a Web Application
with Auth0, React,
and JWT

QUICK VIEW
01

Online services like Auth0 allow


developers and companies to
leverage on their infrastructure
to ease the entry barrier to
any web product that requires
authentication.

02

They also let companies Integrate


multiple social platforms as entry
points for the application, avoiding
the necessity of signing up with a
new service.

03

And they allow companies to


manage and organize their users
and the services they consume,

BY JOS AGUINAGA

reducing the amount of business


logic required for the application.

WEB ENGINEER

Setting up an authentication layer is, without doubt,


one of the most challenging yet necessary tasks
within any web application. Not only does the
application in question always needs to ensure the
most basic functionality is set up by default (such
as login, logout, reset password), but additionally,
its required to develop all the libraries to handle
the validation of the credentials, the connections to

LINKS
Auth0.com

Free account required for performing OAuth2 with GitHub.


Create React App

Required for setting up our sample application.


Download.Repos.Club

Repository with final code.

SETUP
The initial setup is fairly easy thanks to Facebooks create-react-

the database responsible for the user data, session

app utility. Calling the tool with a name will setup a repository

management, and general security.

with a development workflow toolchain that includes Webpack,


Babel, Hot-Reload, and ES6 support.

Enter Auth0. Auth0 is an online web service that handles


authentication protocols like OAuth2, LDAP, and OpenID Connect

\$ create-react-app download.repos.club

to allow clients to create authenticated services without need


to build the entire infrastructure. In particular, Auth0 uses

After running the command successfully, the folder will have the

the standard RFC 7519 approved by the IETF, better known

following structure:

as JSON Web Tokens (JWT), to communicate with its clients


that an authentication flow has been performed. This way, an
application can retrieve user related data and showcase protected
information to only logged in users.
In the following article we will learn how to use React and Auth0
to enable authenticated-only sections within a web application,
as well as to retrieve protected resources. The application will
show the logged-in user their GitHub repositories, so we will

README.md
package.json
public
favicon.ico
index.html
src
App.css
App.js
App.test.js
index.css

use our application with Auth0 and OAuths GitHub integration.

index.js

Additionally, we will leverage the auth0-lock JavaScript library

logo.svg

version 10 for performing calls against Auth0, and use the create-

16

react-app library from Facebook to bootstrap our application.

We will focus on the src folder for our application. As with many

Knowledge about Node.js and npm will be assumed.

React applications, we want to make sure our view is in place

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

before we perform any business logic on the application. The key


</div>

view components for our application will be the Login/Logout

</div>

button, and the Repositories List View. The files src/Navbar.js and

<div className=Repo__container>

src/Repo.js showcase each view:

<span className=Repo__latest-update>Last Updated:


<b>{new Date(updatedAt).toDateString()}</b></span>
<div className=Repo__actions-container pt-button-group>

src/Navbar.js

<AnchorButton href={downloadRepo} download={`${name}.

import React from react


export const Navbar = ({loggedIn, onClick}) => {

zip`} iconName=download> Download </AnchorButton>


{/*<Button className=pt-intent-danger iconName=delete
disabled={disabled}> Delete </Button>*/}
</div>

return (

</div>

<nav className=pt-navbar pt-dark>

</div>

<div className=pt-navbar-group pt-align-left>


<div className=pt-navbar-heading>Download Repos
</div>

</div>
)

</div>
<div className=pt-navbar-group pt-align-right>
<button onClick={onClick()} className=pt-button ptminimal pt-icon-user>

Note: We are using Palantirs Blueprint React components module


to display some of the objects in our application. Visit

blueprintjs.com to learn more about BlueprintJS.

loggedIn
? Logout
: Log in

As we can see, both our view components receive a series

of parameters, particularly the src/Repo.js, that contains

</button>

authenticated information. We need to use Auth0s library Lock

</div>

to help us retrieve that information from our user. Including

</nav>
)

auth0-lock in our library and adding an ES6 class wrapper around

it ensures we can request the user GitHub credentials. The class,


which will be located in src/Auth.js, will look something like this:

src/Repo.js
src/Auth.js
import React from react
import emoji from node-emoji

import Auth0Lock from auth0-lock

import {

export default class Auth {


constructor (clientId, domain, callback) {
// Configure Auth0
this.lock = new Auth0Lock(clientId, domain, { redirect: true,
allowSignUp: false })
// Add callback for lock `authenticated` event
this.lock.on(authenticated, this._doAuthentication.bind(this,
callback))
// binds login functions to keep this context
this.login = this.login.bind(this)
}

Colors,
AnchorButton
} from @blueprintjs/core
export const Repo = ({name, description, stars, forks,
updatedAt, forked, disabled, downloadRepo}) => (
<div className=Card pt-card pt-elevation-3>
<div className=Repo>
<div className=Repo__container>
<div className=Repo__headline-container>
<span className=Repo__name>
<span className={`pt-icon-standard ${forked ? pticon-git-branch : pt-icon-git-repo} Repo__icon`} />
<b>{name}</b>
{ forked && <span className=pt-tag pt-intentwarning Repo__tag>Fork</span> }
</span>
<span style={{color: Colors.GRAY1}}className=Repo__
description>{description ? emoji.emojify(description) : }</
span>
</div>
<div className=Repo__metadata-container>
<span className=Repo__stars><b>{stars}</b> stars</
span>
<span className=Repo__forks><b>{forks}</b> forks</span>
</div>
</div>
<div className=Repo__container>
<span className=Repo__latest-update>Last Updated:
<b>{new Date(updatedAt).toDateString()}</b></span>

_doAuthentication (callback, authResult) {


this.setToken(authResult.idToken)
callback()
}
login () {
// Call the show method to display the widget.
this.lock.show()
}
loggedIn () {
// Checks if there is a saved token and its still valid
return !!this.getToken()
}
setToken (idToken) {
// Saves user token to localStorage
localStorage.setItem(id_token, idToken)
}

Continued next page

17

Continued top right

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

getToken () {
// Retrieves the user token from localStorage
return localStorage.getItem(id_token)
}
logout () {
// Clear user token and profile data from localStorage
localStorage.removeItem(id_token)
}

async getProfile () {
const profile = await axios.post(https://jjperezaguinaga.
auth0.com/tokeninfo, {id_token: this.auth.getToken()})
return Promise.all([
profile.data,
axios.get(`https://api.github.com/users/${profile.data.
nickname}/repos?per_page=100&sort=updated`)
])
}

isLoggedIn () {
return this.auth.loggedIn()

The most important parts of this class are the constructor and

login method. The constructor initializes the Auth0 library with

login () {
this.auth.login()

your own credentials, while the login will trigger the Auth0

modal display for showing the user credentials. Since we are

logout () {

only interested in our users GitHub information, we dont want

this.auth.logout()

to allow signing up through Auth0. This can be specified as a


parameter to Lock. You can read more about Lock in auth0.com/

}
}

docs/libraries/lock.
We are taking advantage of both Promise and Axios to perform
Before we continue, we need to retrieve our Client ID and Domain

asynchronous requests to our endpoints, and resolve them

from Auth0. Additionally, ensure that localhost is included in the

gracefully, respectively. Additionally, we use await and async to

list of Allowed Callback URLs and Allowed Origins (CORS)


within the Auth0 dashboard. To be able to use GitHub as a
Connection, you need to create a new application under Settings
> OAuth Applications in GitHub, and pass both Client ID and
Client Secret from the new registered application. Add Auth0s
callback URL within the GitHub application, which should be in
the form https://<user>.auth0.com/login/callback.

control the flow of our requests, and chain each response to then
retrieve the user GitHub repositories. Finally, src/Api.js provides
us with utilities to communicate with our src/Auth.js class and
log out whenever we dont need the resources anymore.

CONCLUSION
The process we used to authenticate our user is known as the

If everything has been done correctly, we should be able to wire

Implicit Grant flow defined by RFC 6749, better known as OAuth2.

our application with the Auth class with the button, and display

Due to the security restrictions of any client-side application,

the Auth0 modal inside.

one can perform limited operations against the Resource Server.

We are now able to log in our user, but we still need to fetch

creating a new repository in GitHub, for instance), its required

its data. Thats where JSON Web Tokens (JWT) come in. On

to set up a server that is able to perform the access_token

a successful login, src/Auth.js will store the JWT of the

handshake with the Resource Server. However, even without a

authenticated request as an id_token inside our local storage. We

server, we are able to retrieve basic information about our user,

can then use this token to request Auth0s profile information

such as their profile and repositories. A few years ago it would

In order to use Auth0 to perform calls against an API (such as

of the user. Since JWTs are encoded with a secret that only

have been required to have a full-blown dedicated server and

Auth0 knows, they are safe to send and receive in a client-side

database to perform such tasks.

application. We will retrieve the JWT through an API class, and


then perform the required queries to both Auth0 and GitHub. Our
now src/Api.js looks like this:

Although we picked Auth0 to showcase this flow, its important to


mention that Auth0 is not the only service in the authenticationas-a-service industry. Amazon Cognito and Stormpath provide

import axios from axios

similar solutions, both with their pros and cons. Particularly,

import Auth from ./Auth

Amazon Cognito interacts perfectly with the AWS ecosystem,

export default class Api {


constructor (callback) {
this.auth = new Auth(xRTGXVGR03uOlQMRds6ZpU0fx8OjLakE,

and might be a better option over Auth0 if the consumers of your


application are working with AWS-related resources.

jjperezaguinaga.auth0.com, callback)
}
getRepos () {
return this.isLoggedIn()
? this.getProfile()
: Promise.reject(new Error(User is not authenticated))
}

Continued top right

18

J OS AG UI N AG A is a Web Engineer with multiple years


of experience in JavaScript-related technologies. Having
worked for different startups in various cities across the world
like Zrich, San Francisco, Mxico City, and Bali, Jos has
developed an insiders understanding of the startup culture
and the web development industry, especially within the
Fintech ecosystem.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Diving Deeper
INTO WEB DEV

TOP #WEBDEV TWITTER FEEDS

WEB DEV ZONES

To follow right away

Learn more & engage your peers in our Security-related topic portals

@swizec

@jdalton

Web Dev

dzone.com/webdev

@davidwalshblog

@rachelandrew

Web professionals make up one of the largest sections of IT audiences;


we are collecting content that helps web professionals navigate in a
world of quickly changing language protocols, trending frameworks,

@addyosmani

@collis

and new standards for user experience. The Web Dev Zone is devoted
to all things web developmentand that includes everything from
front-end user experience to back-end optimization, JavaScript

@rauschma

@rasmus

frameworks, and web design. Popular web technology news and

@paul_irish

@chriscoyier

Java

releases will be covered alongside mainstay web languages.

dzone.com/java

TOP WEB DEV REFCARDZ

The largest, most active Java developer community on the web. With

Node.js

and strategies that keep your skills razor-sharp.

dzone.com/refcardz/nodejs
Developing distributed, multi-threaded applications using traditionally
synchronous languages can be complex and daunting, Node leverages
JavaScripts asynchronous programming style via the use of event loops with
callbacks to make applications naturally fast, efficient, and non-blocking.

Functional Programming in JavaScript

news and tutorials on Java tools, performance tricks, and new standards

Mobile

dzone.com/mobile
The Mobile Zone features the most current content for mobile
developers. Here youll find expert opinions on the latest mobile
platforms, including Android, iOS, and Windows Phone. You can find
in-depth code tutorials, editorials spotlighting the latest development

dzone.com/refcardz/functional-programming-with-javascript

trends, and insight on upcoming OS releases. The Mobile Zone delivers

Functional programming is a software paradigm that will radically change the way

unparalleled information to developers using any framework or platform.

in which you approach any programming endeavor. Combining simple functions to


create more meaningful programs is the central theme of functional programming.

AngularJS
dzone.com/refcardz/angularjs-essentials
Provides an essential reference to AngularJS, an MVW framework that enables
web developers to build dynamic web applications easily.

WEB DEV BOOKS


Secrets of the JavaScript Ninja
by John Resig and Bear Bibeault

WEB DEV PODCASTS


The Shop Talk Show
Front End Happy Hour
Three Devs and a Maybe

19

Programming Ruby 1.9 & 2.0:


The Pragmatic Programmers Guide
by Dave Thomas, Andy Hunt, and Chad Fowler

Python Cookbook
by David Beazley, and Brian K. Jones

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

try {
QlikPlayground.learn();
} catch (Exception e) {
System.out.println(never called);
} finally {
me.setGenius(true);
}

Create genius data-driven apps with built-in features


like search and associative modeling.
Qlik Playground is a free, one-of-a-kind programming environment that lets developers
get hands-on with their datawithout all the hassle. Built for developers by developers,
Playground makes it easy to import your data to start building, playing and exploring right
away. Backed by an open source community, it works with any stack, architecture or
platform so you can get ramped-up fast. Skip the boring tasks like writing queries and
creating tables and start building the stuff you love.
Come play at playground.qlik.com

SPONSORED OPINION

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

How Reactive
Programming
Can Elevate Your
Data-Driven
Development
Over 2.5 quintillion bytes of data are generated each
day across the interneta never-ending onslaught of
information that requires a level of programming that
can capture, manipulate, and transform that data into
actionable and relevant knowledge. Reactive programming

At Qlik, we offer a complete set of reactive tools and an


engine through a responsive user interface that utilizes
WebSockets and real-time communication to quickly and
easily associate, analyze, and update data across servers
and applications. Gone are the days when developers have
to manually and tediously update their code for each new
data source or change in the data. As any CIO can tell
you, the ongoing management of all of the different data
sources and processing engines can be a huge amount of
overhead: overhead that opens the door to mistakes and
closes the door to time for new projects and developments.

Application scalability and


resiliency are paramount
in order to meet expanded
user expectations, minimize
downtime, and stay ahead of
competitors.

is this new paradigm: a powerful evolution in data-driven


application and website development.

The reactive way of developing with the Qlik Engine gives


developers the tools to set up the data from the onset to

With an unprecedented number of internet users browsing

automatically react to changes. Using tools like ReactJS,

existing data, and creating more data, its critical that

Redux, Flux, and asynchronous programming, developers

websites and applications can respond to user inquiries

can use Qlik to quickly build an event-driven application

with quick, accurate information. This means applications

that incorporates visualizations and analytics on huge

must be scalable, resilient, and built on a foundation that

data sets. Once your dashboard is built out and your

is event-based and message-driven.

organizations data is displayed in reactive charts and


other UI elements, they are hooked up to the engine. Every

Application scalability and resiliency are paramount in

time the user makes a selection or drills down to explore a

order to meet expanded user expectations, minimize

particular use case, the engine automatically recalculates

downtime, and stay ahead of competitors. A message-

and updates each chart. No extra coding is necessary.

driven architecture provides an asynchronous boundary


needed to decouple from the strict time-and-space
boundaries that monolithic applications must conform to.
This decoupling can endow the application with elasticity,
or the ability to easily scale out on demand. These
attributesmessage-driven architecture and elasticity
are the cornerstones of reactive programming.

To try this out for yourself, Qlik has developed an open


sandbox architecture for developers. Qlik PlaygroundTM
is a free programming environment that allows
developers the chance to check out Qliks engine without
commitment. Once an account is created, just load in your
external data and begin to quickly and effortlessly create
your data-driven application.

A reactive approach to data-driven development

Sources: https://medium.com/reactive-programming/what-is-reactive-

also allows for more flexibility, making websites and

programming-bc9fa7f4a7fc#.ah2e144gi

applications easier to develop and to change, as well as

21

more tolerant of failure, which makes releasing patches on

WRITTEN BY DAVE NUGENT

highly-available infrastructure possible.

DEVELOPER RELATIONS ENGINEER, QLIK

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Executive Insights
on Web Application
Development
BY TOM SMITH
RESEARCH ANALYST AT DZONE

QUICK VIEW
01

Keys to developing web


applications are planning, UX,
and using appropriate tools
and technologies to optimize
developer productivity.

02

The most significant changes


to the development of web
apps are platforms, tools, and
the speed with which they
have enabled developers.

03

Web apps enable speed


to market securely and
automatically, making
customers' lives simpler and
easier across a variety of
industries.

To gather insights on the state of web application

this, you must understand who and what you are building for

development today, we spoke to 13 executives

and the definition of a successful application. Your application

from 12 companies developing web applications


or providing web application development tools
to their clients. Specifically, we spoke to:

must provide a seamless UX across any browser and any device


including IoTthe right experience, on the right device, at the
right time. Automate the process, including testing, with DevOps/
CI/CD. Anything that improves the quality of life for developers
will improve the quality of applications.

SAMER FALLOUH, Vice President, Engineering and


ANDREW TURNER, Senior Solution Engineer, Dialexa
ANDERS WALLGREN, CTO, ElectricCloud
BRENT SANDERS, CEO, Fulton Works
CHARLES KENDRICK, CTO, Isomorphic Software
ILYA PUPKO, V.P. of Product Management, Jitterbit
FAISAL MEMOM, Product Marketing, NGINX
BRUNO CORREA, IT Coordinator, Ranstad (Brazil)
CRAIG GERING, Vice President, Engineering, Sencha
JOACHIM WESTER, Founder, Starcounter

have enabled developers to develop applications. Frameworks


have matured, build systems have evolved, there are new
architectural patterns, and movement to the cloud is enabling
the standardization of advanced technology stacks. Theres
an increasing set of tools for all budgets. Tools have become

extremely easy to use and many are almost like 20 th century


magic that write code for you. Applications are developed and
brought to the end user more quickly with design sprints that
enable the development team to work more quickly.
03 The technical solutions used most frequently to develop

MICHAEL MORRIS, CEO, Topcoder

web apps are JavaScript, AngularJS, ReactJS and Native,

GREG LAW, CEO, Undo

Node.js, and HTML5. Other solutions mentioned include: AWS,

ALEXEY AYLAROV, CEO, Voximplant

KEY FINDINGS
01 The keys to developing sound web applications are planning,

22

02 The most significant changes to the development of web


applications are platforms, tools, and the speed with which they

CSS, Docker, Ember, Java, NGINX, open source, Selenium,


TypeScript, and Webpack.
04 Real-world problems solved by web applications are diverse
with speed to marketsecurely and automaticallyand making

user experience (UX), and using the appropriate tools and

customers' lives simpler and easier across a variety of industries

technology to optimize developer productivity. Its important to

most frequently mentioned. Applications with APIs integrate

think through the requirements up front in order to choose the

with other applications automatically. A manufacturer of telecom

most appropriate platform, technology, and tools to deliver the

chips uses process controls and predictive analytics to ensure

project in the smartest and most efficient way. In order to do

chips will meet FCC regulations. Apps are empowered with voice

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

and video calls. An app for NASA is helping astronauts keep

08 The skills developers need to develop effective web

up with their food intake. A staffing company in Brazil used

applications are: agility, knowledge of the fundamentals, and

an app to move from 75,000 job applicants, to 7,000 candidates

knowing themselves. The technical landscape continues to

who self-scheduled interviews picking the time and location

rapidly evolve, and developers must be able to adapt to the

most convenient for them. Airport dashboards, fleet tracking,

changes. Great developers will freely abandon their own solutions

car management, lot management, moving services, oil and

when better ones come along. The best developers dont always

gas taxing, device tracking, social media ranking, class pass


for kids, kids healthy eating, LA metro patrons able to update
fare balances, and students completing all of the steps in their
enrollmentare just a few ways applications are improving life.
05 The most common issues affecting the development of web
applications are the increased complexity of the platforms, tools,
and languages and the lack of planning that goes into ensuring
you are using the best solution for the problem at hand. The most
prominent issue is the number of tools and languages available
to accomplish the same thing and to be able to discern which
solution to invest in. New JavaScript frameworks, versions of

have the strongest technical experience, but they produce great


work because they listen to, and empathize with, the end users
and can honestly and objectively judge their own work to ensure
theyre meeting the needs of the end user. Know the components
of the application and the database frameworks. Understand
the glue code, but dont get too involved with it. The attitude of
developers needs to scale with deployment and DevOps to bridge
the gap. Developers need to become responsible for the operation
of their code. Lastly, developers need to focus on what they are
good at and what theyre passionate about. Dont be afraid to say,
no, Im not the best fit for this. Focus on your strengths.

.NET, and Java are emerging every week. Things tend to get too
technical and too hard to integrate. Teams need to support a wide

09 Additional consideration with regard to developing web

variety of device types, browsers, and operating systems, and

applications were wide ranging:

the landscape is always changing with new versions and updates


being released. In addition, people dont think through whats
needed to solve the problem. Many people with inadequate
backgrounds and conscientiousness are releasing applications
that are neither secure nor user friendly. Instead of doing some
basic pre-planning, authors choose to just jump in and develop
what they think is the solution to the problem rather than
determining the end-user need and problem to be solved.
06 The future of web applications will ultimately integrate

Productivity is about to see a dramatic change with artificial


intelligence.

What are the big conferences for JavaScript? Is there a


JavaOne equivalent?

Lack of thinking through requirements up front is killing a lot


of applications today.

Whats your strategy for getting access to the IT talent you

across all devices providing a great user experience (UX). Virtual

need? How do you plan to leverage the on-demand workforce?

tools will continue to make web application development faster,

How does crowdsourcing and virtual labor fit into your

simpler, and easier. Applications will integrate across devices

company?

with APIs providing a more integrated ecosystem. They will


also be more integrated into our daily lives with IoT, wearables,
and practical applications that make our lives easier and more
manageable. Progressive web apps will provide the performance
and functionality of native apps combined with the convenience
of the web. In the end, the web wins due to its openness,
flexibility, and convenience. WebAssembly technology will allow

Does the business have clear visibility about how web


development will help them achieve their goals?

What are the dynamics of an effective team? Are people


working as a team to build something together?

How does a corporate culture impact software development

developers to use any programming language to create web

and teamwork? Are DevOps/CI/CD driving application

apps. Rapid application development will kill complexity while

development or is application development driving the move

increasing development speed.

to DevOps?

07 The biggest concerns around the development of web

To ensure companies make the right technology choices,

applications are security and complexitywhich can be

IT managers, developers, and executives need to work

addressed with planning. Security is still a big issue, with many

together and trust each other to solve business problems.

websites not defaulting to SSL, and were replacing more offline

Forming cross-functional teams is important for building

apps with their web counterparts. Security needs to be done

relationships, so each group understands the value and

correctly with web apps and IoT since this will affect our homes,

perspective of the others.

our cars, and our medical devices. Theres still a lack of planning
upfront and this becomes critical as complexity increases. We
need more standardization across browsers. Breaking changes
introduced by new versions of consumed frameworks can
be a nightmare. This increases the need to choose the right
technology platform for the job.

23

TOM S M I T H is a Research Analyst at DZone who excels

at gathering insights from analyticsboth quantitative and


qualitativeto drive business results. His passion is sharing
information of value to help people succeed. In his spare time,
you can find him either eating at Chipotle or working out at the gym.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Embracing
Simplicity with Static
Site Generators

QUICK VIEW
01

Static sites can be beneficial by


providing an incredibly simple
output that can be deployed
anywhere quickly and cheaply.

02

By acting like an app server locally,


the developer gets the benefit of
a dynamic language on their local
machine with the benefit of static
output when done.

03

Even after moving to a static


solution, many dynamic
aspects, like forms and

BY RAYMOND CAMDEN

comments, can be added in via


third-party services.

DEVELOPER ADVOCATE AT IBM

For many years developers have made use of various

For this reason and more, static site generators provide a great

application servers to create dynamic websites.

alternative. A typical generator will do the following for you:

From PHP to ASP to ColdFusion and more recently


Node.js, app servers let you integrate databases and

"programming" language per se, these template languages

other dynamic features into your websites. But more

let you embed tokens in your code that will be replaced on

recently, many developers are beginning to realize

the fly.

that app servers may be more power than they need.


Static site generators, a relatively recent innovation,
provide developers with the nimbleness of an app
server while working locally and outputting simple
static files for easy deployment.
Given that an app server can be so powerful, why would a developer
willingly give that up?

1. One of the biggest reasons is that an app server can go


down. Every app server needs to be updated, monitored, and
generally babysat to ensure it's running well and secured. On
top of that, app servers are typically paired with database
servers, which require the same time and care.

2. To replace those tokens, they provide a way for you to store


data. This is outside a database server and is generally
something like a simple JSON file.

3. They provide a way to preview your site on your local


machine, running much like a traditional app server.

4. Then they provide a way to output to simple, static files.


Sound interesting? The good news is that you have more than
a few options. The list at staticsitegenerators.net currently has
nearly 450 different options. Every static site generator will have
its own way of doing things while generally following the process
listed above. For this article, let's take a look at a rather simple

2. Many times app servers provide way more power than


necessary. Do you really need PHP for a site getting less than
a thousand hits per month? Do you need MySQL for data that
changes rarely?

generator, Harp (harpjs.com).

3. Another big reason to avoid app servers is that our websites


are doing less and less now that so many people have
moved to apps on their mobile devices. Your website may
have turned into simply an announcement telling people to
download your app.

personal favorite, but it was the first one I encountered and was

4. Finallybrowsers are much more powerful now than they


were years ago. Things that app servers had to do because
the browsers couldn't handle it may be better handled on the
client side.

24

1. They will give you a template language. While not a real

WORKING WITH HARP


Harp isn't the best generator out there, and it isn't even my
responsible for starting my love for generators in general. It's also
one of the simplest ones to get started with, and that makes it a
good option to discuss. Keep in mind, though, that if you don't like
the particulars of how it works, you still have over four hundred
other ones to try. (I'll discuss some other options at the of this
article as well.) To begin, simply npm install -g harp. This will
add the Harp command line to your system. To confirm, just run

harp at the command line.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

trash$ harp

h1 Welcome to Harp.
h3 This is yours to own. Enjoy.

Usage: harp [options] [command]

Even if you've never seen Jade before, you can probably guess as

Commands:

to how it is working. The first line is creating an h1 block with text

init [options] [path]

Initialize a new Harp project in current

directory

inside it, and the second line is creating an h3 block. Modify the
template like so:

server [options] [path] Start a Harp server in current


directory

h1 Welcome to Harp.

multihost [options] [path] Start a Harp server to host a


directory of Harp projects

h3 This is yours to own. Enjoy.


p I love static site

compile [options] [projectPath] [outputPath] Compile project

i generators!

to static assets (HTML, JS and CSS)

All we've done is added a new paragraph with a bit of styled text.

Options:

Reload the page in your browser and you'll see the new output:

-h, --help

output usage information

-V, --version

output the version number

Use 'harp <command> --help' to get more information or visit


http://harpjs.com/ to learn more.

Harp's command line mainly revolves around three options


making a new site, running the server, and outputting static flat files.
Let's begin by creating a new site: harp init demo1.

If you view the source, you'll see HTML, not Jade. This ispretty much
like every other old app server out there. PHP acts the same way.

trash$ harp init demo1


Downloading boilerplate: https://github.com/harp-boilerplates/
default

Now let's create another file, about.md:

Initialized project at /Users/raymondcamden/Desktop/trash/demo1


About
===

This will create a simple site with four files:


_layout.jade handles creating the layout for the site.

I love this. Really!

Harp let's you freely mix and match different template engines

404.jade is a 404 handler for the site.

within one site, although probably you'll stick to one for your project.

Index.jade is the home page.

You can open this new file by requesting about.html in the browser.

main.less is a style sheet written using Less

Harp is smart enough to know this maps to the Markdown file you
just created.

For rendering HTML, Harp supports Markdown, EJS, and Jade. For
rendering CSS, Harp supports Less, Stylus, and Sass. You can even
use CoffeeScript as well. Harp automatically converts the particular
language into the right output. Let's see this in action. At the
command line again, run harp server.
demo1$ harp server
-----------Harp v0.23.0 Chloi Inc. 20122015
Your server is listening at http://localhost:9000/
Press Ctl+C to stop the server
------------

Where did the sites rather simple layout come from? The _layout.
jade file:
doctype

If you open this up in your browser, you'll see the following:

html
head
link(rel="stylesheet" href="/main.css")
body
!= yield

In the Jade template above, the critical part is yield. Harp


automatically runs the layout file for every file you requestthats

25

So how did this work? By default, Harp's initial files are all using the

how it worked for both index.jade and about.md. It takes the content

Jade template language. Jade was recently renamed to Pug, and you

from those files and places it in a variable called yield. This then

can find documentation about all it supports at its website: pugjs.org.

allows your template to put the page content anywhere you want.

But for now, open up index.jade:

Heres a modified version that adds a footer.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

For the coup de grace, lets now kill off this server and output in

doctype

static files. That takes all of one command: harp compile -o ../

html

demo1_output

head
link(rel="stylesheet" href="/main.css")
body

This tells Harp to compile the current directory and output it one level
higher in a folder called demo1_output. This will create four files: 404.

!= yield
footer This site is copyright #{ new Date().getFullYear() }

html, about.html, index.html, and main.css. If you open index.html


youll notice the layout and variables have all been rendered. You can

Note the user of a bit of code at the end to include a dynamic year.
Now when you run the home page, youll see (below, left):

now take these files and deploy them as a simple static site.
Harp has more features than weve covered here so be sure to check
the harpjs.com/docs for more information!

Now lets talk a bit about


data. We mentioned that
all static site generators
have a way to let you
define data for use in
the site, and Harp is no
different. Harp provides two different ways of defining data, but for

ADDING DYNAMIC BACK


So obviously once youve gone static you end up losing a few simple
things you may miss. One example of that is form processing.
How do you add, for example, a basic contact form to your site so
visitors can contact you? Luckily theres a few options for this. One
of the best, and easiest, to use is Formspree (formspree.io). With
Formspree, you can simply point your form to their server, include

now, well look at the simpler of the two optionsglobal data. Add a

your email address, and they will forward along the results to you.

new file to your site named _harp.json. Harp will not render any file

Consider the following example:

that begins with an underscore. In this file, include the following:

{
"globals":{
"email":"raymondcamden@gmail.com",
"name":"Awesome Site!"
}
}

In order to use global data, you must use the file named _harp.json
(theres an exception to this, but dont worry about that for now)
and an object defined with the name globals. Outside of that, you
can then use whatever variables you want. In the example above,
two variables, email and name, are defined, but thats completely
arbitrary. You can include any valid JSON you want here.
Once defined, these variables will be available in all your files. Heres
an updated _layout.jade file that includes the name value as the title:

Contact Me
===
<form action="https://formspree.io/raymondcamden@gmail.com"
method="POST">
Your Name: <input type="text" name="name"><br/>
Your Email: <input type="email" name="_replyto"><br/>
Your Comments: <textarea name="comments"></textarea><br/>
<input type="submit" value="Send Comments">
</form>

In this rather simple (and kinda ugly) form, the action points to
Formspree and includes my email address. Now when the form
is submitted, Formspree will take the contents and email them
to me. The very first time this happens Formspree will require
you to confirm that you want the form to work, but after that its
automatic. You can even tell Formspree where to send the user next
by including a hidden form field: <input type="hidden"
name="_next" value="some url on your site telling the
user thank you">.
Formspree is a great service with a very generous free tier. Check

doctype

the site for current costs and whats supported at that level.

html
head
title #{ name }

On top of forms, you can also find services for calendars, comments,

link(rel="stylesheet" href="/main.css")

and other dynamic aspects.

body
!= yield
footer This site is copyright #{ new Date().getFullYear() }

WRAP UP
While obviously static site generators arent going to be a good
option for every site, its amazing how many places they can be used.

And heres a modified home page using the email:

As much as I consider myself a decent developer, I absolutely love


the idea of my production websites being as simple, and stupid, as

h1 Welcome to Harp.
h3 This is yours to own. Enjoy.
p I love static site

possible. The fewer things I have to worry about breaking down is


always a good thing!

i generators!
p Email me at
a(href="mailto:#{email}") #{ email }

While not as powerful as a proper database, we now have one place


where we can define dynamic values and have them automatically
updated throughout the site.

26

RAY MON D CA MD E N is a developer advocate for IBM. His work


focuses on APIs, Bluemix, hybrid mobile development, Node.js, HTML5,
and web standards in general. Along with Brian Rinaldi, he is the author
of the soon-to-be released book on Static Sites from O'Reilly(Working
with Static Sites). Raymond can be reached at his blog (raymondcamden.com),
@raymondcamden on Twitter, or via email atraymondcamden@gmail.com.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

Solutions Directory
This directory contains solutions for debugging platforms, platforms as a service, device
detection, various web dev frameworks, web testing, IDEs, and more. It provides feature data
and product category information gathered from vendor websites and project pages. Solutions
are selected for inclusion based on several impartial criteria, including solution maturity,
technical innovativeness, relevance, and data availability.

27

COMPANY NAME

PRODUCT

TYPE

FREE TRIAL

WEBSITE

ActiveState

Komodo IDE

PaaS

21 Days

activestate.com/komodo-ide

Afilias Technologies

DeviceAtlas

Device Detection

30 Days

deviceatlas.com

Amazon

AWS Elastic Beanstalk

PaaS

Free Tier Available

aws.amazon.com/elasticbeanstalk

Aryaka

SmartCDN

Web App Acceleration

Available by request

aryaka.com/services/web-app-acceleration

Automattic

Wordpress

CMS

Free Tier Available

wordpress.com

Backtrace

Backtrace

Debugging Platform

Available by request

backtrace.io

Bithound

Bithound

Node.js Debugging

Free Tier Available

bithound.io

Blue Spire

Aurelia

JavaScript Framework

Open Source

aurelia.io

Browserling

Browserify

Build Script Tool,Package


Manager

Open Source

browserify.org

BrowserStack

BrowserStack

Web Testing

Available by request

browserstack.com

Cake Foundation

CakePHP

PHP Web Framework

Open Source

cakephp.org

ClojureScript

ClojureScript

Compiler

Open Source

clojurescript.org

CoffeeScript

CoffeeScript

Language

Open Source

coffeescript.org

CommonJS

CommonJS

Package Manager

Open Source

commonjs.org

Django Software Foundation

Django

Python Web Framework

Open Source

djangoproject.com

DocumentCloud

Backbone.js

JavaScript Framework

Open Source

backbonejs.org

DocumentCloud

Underscore.js

JavaScript Library

Open Source

underscorejs.org

Dropbox

Dropbox platform

PaaS

Available by request

dropbox.com/developers

Drupal

Drupal

CMS

Open Source

drupal.org

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

28

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

COMPANY NAME

PRODUCT

TYPE

FREE TRIAL

WEBSITE

Ecma International

ECMAScript

Scripting Language

Open Source

github.com/tc39/ecma262

Elm

Elm

Language

Open Source

elm-lang.org

Engine Yard

Engine Yard Cloud

PaaS

21 Days

engineyard.com

Facebook

React.js

JavaScript Library

Open Source

facebook.github.io/react/

Facebook

Flow

Static Type Checker

Open Source

flowtype.org

Fujitsu

Fujitsu S5 Cloud Service

PaaS

No Free Trial

welcome.globalcloud.global.fujitsu.com

GNU

Make

Build Script Tool

Open Source

gnu.org/software/make

Google

AngularJS

JavaScript Framework

Open Source

angularjs.org

Google

Google Cloud Platform

PaaS

60 Days

cloud.google.com

Grails

Grails

Java Web Framework

Open Source

grails.io

Grunt

Grunt

Build Script Tool,Package


Manager

Open Source

gruntjs.com

Hewlett Packard Enterprise

HPE Helion

PaaS

Available by request

hpe.com/us/en/solutions/cloud.html

Hewlett Packard Enterprise

HPE Unified Functional


Testing

Web Testing

Open Source

www8.hp.com/us/en/software-solutions/unifiedfunctional-automated-testing/

IBM

Bluemix

PaaS

30 Days

ibm.com/bluemix

IBM

LoopBack

Node.js API Framework

Open Source

loopback.io/

Intel

Crosswalk

Web Runtime

Free Solution

crosswalk-project.org

Jelastic

Jelastic

PaaS

Varies by hosting
provider

jelastic.com

JetBrains

WebStorm

IDE

30 Days

jetbrains.com/webstorm

JetBrains

PyCharm

IDE

Free Tier Available

jetbrains.com/pycharm

JetBrains

RubyMine

IDE

30 Days

jetbrains.com/ruby

JetBrains

PHPStorm

IDE

30 Days

jetbrains.com/phpstorm

JetBrains

Rider

IDE

Available through early


access

jetbrains.com/rider/

JetBrains

Resharper

Debugging Platform

30 Days

jetbrains.com/resharper

Langa

Trails

Node.js Web Framework

Open Source

trailsjs.io

Laravel

Laravel

PHP Web Framework

Open Source

laravel.com

LeaseWeb

LeaseWeb

IaaS

Available by request

leaseweb.com/cloud

Less

Less

CSS Preprocessor

Open Source

lesscss.org

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

29

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

COMPANY NAME

PRODUCT

TYPE

FREE TRIAL

WEBSITE

Lightbend

Play

Java Web Framework

Open Source

playframework.com

Mendix

Mendix Platform

PaaS

Up to 10 Users

mendix.com

Meteor Development Group

Meteor

JavaScript Framework

Open Source

meteor.com

Microsoft

Visual Studio Code

IDE

Free Solution

code.visualstudio.com

Microsoft

ASP.NET

Web Framework

Free Solution

asp.net

Microsoft

Microsoft Azure

PaaS

Free Tier Available

azure.microsoft.com

MochaJS

Mocha

Web Testing

Open Source

mochajs.org

NearForm

Hapi

JavaScript Framework

Open Source

hapijs.com

Node.js Foundation

Node.js

JavaScript Environment

Open Source

nodejs.org/en

Node.js Foundation

Koa

Web Framework

Open Source

koajs.com

Node.js Foundation

Express

Web Framework

Open Source

expressjs.com

Nodesource

N|Solid

Node.js Runtime

Available by request

nodesource.com

npm, inc.

npm

Package Manager

Open Source

npmjs.com

Open Source Matters

Joomla!

CMS

Open Source

joomla.org

OpenQA

Selenium

Web Testing

Open Source

seleniumhq.org

Optimizely

Optimizely

Web Testing and


Experimentation

30 Days

optimizely.com

Oracle

Oracle Cloud

PaaS

Available by request

cloud.oracle.com

OutSystems

OutSystems

PaaS

Free Tier Available

outsystems.com

PhantomJS

PhantomJS

Web Testing

Open Source

phantomjs.org

Pivotal Labs

Jasmine

Web Testing

Open Source

jasmine.github.io

Pivotal Software

Spring

Java Web Framework

Open Source

spring.io

Progress Software

OpenEdge

PaaS

60 days

progress.com/openedge

Qlik

Qlik Playground

Web App Testing


Environment

Open Source

playground.qlik.com

QuickBase, Inc.

QuickBase

PaaS

30 days

quickbase.com

Raygun

Pulse

Real User Monitoring

30 days

raygun.com/products/real-user-monitoring

Red Hat

OpenShift

PaaS

Free Tier Available

openshift.com

RequireJS

RequireJS

Package Manager

Open Source

requirejs.org

RisingStack

Trace

Node.js Debugging

Free Tier Available

trace.risingstack.com

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

30

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

COMPANY NAME

PRODUCT

TYPE

FREE TRIAL

WEBSITE

Rogue Wave Software

Zend Framework

PHP Web Framework

Open Source

framework.zend.com

Ruby on Rails

Ruby on Rails

Web Framework

Open Source

rubyonrails.org

Salesforce

Heroku Platform

PaaS

Free Tier Available

heroku.com

SAP

OpenUI5

JavaScript UI Library

Open Source

openui5.org

SAP

SAP HANA Cloud


Platform

PaaS

Free Tier Available

hcp.sap.com

Sass

Sass

CSS Preprocessor

Open Source

sass-lang.com

Sauce Labs

Sauce

Web Testing

14 Days

saucelabs.com

Sencha

Sencha Platform

Web App Platform

30 Days

sencha.com/web-application-lifecyclemanagement-sencha-platform

Sencha

Ext JS

JavaScript Framework

30 Days

sencha.com/products/extjs

Sencha

Sencha GXT

Java Web Framework

30 Days

sencha.com/products/gxt

SensioLabs

Symfony

PHP Web Framework

Open Source

symfony.com

Stylus

Stylus

CSS Preprocessor

Open Source

stylus-lang.com

Swisscom

Swisscom Application
Cloud

PaaS

Available by request

swisscom.ch/en/business/enterprise/offer/clouddata-center-services/paas/application-cloud.html

Telerik

Kendo UI

HTML and JavaScript


Framework

Available by request

telerik.com/kendo-ui-html-framework-opt

The jQuery Foundation

jQuery

JavaScript Library

Open Source

jquery.com

The jQuery Foundation

QUnit

Web Testing

Open Source

qunitjs.com

Tilde

Ember.js

JavaScript Framework

Open Source

emberjs.com/

Tsuru

Tsuru

PaaS

Open Source

tsuru.io

Twitter

Bootstrap

Web Framework

Open Source

getbootstrap.com/

Twitter

Bower

Package Manager

Open Source

bower.io

Vaadin

Vaadin

UI Framework

Open Source

vaadin.com

Verizon Digital Media Services

Edgecast CDN

CDN

Available by request

verizondigitalmedia.com/platform/edgecast-cdn

Vue.js

Vue.js

JavaScript Framework

Open Source

vuejs.org

Walmart Labs

Joi

Validation System

Open Source

github.com/hapijs/joi

Walmart Labs

Lazo

Web Framework

Open Source

github.com/lazojs/lazo

WaveMaker

WaveMaker

PaaS

30 Days

wavemaker.com

Webpack

Webpack

Package Manager

Open Source

webpack.github.io

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

DZONE.COM/GUIDES

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

GLOSSARY
AJAX: A method of using
asynchronous data exchange
between the client and server
in order to create interactive
websites.

DEPENDENCY INJECTION: A

MODULE: A component of

process that occurs in object-

software or hardware that is

oriented programming in which

portable and interoperable.

a resource that a piece of code


requires is supplied.
DOM (DOCUMENT OBJECT
MODEL): Allows for the creation

API (APPLICATION PROGRAM


INTERFACE): Code that allows for
communication between different

and modification of HTML and


XML documents as program
objects to help control who can

MODULE BUNDLER: A tool


that eases the process of using
modules by bundling them with
necessary dependencies.
MVC (MODEL-VIEWCONTROLLER): A way of relating

software programs.

modify the document.

ASP: Active Server Page; a

HARP: A static web server written

code and reduce the time spent

feature of the Microsoft Internet

in Node.js that uses built-in

developing applications with UIs.

Information Server and an HTML

preprocessing.

the UI to underlying data models


that lets developers reuse object

page where scripts are processed


before a page is sent to the user.
ASYNCHRONOUS MODULE
DEFINITIONS (AMD) API:

NODE: The most basic element


JADE: A feature-rich Node.js
template.
NODE.JS: An I/O framework that

Defines modules so that their

JAVASCRIPT: An interpreted script

develops applications that are

dependencies can be loaded

language from Netscape that is

highly dependent on JavaScript

at different times. It is ideal in

used in website development for

on both the client-side and server-

browser environments.

both client-side and server-side

side. It is event-based, non-

scripting. It is easier and faster to

blocking, and asynchronous.

AUTH0: A platform that helps

code than compiled languages,

simplify application and API

but takes longer to run.

authentication.

internal workings either are


not known or dont have to be
understood in order to understand
its input, output, and transfer
characteristics.

JSON: JavaScript Object Notation;

web development that interprets

a language-independent textual

and performs operations before a

data interchange format that is

page is sent to the user.

used in browser-based code to


represent simple data structures
and objects.

PRETTYPRINT: Stylistic formatting


conventions that make text, source
code, etc. easier to read and

COLDFUSION: A program used


to build websites and deliver web
pages that allows developers
to build websites in pieces that
can be stored in a database and
reassembled.

JSON WEB TOKENS (JWT): A

JavaScript to outside of the

understand.

method of transferring claims in a


compact and URL-safe way.
MODULAR PROGRAMMING:
Making a program being written
more efficient, understandable,

COMMONJS: A project that moves


browser.

PHP: A script programming


language and interpreter used in

BLACK BOX: A device whose

31

that is used to build data structure.

and modifiable by enforcing a


certain logical structure; also
known as structured programming.

REACT: A Library in JavaScript


that is used to build user
interfaces.
VIRTUAL DOM: A data structure
that describes how the DOM
should look.

DZONES GUIDE TO WEB DEVELOPMENT: APPLICATIONS AND FRAMEWORKS, VOLUME I

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy