LATEST FROM OUR BLOG

Take your daily dose of (only) relevant news, useful tips and tricks and valuable how to's on using the latest web technologies shaping the digital landscape. We're here to do all the necessary information sifting for you, so you don't have to, to provide you with content that will help you anticipate the emerging trends about to influence the web.

What Is the Best Way to Style React Components? 4 Most Widely-Used Approaches to Styling
Sorry to disappoint you, but: there's no such thing! No such thing as “the best way to style React components”. Or “the most effective approach” or “the currently best option” for styling reusable components within your application. What you do have, instead, is: “The most popular or commonly-used ways of styling components!” 4 of them, actually. And rating one of these approaches as “the best” is totally up to you:   to your personal preferences to your React app's level of complexity to what precisely it is that you need to style in your React project and to your feature needs   Is it just a few style properties that you need to add? Then the inline styling approach suits your “component styling scenario” perfectly. Or maybe it's a more complex React app that you're working on? In this case, you might want to go for the classic approach: using CSS classes and stylesheets and tying them all together with webpack.  But let's just put each of the 4 popular ways of styling React components into the spotlight and clear the picture for you a bit more! I'll be highlighting each option's main advantages and drawbacks, so you can knowingly decide which one's the best option for you.   1. The Classic Approach: Using Regular CSS Stylesheets  You always have classes and stylesheets to rely on when it comes to styling. Simply tie them all with webpack after you've imported CSS file: import './DottedBox.css' … ensuring, this way, that you have a separate CSS file for each one of the components to be styled. The main advantages of this common approach?   it'll then be easier for you to move between your CSS and the browser it will streamline overriding or MVT in case you'll need to go in that direction   Yet, there's also a bit discouraging drawback to this approach to styling React components: Do expect to face all the “standard” CSS problems: potential conflicts between definitions and mutual classes, attribute inheritance (both good and... bad)...   2. CSS Modules  And before we delve into the:   “why” you might rate using CSS modules as “the best way to style React components” “how” to leverage their styling capabilities   ... let us try to define them: They're CSS files where all animation and all class names get automatically scoped. Moroever, CSS modules help you “keep things clean” when it comes to all the previously mentioned problems that CSS stylesheets can challenge you with. They make the most efficient approach to styling React components when you're dealing with complex applications. And now, here are the steps to take for styling your reusable components using CSS modules:   import CSS file: import styles './DashedBox.css' next, access className as you access to the object   And here you have 2 options at hand:   :local(.className) if/when you opt for create-react-app due to webpack configurations .className in case it's your own React boilerplate that you're using    “OK, but how do I make my CSS modules work with Webpack now?” A legitimate question that you might be asking yourself right now. Here's how:   you simply include the modules early mentioned next add the loader here below to your webpack.config.js file: . . . { test: /\.css$/, loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' } . . . 3. Styled Components: Is This the Best Way to Style React Components? “It is if working with class names to compose stylesheets is not really... your thing.” Take it as a more “non-traditional” way of styling components, where you: Create encapsulated styles and integrate them with the props of your components. In other words: instead of using className, you'd be using style attribute. And styled-components — a JavaScript and CSS “combo —  are no more than a library enabling you to use component-level styles within your React app.  Or, you can also see them as a “wrapper component”: mapped to HTML tags in order to style itself and its child elements. This way, you can easily write regular CSS in your JS file.  The main advantages?   you get to store all the styling within the component  … to have separate and reusable UI for your React stateful/stateless components … to build “isolated” components    And now, let me take you through all the steps required for leveraging this library's styling capabilities:   fist, just install the library itself: npm install styled-components –save next, set up a variable by selecting a specific HTML element, to store your style keys const Div = styled.htmlElemnet`color: pink`  and finally, use that variable's name as a wrapper <Div></Div> type of React component     4. Inline Styling  This might just be the best way to style React components for you if it's only a few style properties that you need to add. Don't expect for inline styles to be specified as a string in React:  They're not! Instead, they're mentioned with an object: whose key is the style name's camelCased version whose value is usually a string, the style's own value, actually   And you have 2 options at hand for “triggering” the styling capabilities with this approach:   you create a variable storing style property and get it sent through to the element like style={nameOfvariable} you pass the styling — style={{color: 'pink'}} — directly   Still, don't get overly “enthusiastic” about using this approach to styling! At least not until you've taken note of all the challenges that it presents, as well (and there are quite a few):   you won't be able to use pseudo-classes, one of the core features of CSS (:active, :hover, :focus etc.)   expect duplication in markup each time you'll use a specific component: you won't be having your styles in your JS only, meaning that doing server-side rendering will lead to duplication, to using repetitive rules and the same style code for multiple components   you won't get any media queries: you're left with the solution of using a JS approach for “juggling with” different screen variations   and you can't use vendor prefixes, nor override a rule on the very same selector   In a few words: using inline styling might just not be the best way to style React components if: ... It's a UI-heavy, complex application that you're working on and this is due to the approach's highly restrictive usage. Nevertheless, if you still consider that this option suits your preferences and your app's feature needs best, go for it! You could always use a library such as React JSS, Readium, React style to deal with the above-mentioned inline styling limitations. The END! These are 4 most widely-used ways of styling components in React, along with their key benefits and their most discouraging drawbacks. Which one would you rate as “the best way to style React components” according to your personal preferences and to your current app's “needs” in terms of styling capabilities? ... Read more
Adrian Ababei / Jun 14'2018
What Are The 5 Most Common Angular Mistakes that Developers Make? 
“Learn from your mistakes” should be every developer's life mantra. But that doesn't mean that they should be all your mistakes, right? With a list including the most common Angular mistakes at hand, you'd get to narrow down the number of possible pitfalls that you risk falling into to the... uncommon, the less predictable ones. So, what are the traps that Angular developers fall into most often as they build their applications? We've run our own "investigations" for you:   gone through the code examples on the web ran an inventory of the most frequent questions on StackOverflow looked over some of the issues that we've knocked our heads against while working on our own Angular projects    … and trimmed down our list to 5 most frequent mistakes that Angular developers make: 1. ngOnChanges vs ngDoCheck: Misunderstanding When the ngDoCheck Gets Triggered  "I have used OnPush strategy for my component and no bindings have changed, but the ngDoChecklifecycle hook is still triggered. Is the strategy not working?" I bet that you've stumbled across this question (maybe put into different words) on various developer forums. It could easily win any “popularity” test there since it keeps coming up again and again. But, before we give it a straight answer and settle this matter for good, let's focus on these 2 “change detecting” lifecycle hooks in Angular. And see where the problem stems from: As you well know it, AngularJs has the watch feature, which “alerts” you whenever a value changes. Angular, on the other hand, has replaced the watch and scop feature with component inputs as properties. Moreover, it has added the ngOnChanges lifecycle hook, as well. And here's where things get “tricky” and risk to turn into the trap that many Angular developers fall into: The OnChanges event doesn't emit if/when a deep field of the input property changes. Hence, the value of the input is the reference of the object. How do you approach this problem? You have several methods at hand, in fact, but I'm going to focus on the most common one: Using the ngDoCheck lifecycle hook once you run the change detection process! Now here's the answer that I've promised, to the above-mentioned common developer question: The onPush strategy for detecting changes in Angular does work: the hook is triggered by the design itself!   Note: another ridiculously frequent mistake that developers make is to take "Angular" for "AngularJS"! Be better than that: the term "AngularJS" should be used only when you refer to the old Angular and to Angular 1, while Angular 2/2+ 4 and 5 is just... "Angular". Mind you don't delve deep into this confusion yourself, too!   2. Forgetting to Unsubscribe: One of the Most Common Angular Mistakes  “Forgetting” or simply ignoring this issue.  And you have no “excuse”, you know, for overlooking to clean up your subscriptions in Angular. Considering that there are methods and libraries developed precisely for handling these unsubscriptions once you've finished using an event or an observable in JavaScript. Why does this “clumsiness” risk to grow into a major issue? Because lingering subscriptions cause memory leaks in your system. And when it comes to the unsubscription process, there are 2 scenarios:   you trigger the OnDestroy lifecycle hook if it's in a component that you've subscribed in you initiate the lifecycle hook yourself if it's a service that you've subscribed in (since, in this case, there's no available hook for you to fire)   To recap: Remember to unsubscribe when you no longer use a service/component!   3. The Wrong Use of Providers One of Angular's (compared to AngularJS) key improvements is its Hierarchical Dependency Injection, agree? This means that now you're free to instantiate a service several times (services used to be singletons back in the AngularJS's “glory days”, remember?). Now that being said, let's have a look at a more than likely scenario: Imagine yourself fetching your heroes using a heroes service: @Injectable() export class HeroesService { heroes: Hero[] = []; constructor(private http: Http) { this.http.get('http://give-me-heroes.com').map(res => { return res.json(); }).subscribe((heroes: Hero[]) => { this.heroes = heroes; }); } getHeroes() { return this.heroes; } } Nothing unexpectedly wrong till here:   the data is being fetched in the constructor there's also a getHeroes method for retrieving the heroes    Now, let's take a look at the hero component, too: @Component({ selector: 'hero', template: '...', providers: [HeroesService] }) export class HeroComponent { constructor(private heroesService: HeroesService) {} } @NgModule({ declarations: [HeroComponent] } export class HeroesModule { ... } As you can see, first the HeroComponent declares the HeroesService provider in the @Component.providers array, next it incorporates it in the constructor.  All well and good till you realize that each HeroComponent instance instantiates a new instance of the HeroesService.  To put it more simply: Your HeroesService will be fetching the data (by HTTP request) several times, for each and every HeroComponent instance! And this is due to the Hierarchical DI in Angular. The solution for avoiding this issue — no doubt one of the most common Angular mistakes?  Declaring the service in the @NgModule.providers instead: @Component({ selector: 'hero', template: '...' }) export class HeroComponent { constructor(private heroesService: HeroesService) {} } @NgModule({ declarations: [HeroComponent], providers: [HeroesService] } export class HeroesModule { ... } There! The provider will now be instantiated once and for all. “For all” the HeroComponent instances I mean. “How come?” You might ask yourself. Because the provider (declared in the NGModule now) is a singleton now. Therefore all the other modules can use it.   4. Manipulating the DOM Directly Although I've already said this about another mistake from this list, I now tend to consider this one here instead as being one of the most common Angular mistakes: Manipulating the DOM directly; oftentimes from the controller itself! And this is one of those top 10 Angular mistakes that any developer stands a high risk of making. Since manipulating the DOM is such a common task when using this platform:   you might need to render SVG you might need to refresh a page's title based on a context change you might need to set the focus on a control after a validation error … and the list of possible situations goes on   Then... you fall right into it: you take the easy way out and hack the DOM directly! Now what I feel like pointing out it here is that: Angular's grown from a web framework into a platform! And this can only mean that you're now free to decouple your Angular application's codebase from the renderer and:   have your app executed in on the server … in the browser … as a native app    And decoupling opens the door to other possibilities for you to explore and to tap into, such as using web workers or AOT (ahead of time compilation).   Speaking of the latter: AOT enables you to compile your app's templates in the build time of your server. Moreover, you won't need to use the oversized @angular/compiler package in your bundle, which leads to a lower size and load time. Yet, for future-proofing these “facilities” that Angular provides, you'll need to abide by... some sort of rules at least. And one of them is: Restraining yourself from manipulating the DOM directly, using jQuery, the global document object or the ElementRef.nativeElement. Instead, use the Renderer2 service (or Renderer for Angular 2): It's 2 things that this wrapper to the view mutation layer will enable:   for the default layer to be used in the browser for the renderer to get replaced with a more suitable one whenever your Agular app runs on another platform (e.g. a phone)   In short: Resist “temptation” and never ever touch the DOM directly!   5. Declaring The Same Component in More than Just One NgModule  And declaring a component in multiple NGModule-s is one of those most common Angular mistakes that end up throwing an error “at” you. “Why, so?” Because you need to declare each component in its own NgModule — and to list it in the @Ngmodule.declarations array — in order for it to be available for the views.  If you do need to declare the very same component in multiple modules, you'll need to consider the relationship between those modules: Is it a parent-child one, maybe? If this is the case, then:   use the child's NGModule.declaration to declare the HeroComponent in the child module use the chid's NGModule.exports array to... export the HeroComponent  use the parent's NGModule.imports array to import the child module    If not (if we can't be talking about a parent-child module relationship), then you'll need to declare another NgModule as the module of the shared data.   Final Word  It's only by knocking your head against unexpected issues while building your projects on this platform, that you'll get to grow as an Angular developer. And still, instead of embracing the “fail fast, fail often” concept, wouldn't it be best if you:   learned from other developers' mistakes, thus knowing what the most common Angular mistakes are   ensured that you failed "rarely" instead? ... Read more
RADU SIMILEANU / Jun 05'2018
How to Start Building a Web App Using React: 5 Steps to Creating Your First App with React.js
Building a web app using React for the first time? Then it must be a simple "Hello World" type of app that you're planning to set up. One that would guarantee you a smooth first-hand experience with React.js... So, you're wondering: "What's the fastest way to build a basic app in React?"   A question then followed by a... myriad of other questions:   "What dependencies should I use?" "What React stack should I go for if it's just a simple web app that I want to create?" Now it's about time that you moved from questioning yourself to code writing, don't you think? Here's a simple and easy-to-follow tutorial on how to create a React app from scratch.   1. Create a New React Project Folder  The very first step to take is to start a new React project. Obviously! Note: Make sure you have NPM and Node installed in your environment first things first! For this, just run the command here below: npm install -g create-react-app Tada! Your React boilerplate app creator has just bee installed! Now the second code that you'll run is going to create your "Hello World" React app itself: create-react-app hello-world Running an imaginary magnifying glass across your app's structure you can't help not noticing the 3 major file types there:   public/index.html files src/index.js files src/App.js  files   And scanning your app's backbone a little deeper you'll spot:   a div with the id root this piece code here below in the index.js.file: ReactDOM.render(, document.getElementById(‘root’)); If we were to translate this code segment into plain language it would go something like this: React injects your app component into the div by using the root id.   2. Write the Simplest React Component  "But what is an app component more precisely?"  Take it as React's convention to use the same names both for JavaScript files and the component.  And now the code for your more-than-basic component would look something like this: import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="greeting"> <h1> Hello World! </h1> </div> ); } } Feel free to create a JavaScript class for it and to extend it from the Component class. Next, implement the render () method, which will return a whole suite of elements (unlike prior to React 16, when one had to return a single element per each render method that was being implemented). Then, running the npm start command in your app's directory, you'll see the "Hello World" text message displayed at http://localhost:3000.   Hello World!   3. Building a Web App Using React and JSX And I feel that I should start by defining JSX, right? Before I go ahead and delve into details on how to use it with React: An extension to the JavaScript language — therefore a template language — with a structure similar to HTML. One that makes a great team with React. Its true "power" is that it... empowers you to write your HTML components and React components in an HTML-like tag: <HelloWorld /> And here's JSX "in action", right in this "Hello World" app that we're building here: The following code: const element = ( <h1 className="greeting"> Hello, world! </h1> ); ... gets compiled to the familiar JavaScript code here below: const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, world!' ); See? A familiar HTML-tag language that makes structuring an app's code a whole lot easier for any developer! And this is JSX's main role and the very reason why it works perfectly with React.   4. How to Use State vs Props in React.js How about creating another component as we're building a web app using React? Let's name it "Mary": import React, { Component } from 'react'; class Mary extends Component { render() { return ( <div> <h2> Hi, I am Mary </h2> </div> ); } } export default Mary; Bravo! Next, we can include it, as a child component, into our existing React App component: import React, { Component } from 'react'; import Mary from './Mary'; class App extends Component { render() { return ( <div className="greeting"> <h1> Hello World! </h1> <Mary/> </div> ); } } export default App; Note: Noticed the import statement for our "Mary" component? It plays a key role since without it our React app wouldn't work. And this because React wouldn't be able to identify, all by itself, the component that corresponds to the Mary tag. Curious now how you could manipulate your "Mary" component? How you can control its behavior? By manipulating its... state object, that's how! Note: each React component comes with its own state object. import React, { Component } from 'react'; import Mary from './Mary'; class App extends Component { constructor() { super(); this.state = { greeting: "Hello World!" } } render() { return ( <div className="greeting"> <h1> {this.state.greeting} </h1> <Mary/> </div> ); } } export default App; See the "greetings" property — having the "Hello World" value — that corresponds to the state object? Remember that you're free to add as many properties as needed. Next, how about trying to pass data from our App component into its child one, Mary: import React, { Component } from 'react'; import Mary from './Mary'; class App extends Component { constructor() { super(); this.state = { greeting: "Hello World!", parentMessage: "Hello Mary!" } } render() { return ( <div className="greeting"> <h1> {this.state.greeting} </h1> <Mary newMsg={this.state.parentMessage} /> </div> ); } } export default App; Noticed the "newMsg" key there? It's precisely this key that's responsible with the data transfer. Now, as for the child component "Mary": import React, { Component } from 'react'; class Mary extends Component { constructor(props) { super(props) this.state = { greeting: props.newMsg } } render() { return ( <div> <h2> {this.state.greeting} </h2> </div> ); } } export default Mary; If you're willing to give this piece of code a deep scan, you'll notice that there's a "props" method argument in there.  Keep in mind that it's precisely this object that stores all the data transferred from the parent component to the child React component. Also, another "detail" that you should be able to detect is the "newMsg" property (transferred from the parent/App component); we've used it to initialize the state of the Mary component.   5. How to Use The React (Component) Lifecycle Hooks I won't get into too many details, since React's documentation is already more than "enlightening" when it comes to:   the different lifecycle methods (or hooks) to be invoked for each state of a React component  the precise times in the development process for triggering each hook   Nevertheless, I'll briefly add that all these methods to be used across your React components' lifecycles fall into 3 main categories:   mounting hooks: use them at the very start, when your React component is being rendered in the browser page updating hooks: fire them when your component gets re-rendered on the web page. And this happens if/when changes are made to the state/props objects unmounting hook: invoke the componentWillUnmount() hook shortly after your component gets removed from the DOM     Note: Since React 16, the collection of hooks has enriched with a brand new one: componentDidCatch()! Fire it whenever you're dealing with an exception during the other lifecycle methods of your component. In other words: invoke it whenever a component fails to function as it should when you're building a web app using React! As for the specific way that React manipulates DOM via the Virtual DOM that it creates, feel free to have a look at our post precisely on this topic: How React Virtual DOM Works! The END! Your turn now: go through all the steps included here and, step by step, set up your first basic React application!  ... Read more
RADU SIMILEANU / May 31'2018
How to Create an Angular Project with Angular CLI in 5 Simple Steps
About to build your very first Angular app? Then you must be planning to create an Angular project with Angular CLI, right? The much-acclaimed tool that the Angular team built precisely to jumpstart the whole development process. … to have a simple app scaffolded, generated and deployed in no time, by entering just a few commands (so they say, at least).  And since I'm sure that you don't want to waste these bundles of convenience by letting yourself tangled up in overly complex explanations instead, I've kept things simple with this guide. So, here's how you create and run your first Angular project via the Angular command-line interface:   1. But How Precisely Can Angular CLI Jumpstart Your App's Development Process? Take this command-line interface as a starter kit “present” that the Angular team has nicely wrapped for you:   it's practically geared at empowering you to get up and start developing a new Angular app in no time it takes just one short command to generate a default Angular project that would include all the needed dependencies (in the node_modules folder), as well as testing files for each component   Now, this is what I call a major kickstart! It's got you covered from the stage of setting everything up, to creating the Angular project itself, to testing it and finally deploying it. Other key usages of the Angular CLI that we're not going to focus on in this tutorial here are:   real-time server maintenance and support building applications for production adding new features to your existing app  running tests on your application units    2. Setting It Up: Install Angular CLI Globally Before you jump to the part where you create an Angular app using Angular CLI, you need to install the command-line interface itself. Globally! And this is the “power” command to enter in your terminal with the npm installed: npm install -g @angular/cli Notes: if you already have the CLI installed, make sure it's the latest version if you need to update it, these are the commands to enter: npm uninstall -g angular-cli npm uninstall --save-dev angular-cli And there's more! A few more must-have dependencies that you need to make sure that are already installed and upgraded to their latest versions: Node.js: v6.9.x + npm: 3.x.x +   3. Create an Angular Project With Angular CLI With your command line interface ON, use it to enter THE one and only command that will generate a new Angular project for you. One incorporating, by default, all the needed dependencies: ng new ng-yourproject Tada! A “yourproject” named directory has just been generated. That's where your new Angular project — along with all the requested dependencies — gets stored. Eager to test it out? Just run the following command in your terminal: ng serve   Your Angular app will then get built and served up to localhost:4200. Feel free to open this URL in your browser and it's the here-below screen that you should be able to see: Basically, it's the default application shell itself rendered by the CLI.   4. “Deconstructing” Your New Angular Project: What Does It Include? Now, before you go ahead and do your “tweaking” on your newly created app, let's see what you've got in there! What are the elements that the CLI has generated for you to help you jump to development right out of the box? For this quick “scan”, open your Angular project in your IDE of choice and start “exploring” your src/folder:   src/*    styles.css any styles that you'll plan to apply globally, it's this file that you can add them to; and it's here, as well, that you can import new .css files (Bootstrap or any other styling frameworks of your choice)   index.html  where your Angular app gets started   src/app/*    app.component.ts this is where your app's one and only (for now at least) component gets stored   app.module.ts  the modules Angular needs for managing your app's components note: @NgModule marks the class file as a module and this is what makes it similar to @Component   5. Create a New Component  Remember your “one and only component” that I mentioned during the previous “inventory” of all the “bunch of stuff” that CLI has generated in your project? Well, how about creating a new one now? One that would load under that root component? Just run the following command to generate it: ng generate component the-quote Next, time to “show it off” in your browser: <h3>{{myQuote.quote}}</h3> <small>- {{myQuote.by}}</small> Add the app-the-quote selector to the root component that the CLI generated in your Angular project: <h1> {{title}} </h1> <app-the-quote></app-the-quote> 6. Apply External Styling  Now you do agree that when you create an Angular project with Angular CLI applying styling is a key step. So, let's add your favorite CSS framework to your new application! Me, it's Bulma that I'll be using in this tutorial here: npm install bulma --save With our CSS framework installed, we'll need to enable it to load the CSS file into our Angular app. For this, just place the relative path within the .angular-cli.json file., to the file in the styles array more precisely. ... "styles": [ "../node_modules/bulma/css/bulma.css", "styles.css" ], ...   “Tempted” to display some icons now, as well? Then go ahead and add the font-awesome library as cdn link. For this, just include the stylesheet right into your index.html: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> Et voila! This is how you create an Angular project with Angular CLI! What do you think? Is the Angular command-line interface an extremely useful tool to jumpstart your project with or did you expected your “starter kit” to include, right out-of-the-box, more elements to get you started? ... Read more
RADU SIMILEANU / May 25'2018
When Should You Not Consider Using Node.js? 3 Unsuitable Use Cases
It's undebatable: Node.js has practically laid the foundation of the real-time web! The real-time, two-way connection web apps have revolutionized the old web response paradigm. The one where it was just the client who could initiate communication, never the server, as well. Even so, there are certain cases when using Node.js is not the best decision you could make. Specific use cases for which the otherwise flexible and revolutionary web server technology turns out not to be... unsuitable. So: “When shouldn't I use Node.js?” You might legitimately ask yourself. Here are the 3 bad use cases for this JavaScript runtime environment. Scan them through, take note all the factors that I'll be outlining and think them through before rushing to use Node.js to power your next project with.   1. A CRUD-Heavy Application: Using Node.js Is Simply a Bad Idea Face it, deal with it and... adjust your decisions to it: There are plenty of better solutions (other than Node.js) for powering your CPU-intensive app. It's just not the best technology at hand when it comes to heavy computation. Now here's why, by using Node.js, you'll only end up “sabotaging” its very advantages, instead of turning it into a true “horsepower” for your app, as you might expect:   Node.js leverages an event-based, non-blocking I/O model, using a single CPU  hence, all that intense CPU-processing activity will actually block the incoming requests … since the thread will get “held up” with number-crunching   The direct effect of “exploiting” Node.js in the context of heavy server-side computation?  The very benefits of its event-driven, non-clocking I/O model would get practically... nullified in the context of CPU-intensive operations. Given this, why would you stubbornly stick to Node.js, when there are other technologies more suitable for building your CPU-heavy software with? With better results?   2. A Simple CRUD (or HTML) Application No need to get your hopes high when using Node.js with a basic CRUD or HTML application: It might turn out to be just “slightly” more scalable, yet don't expect a traffic flood just because it's Node.js-powered. In short: use cases like this one, where data's provided, straightforwardly, by the server and where there's no need for a separate API, render Node.js superfluous. There are other frameworks suited specifically for this type of projects (take Ruby for instance). Using Node.js in this case would be like driving a Formula 1 car while... stuck in rush hour traffic.    3. A Relational Database-Backed Server-Side App Why isn't Node.js your best choice for a relational data access type of project? Because its relational database tools aren't as reliable, robust and easy to work with as other frameworks' toolboxes (take Rails for instance!). Rails, for example, would “spoil” you with:   already matured Data Mapper and Active Record data access layer implementations out-of-the-box data access setup DB schema migrations support tools … and the list goes on   In short: if there already are frameworks perfectly “equipped” for this type of project “scenarios”, why would you stick to using Node.js? Since its relational DB toolbox is not (yet) as advanced?   In Other Words... With these 3 “bad” use cases for Node.js “exposed”, allow me to put together a short “inventory” here, one including all the “gotchas”, aspects to consider before kicking off your Node.js project and limitations to be aware of:   Node.js hasn't been built with the “solving the compute scaling” issue in mind   … but it has been created to solve the I/O scaling issue instead   excepting contexts of CPU-heavy operations, Node.js still is the best technology at hand for powering your real-time, scalable web apps with   do reconsider your decision of using Node.js if for developing your piece of software you depend on some kind of threading model   there are also poor quality packages available in npm, free to use in your Node.js application; do keep this in mind as you dig deep into the “load” of  Node.js packages   Node.js will never be “the best choice” for event loop-blocking use cases (take asynchronous parsing XML, for instance)   … nor for powering apps relying on intense computation   Node'js “worker” is geared at solving HTTP server calling issues (rather than intense computing issues)   The END! ... Read more
RADU SIMILEANU / May 17'2018
What Is Node.js Used for? What Projects Can You Build Using It? 7 Best Use Cases
Not exactly the “jumping on the latest trend" type? Therefore, you're still a bit hesitant to get on the Node.js bandwagon? And this because you still haven't got some crystal-clear answers to your “What is Node.js used for?” question? You're legitimately hesitant then! For everyone's gone crazy over it these days, but you know that there must be certain factors to consider. Specific use cases for Node.js, as well as cases when... well... it just isn't the best idea. You're well aware that there are some particular applications that call precisely for this JavaScript runtime environment. And you need to be 101% sure that your project fits the “profile”. One of the “best use cases of Node.js”. But let's not meander any longer and get you some clear answers to your questions instead:   Why should you even consider Node.js one of the possible technologies to choose from for your next project?   Which are the ideal use cases for Node.js?    1. Why Would You (Even) Consider Node.js for Your Project?  Why should Node.js be on your list of... options, in the first place? On your shortlist of technologies that might power your next project? There must be some “bundles of convenience”, some major benefits that you can “reap” from using it, right? Benefits that make it worth building your project using this specific environment. Well, let us shed some light on these clear advantages of developing your application in Node.js:   it's a Google JavaScript engine (a runtime environment) which, translated into clear benefits, means that: it's fast and scalable web apps that you'll build using it   speaking of its scalability: Node.js's built to scale on individual process basis and to leverage multi-core processing on modern servers (via its Cluster module)   it's JavaScript-based... so the “pool” of developers with some kind of JS knowledge/expertise is conveniently large: 99,9% of them know at least “some” JavaScript   … no to say that this turns Node.js into the perfect choice if there are beginner developers in your team (even junior developers are at least familiarized with JS)   any developer will be able to gain a quick understanding of your Node.js app's codebase   it speeds up developers' work with a collection of modules (Grunt, NPM, etc.)   it provides your development team with a great package manager, npm, with a widely available and increasingly heavy “load” of open-source tools    it's backed and actively maintained by an ever-growing community ready to... support you; the knowledge base that your development team needs to get a grip on Node.js is accessible and... free   it's open-source: you'll benefit from a single, free codebase    it's just... fast, there's no point in debating over this: the event loop and Google's innovative technologies are “turbocharging” it   it cuts down costs, as simple as that: Node.js enables your team to use the same language on the front-end and on the back-end, which translates into boosted efficiency, cross-functionality and implicitly... reduced costs   you're “tempted” with a whole range of hosting options to select from   it supports native JSON: it's in this specific format that you'll get to keep your data stored in your database   Now if I was to trim this list to just 3 answers to your “what is Node.js used for?” dilemma, it's these 3 key benefits that I'd stubbornly stick to:   performance: Node.js is simply... fast, faster than other JS languages; moreover, as a runtime language it has enhanced JavaScript with new capabilities versatility: from backend to front-end apps, to clips to... pretty much everything in between, Node.js enables you to build any kind of project that you have in mind; as long as it's written in JavaScript, of course agility: regardless of your/your team's level of JavaScript expertise, Node.js empowers you to kick-start your project, to get it up and running in no time; it's developer productivity-oriented (just think same language for both back-end and front-end!!!), with a low learning curve    2. What is Node.js Used for? 7 Great Use Cases Now back to the very question that started this post: “What exactly is Node.js good/used for?” There are specific app projects that this server-side JavaScript technology makes the best choice for: 2.1. Chat servers And generally speaking any type of fast-upload system challenged to respond, in real-time, to an “avalanche” of incoming requests. 2.2. Real-time apps  This is the use case that Node.js “rocks at”. Where you get to make the most of its capabilities. Apps geared at processing high volumes of short messages, where low latency becomes critical, make the best possible answer to your “what is Node.js used for?” question. Here's why:   it enables sharing and reusing Node.js packages that store library code it processes ideally fast: quick data sync between the client and server it's perfectly “equipped” to cope with multiple client requests   In short: if scalability and real-time data processing are 2 critical factors to consider when choosing the best technology for your project, think Node.js! It's built to suit specifically those situations that are “overly demanding” of our servers. 2.3. Video conference apps  ...applications using VoIP or specific hardware.  Projects involving intense data streaming — audio and video files — make the best use cases for Node.js. 2.4. Instant-messaging, live-chat apps  2.5. Highly scalable apps Think Trello or Uber-alike apps, that depend on a server-side server technology enabling them to scale out on multi-CPU servers. Node.js, thanks to its cluster-based architecture, will always make the best choice for apps depending on a technology that would spread out the load across a multi-core server. Note: speaking of scalability requirements, should I also mention that Node.js is... conveniently lightweight, too? 2.6. eCommerce transaction software and online gaming apps “What is Node.js used for?”  For powering apps for which online data is of critical importance. Like these 2 examples here! 2.7. Server-side applications  Being an event-driven model of programming, the flow is determined by messages, user actions, and other specific events of this kind.   3. Afterword Does this clear the picture for you a bit more?  As a conclusion or “final” answer to your “what is Node.js used for?” type of dilemma, the key takeaway from this post here is that: Node.js is used primarily for web applications, but it's starting to get used more and more often for developing enterprise apps, too, thanks to its versatility. What does the future have in store for this increasingly (still) popular technology:   rising potential for Node.js to be used for building IoT solutions …. for “experimenting” with enterprise data more and more big names (adding to Netflix, IBM, Amazon, Uber, LinkedIn, etc.) choosing it over legacy languages such as Java or PHP   ... Read more
RADU SIMILEANU / May 10'2018
How to Scale Your Node.js App: Best Strategies and Built-In Tools for Scalability 
Whether it's the increasingly challenging workload or you simply want to enhance your Node.js app's tolerance to failure and availability, there comes a time when you just need to scale it up, right? To “squeeze” the best performance out of your entire infrastructure of... nodes. Well then, here's how to scale your Node.js app: And scaling up your web back-end app at different levels —  overall improving its throughout — sure isn't an afterthought with Node.js: Scalability is built in the very core of the runtime. And the infrastructure of nodes, strategically distributed, communicating with each other, is what makes this framework particularly scalable. So, what is the best way to scale up your Node.js app? Which are the most powerful built-in tools for scalability to explore and to “exploit”? And what are the best strategies to go for depending on your specific scenario and scalable architecture needs?   Horizontally Scaling Your Node.js App  Horizontal scaling comes down to... duplicating: Basically, you duplicate your application instance, enabling it to “cope with” a larger number of incoming connections. Note: you can horizontally scale your Node.js app either across different machines or on a single multi-core machine. A word of caution: do keep in mind, though, that this scaling solution might add up unnecessary complexity to your app's infrastructure; it might entail the need to provision and to maintain a load balancer, might make troubleshooting more challenging, and even change the way you deploy your app. That being said: make sure that it's specifically this Node.js scaling solution that your project needs before you go ahead and implement it!   Vertical Scaling If your scalability architecture needs involve nothing more than:   injecting more power  adding more memory   … with no particular “tweaking” applied to the code, then vertical scaling might just be the right answer to the “how to scale your Node.js app” dilemma. Here's why:   by default, Node won't use more than 1.76GB of 64-bit machines' memory in case of a 32GB of RAM machine, for instance, the Node process will limit itself to only a fraction of its memory   Have Multiple Processes Running on The Same Machine Here's another possible answer to your “How to Scale your Node.js app” question: Have multiple processes running on the same port. It goes without saying that this scaling solution calls for some kind of internal load balancing that would distribute the incoming connections across the entire ecosystem of cores/processes. Word of caution! Not sure whether there's any need to add this: keep the number of running processes lower than that of the cores! Hereinafter, let's focus on 2 Node.js built-in tools for scalability that you might want to tap into:   The Cluster Module  Node's cluster module makes a great starter for scaling up your application on a single machine. How does it work precisely? It makes setting up child processes sharing server ports conveniently easy.  Practically, one “master” process will be in charge with spawning all the child processes (and there's one “worker” for each core), those that actually run your Node.js app. Feel free to dig here into more details on the whole process.  Yet, there are certain limitations to this basic scaling solution:   in case one of your child processes “dies”, it doesn't... regenerate itself you'll need to handle the master-worker processes difference... the “old school way”, using an “if-else” block there's no way of modifying multiple processes, at once, on-the-fly!   Note: yet, when it comes to the “dead child processes” drawback, there's... hope. For instance, use this piece of code that would enable the master process to... respawn the “worker”: cluster.on('exit', (worker, code, signal) => { cluster.fork(); }); And voila! This drawback has been taken off your list!    The PM2 Cluster Module Using the PM2 cluster module, “how to scale your Node.js app” dilemma turns into: “Lay back and let the PM2... clusterfy your server for you!” All you need to do is “trigger” this command's superpower: pm2 start app.js -i 4 –name="api" It will instantly create a 4-node cluster for you! Now, here are some more details about what's going on “under the hood” during this process:   the PM2 daemon will take over the ex “master process'” role and spawn N processes (the former “worker processes”) while relying on round-robin balancing moreover, if it's PM2 process manager that you're using, your process gets automatically scaled across all the existing cores (no need to trigger the cluster module for that anymore) also, the same PM2 process manager will ensure that processes restart, instantly, if they happen to crash   You'll just need to write your Node.js app as if it were for single-core usage and the PM2 module will make sure that it gets scaled for multi-core. Note: now if you want to scale your Node.js application further, you might want to consider deploying more machines...    Scaling Across Multiple Machines with Network Load Balancing The underlying process is more than similar to the “multiple core scaling” one, if you come to think of it: Instead of several cores, you'll have several machines; each one will be running one or more processes and will get “backed up” by a load balancer redirecting traffic to each machine in this infrastructure. “And how does a network balancer work, more precisely?” you might ask yourself: Once a request is sent to a node, the balancer sends the traffic to a specific process. And there are 2 ways of deploying your internal balancer:   deploy a machine and set up a network balancer yourself, using NGINX use a managed load balancer (like Elastic Load Balancer); setting it up is conveniently easy and it “spoils” you with all kinds of built-in features, such as auto-scaling   Now if your “How to scale your Node.js app” question turns into a “Isn't it risky to have just one point of failure for my infrastructure?": Just deploy multiple load balancers instead of relying on a single balancer.  They would be all pointing to the same servers, needless to add. Note: for distributing traffic across your “ecosystem” of internal balancers, you could just add several DNS “A” records to your main domain.   How to Scale Your Node.js App: 3 Scaling Strategies to Consider 1. Decomposing “Microservice” is another word for this scaling strategy. For practically you'll be “juggling” with multiple microservices (although their size is of no significant importance, actually). Or multiple applications, with different codebases (and in many cases, each one of them has its own UI and dedicated database). And it's by services and functionalities that you'll be decomposing/scaling your Node.js app. A strategy that can lead to unexpected issues in the long run, but which, if implemented correctly, translates into clear gains for your apps' performance.   2. Splitting Or “horizontal partitioning” or “sharding”, if you prefer. This strategy involves splitting your app into multiple instances, each one responsible for a single, specific part of your app's data! Word of caution: data partitioning calls for a lookup before you carry out each operation; this way you'll identify the right instance of the application to be used. Take this example here: You might want to partition your Node.js app's users by language or area of interest. In this case, a lookup step is a must; you'll need to check that information, first things first.   3. Cloning And this is the easiest strategy at hand for solving your “How to scale your Node.js app” dilemma! Just clone your Node.js back-end application, multiple times, and assign a specific part of the workload to each cloned instance! It's both effective and cost-effective! Moreover, Node's cluster module makes cloning on a single server ideally easy to implement! And this is “How to scale your Node.js app”! See? You have not just one, but several Node.js built-in tools at hand and various strategies to choose from, depending on your scaling needs. Which scaling solution suits you/your app project best? ... Read more
RADU SIMILEANU / May 03'2018
Node.js 10 Is Out: Here Are 10 New Features and Improvements Worth Getting Really Excited About
Have no fear... Node.js 10 is here (since April 24, actually)! And, as expected, this version is planned to grow into the platform's official Long Term Support version (in October 2018); to be supported for 3 years after that date. So? What's in it for you, the back-end web developer? Are there any new features and improvements worth getting really excited about? Which are they and how precisely will they improve the overall developer experience.  Now before we take a deep dive into the “steamy fresh load” of new features, I feel like pointing out that:   it's mostly incremental improvements, applied throughout the entire codebase of the platform, that Node.js 10 ships with … performance, reliability and stability-centered improvements, bubbling up to the back-end developer's experience   But let's name these improvements that ship with the new version of Node.js. Let's talk specific incremental changes, shall we? 10 of the “really worth getting excited about” ones:   1. Error-Handling Improvements And error messages/error-handling improvements do make the majority of semver-major commits (approx. 300) that Node.js ships with. It's a “pledge” made since Node.js 8.0.0 to assign static error codes to all Error objects: “Error messages should be useful, more consistent and predictable”, this has been the “pledge” driving all the sustained efforts geared at improving error-handling. Note: error codes have been included in Node.js 10, making constant error-checking conveniently easier!   2. Enhanced JavaScript Language Capabilities There's an entire list of Node.js 10 language improvements (you can find them all here) worth exploring and... exploiting, I'll outline the highlights only:   you now get to use line and paragraph separator symbols (U+2028 and U+2029) in string literals, that match JSON V8 “introduces”: String.prototype.trimEnd(), String.prototype.trim(), String.prototype.trimStart() prototype.toString() returns the exact “pieces” of the source code text (comments and whitespace here included!) the catch clause of the try statements no longer calls for a parameter   3. The Node.js fs (file system) Has Been Significantly Overhauled And here are the most “dramatic” improvements made during this overhaul:   the type checking and error handling have been improved the code got restructured, for easier maintainability a new experimental fs/promises API got implemented, featuring first-class Promise-based API    Speaking of this new API, its “role” is that of generating a warning at runtime, the very first time that it gets used. Hopefully, things will turn out “bugs-free” so that it can grow from experimental to stable.   4. Node.js 10 Ships with Full Support for N-API  N-API — the ABI stable (Node.js) API for native modules — has leveled up to a stable version in Node.js 10. What does this mean?   it provides a stable module API, one that is not influenced by the changes in Node.js's V8 JavaScript engine the API layer makes upgrading a whole lot easier, streamlining production deployments and... easing module maintainers' lives … and it goes without saying that this bubbles up to native modules' maintenance costs, as well   In short: say goodbye to module breakage!   5. The Assert Module: Explore Some Crucial Improvements  All efforts targetting the assert module have been aimed at easing the internal implementation and improving the developer experience. But let me point out some of these improvements that eventually fleshed out and landed in Node.js 10:   a new “diff” view got implemented, for whenever assertion errors get generated overall the output becomes more descriptive, more... “verbose” (and implicitly more useful) better object comparisons promises support  detailed error messages   6.  Node.js 10 Ships With V8 6.6: Expect a Major Performance Boost Get ready to “exploit” V8 6.6's range of performance improvements to their full potential! Along with its new set of JavaScript language features! From them all, I can't but mention:   the async functions the async generators the promise execution   7. Cryptographic Support  Node.js 10 is the first version of the platform to include OpenSSL 1.x! And this can only translate into: Enhanced protection for your priceless data! Now, if I am to outline just 2 of the OpenSSL features to look forward tapping into, I should definitely mention:   the Polu1305 authenticator the ChaCha 20 cipher   8. The Trace Events Mechanism: Monitoring Your Code's Performance Just Got Easier That's right! Keeping a close eye on how your code's performing and being able to quickly diagnose any emerging issues is easier than ever with Node.js 10! Basically, what these trace events do is enabling that all the diagnostic information output gets collected to a file accessible to the Chrome browsers DevTools utility. No need to use a command-line flag anymore to trigger this whole trace events mechanism underlying Node.js. And since we're here, let me point out to you 2 trace events-related improvements worth getting (really) excited about:   the node.perf.usertiming category got added — its role is that of capturing, in the trace events timelines, all the Performance API user timer marks and measures.  the JavaScript API got implemented, as well; enabling/disabling trace events dynamically is now possible in Node.js:   const trace_events = require('trace_events') const tracing = trace_events.createTracing({ categories: ['node.async_hooks', 'v8'] }) tracing.enable() // do stuff tracing.disable() 9. HTTP and HTTP/2 Improvements  Another thing to get excited about, when it comes to Node.js 10's release, is given by all the incremental improvements made to HTTP and HTTP/2. Let me detail a bit:   when it comes to HTTP, the changes applied range from improved Streams API compatibility to stricter standards support, to improve header and error handling now when it comes to HTTP/2, significant progress has been made for getting it the closest to “stable mode” as possible before Node.js 10 reaches its Long Terms Support cycle. And I'm talking here about improvements made to the way trailing headers requests and responses get implemented and about overall improvements of the internal implementation and the public API   10. Node.js Ships With The Experimental Node-ChakraCore And how does this impact the developer experience? Your experience?   using the JavaScript engine to its full potential tapping into the Time Travel debugging   … gets a whole lot easier for you. You're practically enabled to detect errors way before they even get to “infest” your code. The END! This is how our list of 10 Node.js 10 features worth getting (really) excited about looks like! Do explore them and start your preparations for moving over to this new version of Node.js before October!   ... Read more
RADU SIMILEANU / May 02'2018
How to Use Bootstrap with Angular 4? Here Are 3 Ways to Add It To Your Project 
Here you are now: your Angular 4 front-end app ready to... wow its users! “Almost ready” actually! For it still needs styling... And what better HTML and CSS framework to go for than Bootstrap, right? But how to use Bootstrap with Angular 4 more precisely? How do you properly integrate it into your Angular 4 CLI project? Great news: you have not just one, but 3 options at hand for adding it! Let me get into details:   On Using Bootstrap in Your Front-End Development Process Is there any need to list here the reasons why it's precisely Bootstrap that you're planning to implement into your Angular CLI project? Angular 4, to be more specific. After all, it's the most popular framework for styling websites built in HTML, CSS and modern web & mobile JavaScript frameworks (like Angular here): It's an open source, feature-rich framework that turns front-end development into a such a “breeze”. Basically, it empowers you to build responsive layouts without the need to be a CSS “expert”. And now, let's break down further with the step-by-step “tutorial” on how to use Bootstrap with Angular 4:   Step 1: Create a New Angular Project Using Angular CLI  The very first step to take is obviously setting up a brand new project. Use the Angular Command Line Interface to generate it. But first, install it to on your system: $ npm install -g @angular/cli It's only then, once you've installed its NPM package, that you can go ahead and... generate your new project.  For doing this, just type the following command in your CLI: $ ng new myproject Next, feel free to change into that specific directory and to turn on the web server: $ cd myproject $ ng serve “App works!” This is the message that you should be seeing in your browser right now.   Step 2: Install Bootstrap to Your Project Now that you've launched your new Angular project, it's time to add your Bootstrap library, as well. And you sure aren't nickel and dimed in options. There are 4 ways to add Bootstrap to Angular 4.   Step 3: How to Use Bootstrap with Angular 4 — 3 Different Ways to Integrate It Option 1: Install Bootstrap from CDN And there are 2 particular files that you'll need to install from CDN into your project:   the Bootstrap CCS file the Bootstrap JavaScript file    Note: keep in mind to add the jQuery JavaScript library file, as well! Next, open the src/index.html file and insert the following:   the <link> element to add the Bootstrap CSS file at the end of the head section a <script> element for adding jQuery at the bottom of the body section a <script> element for inserting the Bootstrap JS file at the bottom of the body section   Eager to see “Bootstrap in action” in one of your project's component templates? Then give it a try:   open the src/app/app.component.html enter the following code there:   <div class="container"> <div class="jumbotron"> <h1>Welcome</h1> <h2>Angular & Bootstrap Demo</h2> </div> <div class="panel panel-primary"> <div class="panel-heading">Status</div> <div class="panel-body"> <h3>{{title}}</h3> </div> </div> </div> And it's the following message that this HTML template code should trigger in your browser: “app works!” Note: go for a Bootstrap theme of your choice; once you've downloaded it (from Bootswatch.com for instance), its bootstrap.min.css file will get instantly opened up in your browser. Just copy the file's URL and use it to replace the string assigned to the href attribute of the <link> element, in the index.html file. And voila! It's precisely those colors, defined by your chosen theme, that get displayed in the browser now!   Option 2: Install Bootstrap using NPM And here's another valid answer to your “How to use Bootstrap with Angular 4” dilemma! Simply enter: $ npm install bootstrap@3 jquery –save It's this command that will integrate Bootstrap and jQuery into the node_modules folder of your Angular 4 project directory. Moreover, it will include these 2 dependencies in the package.json file, as well. Once properly installed, you can find both packages at:   node_modules/bootstrap/dist/css/bootstrap.min.css node_modules/bootstrap/dist/js/bootstrap.min.js node_modules/jquery/dist/jquery.min.js   Note! You have 2 options for integrating those files into your Angular 4 project:   add the file paths to the script array and to the file path of the angular-cli.json file add the corresponding <script> and <link> elements to your index.html file   Option 3: Add NG-Bootstrap to Your Project The great thing about this method is that you'll no longer need to add jQuery and Bootstrap dependencies. Ng-Bootstrap comes packed with a set of built-in native Angular directives which are already CSS and Bootstrap's markup-based. Now, getting back to our initial “How to use Bootstrap with Angular 4” question, let's see how we install this NPM package.  For this, just enter the following command in your Angular 4 project directory: npm install --save @ng-bootstrap/ng-bootstrap Next, make sure you also install Bootstrap 4 to your project: $ npm install bootstrap@4.0.0-alpha.6 And, the final step is to add the following files:   jquery.min.js bootstrap.min.js bootstrap.min.css   … to your .angular-cli.json file Now you still need to import the Ng-Bootstrap’s core module — NgbModule — from its @ng-bootstrap/ng-bootstrap package. To do this, just type the following import statement into app.module.ts: import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; All there's left for you to do now is to add the NgbModule to the @NgModuledecorator's imports array.  And since we're here, you'll find some more than “enlightening” info (chunks of code here included!) on the 2 different options at hand for importing the NGBModule: either in your project's child modules  or in your the root module itself … in this article here on Using Bootstrap with Angular.   Using The NG-Bootstrap Components: Which Are They?  With the NgbModule installed into your Angular 4 project, you're now able to use the Ng-Bootstrap components. To leverage them in your app.component.html. Speaking of which, here are the components at hand:   Accordion Alert Rating Tabs Carousel Progressbar Collapse Datepicker Buttons Pagination Typeahead Popover Timepicker Dropdown Modal Tooltip   The END! Does this answer your “How to Use Bootstrap with Angular 4” question?  Which method of adding this front-end framework to your project is more suitable for you? ... Read more
Silviu Serdaru / Apr 30'2018