Understanding Component Architecture: Refactoring an Angular App

In part one or this series, we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine, but unfortunately the whole app was crammed into a single component. In this article, we’ll examine a more modular component architecture. We’ll look at how to break this single component into a structured tree of smaller components that are easier to understand, re-use and maintain.

This article is part 2 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

  1. Part 0— The Ultimate Angular CLI Reference Guide
  2. Part 1— Getting our first version of the Todo application up and running
  3. Part 2— Creating separate components to display a list of todos and a single todo
  4. Part 3— Update the Todo service to communicate with a REST API
  5. Part 4— Use Angular router to resolve data.

You don’t need to have followed part one of this tutorial, for part two to make sense. You can simply grab a copy of our repo, checkout the code from part one, and use that as a starting point. This is explained in more detail below.

Angular Component Architecture

A Quick Recap

So let’s look at what we covered in part one in slightly more detail. We learned how to:

  • initialize our Todo application using the Angular CLI
  • create a Todo class to represent individual todos
  • create a TodoDataService service to create, update and remove todos
  • use the AppComponent component to display the user interface
  • deploy our application to GitHub pages.

The application architecture of part 1 looked like this:

Application Architecture

The components we discussed are marked with a red border.

In this second article, we’ll delegate some of the work that AppComponent is doing to smaller components that are easier to understand, re-use and maintain.

We’ll create:

  • a TodoListComponent to display a list of todos
  • a TodoListItemComponent to display a single todo
  • a TodoListHeaderComponent to create a new todo
  • a TodoListFooterComponent to show how many todos are left.

Application Architecture

By the end of this article, you’ll understand:

  • the basics of Angular component architecture
  • how you can pass data into a component using property bindings
  • how you can listen for events emitted by a component using event listeners
  • why it is a good practice to split components into smaller reusable components
  • the difference between smart and dumb components and why keeping components dumb is a good practice.

So let’s get started!

Up and Running

The first thing you’ll need to follow along with this article is the latest version of the Angular CLI. You can install this with the following command:

npm install -g @angular/cli@latest

If you need to remove a previous version of of the Angular CLI, here’s how:

npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that you’ll need a copy of the code from part one. This is available at https://github.com/sitepoint-editors/angular-todo-app. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.

The code that we ended with in part one and that we start with in this article is tagged as part-1. The code that we end this article with is tagged as part-2.

You can think of tags like an alias to a specific commit id. You can switch between them using git checkout. You can read more on that here.

So, to get up and running (the the latest version of the Angular CLI installed) we would do:

git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
npm install
git checkout part-1
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.

The Original AppComponent

Let’s open src/app/app.component.html and have a look at the AppComponent that we finished with in part one:

<section class="todoapp">
  <header class="header">
    <input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="newTodo.title" (keyup.enter)="addTodo()">
  <section class="main" *ngIf="todos.length > 0">
    <ul class="todo-list">
      <li *ngFor="let todo of todos" [class.completed]="todo.complete">
        <div class="view">
          <input class="toggle" type="checkbox" (click)="toggleTodoComplete(todo)" [checked]="todo.complete">
          <button class="destroy" (click)="removeTodo(todo)"></button>
  <footer class="footer" *ngIf="todos.length > 0">
    <span class="todo-count"><strong>{{todos.length}}</strong> {{todos.length == 1 ? 'item' : 'items'}} left</span>

Here’s its corresponding class in src/app/app.component.ts:

import {Component} from '@angular/core';
import {Todo} from './todo';
import {TodoDataService} from './todo-data.service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [TodoDataService]
export class AppComponent {

  newTodo: Todo = new Todo();

  constructor(private todoDataService: TodoDataService) {

  addTodo() {
    this.newTodo = new Todo();

  toggleTodoComplete(todo: Todo) {

  removeTodo(todo: Todo) {

  get todos() {
    return this.todoDataService.getAllTodos();


Although our AppComponent works fine technically, keeping all code in one big component does not scale well and is not recommended.

Adding more features to our Todo application would make the AppComponent larger and more complex, making it harder to understand and maintain.

Therefore, it’s recommended to delegate functionality to smaller components. Ideally the smaller components should be configurable so that we don’t have to rewrite their code when the business logic changes.

For example, in part three of this series we’ll update the TodoDataService to communicate with a REST API, and we want to make sure that we won’t have to change any of the smaller components when we refactor the TodoDataService.

If we look at the AppComponent template, we can extract its underlying structure as:

<!-- header that lets us create new todo -->

<!-- list that displays todos -->
<ul class="todo-list">

    <!-- list item that displays single todo -->
    <li>Todo 1</li>

    <!-- list item that displays single todo -->
    <li>Todo 2</li>

<!-- footer that displays statistics -->

If we translate this structure to Angular component names, we get:

<!-- TodoListHeaderComponent that lets us create new todo -->

<!-- TodoListComponent that displays todos -->

    <!-- TodoListItemComponent that displays single todo -->

    <!-- TodoListItemComponent that displays single todo -->

<!-- TodoListFooterComponent that displays statistics -->

Let’s see how we can use the power of Angular’s component-driven development to make this happen.

A More Modular Component Architecture — Creating the TodoListHeaderComponent

Let’s start by creating the TodoListHeader component.

From the root of our project, we use Angular CLI to generate the component for us:

$ ng generate component todo-list-header

This generates the following files for us:

create src/app/todo-list-header/todo-list-header.component.css
create src/app/todo-list-header/todo-list-header.component.html
create src/app/todo-list-header/todo-list-header.component.spec.ts
create src/app/todo-list-header/todo-list-header.component.ts

It automatically adds TodoListHeaderComponent to the AppModule declarations:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

// Automatically imported by Angular CLI
import { TodoListHeaderComponent } from './todo-list-header/todo-list-header.component';

  declarations: [

    // Automatically added by Angular CLI
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Adding a component to the module declarations is required to make sure that all view templates in the module can use it the component. Angular CLI conveniently added TodoListHeaderComponent for us so we don’t have to add it manually.

If TodoListHeaderComponent was not in the declarations and we used it in a view template, Angular would throw the following error:

Error: Uncaught (in promise): Error: Template parse errors:
'app-todo-list-header' is not a known element:
1. If 'app-todo-list-header' is an Angular component, then verify that it is part of this module.
2. If 'app-todo-list-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.

To learn more about module declarations, make sure to check out the Angular Module FAQ.

Now that we have all files generated for our new TodoListHeaderComponent, we can move the <header> element from src/app/app.component.html to src/app/todo-list-header/todo-list-header.component.html:

<header class="header">
  <input class="new-todo" placeholder="What needs to be done?" autofocus="" [(ngModel)]="newTodo.title"

Also add the corresponding logic to src/app/todo-list-header/todo-list-header.component.ts:

import { Component, Output, EventEmitter } from '@angular/core';
import { Todo } from '../todo';

  selector: 'app-todo-list-header',
  templateUrl: './todo-list-header.component.html',
  styleUrls: ['./todo-list-header.component.css']
export class TodoListHeaderComponent {

  newTodo: Todo = new Todo();

  add: EventEmitter<Todo> = new EventEmitter();

  constructor() {

  addTodo() {
    this.newTodo = new Todo();


Instead of injecting the TodoDataService in our new TodoListHeaderComponent to save the new todo, we emit an add event and pass the new todo as an argument.

We already learned that the Angular template syntax allows us to attach a handler to an event. For example, consider the following code:

<input (keyup.enter)="addTodo()">

This tells Angular to run the addTodo() method when the enter key was pressed inside the input. This works because the keyup.enter event is an event that is defined by the Angular framework.

However, we can also let a component emit its own custom events, by creating an EventEmitter and decorating it with the @Output() decorator:

import { Component, Output, EventEmitter } from '@angular/core';
import { Todo } from '../todo';

  // ...
export class TodoListHeaderComponent {

  // ...

  add: EventEmitter<Todo> = new EventEmitter();

  addTodo() {
    this.newTodo = new Todo();


So we can now assign an event handler in the view template using Angular’s event binding syntax:

<app-todo-list-header (add)="onAddTodo($event)"></app-todo-list-header>

Every time we call add.emit(value) in TodoListHeaderComponent, the onAddTodo($event) handler will be called and $event will be equal to value.

This decouples our TodoListHeaderComponent from the TodoDataService and allows the parent component to decide what needs to happen when a new todo is created.

When we update the TodoDataService to communicate with a REST API in part three, we won’t have to worry about the TodoListHeaderComponent because it’s not even aware that the TodoDataService exists.

Continue reading %Understanding Component Architecture: Refactoring an Angular App%

Source: Sitepoint

Monthly Web Development Update 3/2018: Service Workers, Building A CDN, And Cheating At Design

Service Worker is probably one of the most misrepresented technologies we currently have. When I hear people talking about it, the topic almost always revolves around serving an app when a user is offline. However, Service Worker can do so much more than that, and every week I come across new articles that show how powerful the technology really is.

This month, for example, we can learn how to use Service Worker for cross-tab messaging and to load off requests into the background with the Background Sync API. I think the toolset we now have in our browsers already allows us to build great experiences regardless of the network state. Now it’s up to us to make the experiences so great that users truly love them. And that’s probably the hardest part.


Sketch 49
Sketch 49 has arrived, and with it comes the new Prototyping in Sketch feature which lets you see the entire flow in action. (Image credit)


  • Ed Ellson examined Chrome’s Background Sync API and the retry strategy it uses to perform a request. By allowing synchronization in the background after a first attempt has failed, the API helps us improve the browsing experience for users who go offline or are on unstable connections.


Cheating At Design
Use color and weight to create visual hierarchy instead of size is only one of the seven practical tips for cheating at design that Adam Wathan and Steve Schoger share. (Image credit)


  • With GraphQL you can query exactly what you want whenever you want. This is amazing for working with an API but also has complex security implications. Instead of asking for legitimate, useful data, a malicious actor could submit an expensive, nested query to overload your server, database, network, or all of these. To prevent this from happening, Max Stoiber shows us how we can secure the GraphQL API in our projects.


  • WebKit is introducing the Storage Access API. The new API targets one of the major issues with Safari’s Intelligent Tracking Protection (ITP): Identifying users who are logged in to a first-party service but view content of it embedded on a third party (YouTube videos on a blog, for example). The Storage Access API allows third-party embeds to request access to their first-party cookies when the user interacts with them. A good solution to protect user privacy by default and allow exceptions on request.

Web Performance

  • Janos Pasztor built his own Content Delivery Network because he thinks it can be a better solution than using existing third parties. The code for the CDN of his personal website is now available on Github. A nice web performance article that looks at common solutions from a different angle.
  • A year after Facebook’s announcement to broadly use Cache-Control: Immutable, Paul Calvano examined how widespread its usage is on the web — apart from the few big players. Interesting research and it’s still sad to see that this useful performance tool is used so little. At Colloq, we use it quite a lot, which saves us a lot of traffic and load on our servers and enables us to serve a lot of pages nearly instantly to recurring users.
Global stats of a self-built CDN
Global stats for the custom CDN that Janos Pasztor built. (Image credit)





Accessibility Checklist
The Accessibility Checklist helps build accessibility into your process no matter your role or stage in a project. (Image credit)

Work & Life

  • This week I read an article by Alex Duloz, and his words still stick with me: “When we develop a new application, when we post content on the Internet, whatever we do that people will have access to, we should consider just for a minute if our contribution adds up to the level of dumbness kids/teenagers are exposed to. If it does, we should refrain from going live.” The truth is, most of us, including me, don’t consider this before posting on the Internet. We create funny things, share funny pictures and try to get fame with silly posts. But in reality, we shape society with this. Let’s try to provide more useful resources and make the consumption of this more enjoyable so young people can profit from our knowledge and not only view things we think are funny. “We should always consider how teenagers will use what we release.”
  • The MIT OpenCourseWare released a lot of free audio and video lectures. This is amazing news and makes great content available to broader masses.
  • Jake Knapp says great work requires idealism and cynicism and has strong arguments to back up this theory. An article worth reading.
  • There’s an important article on how unhappiness has grown in America’s population since around the year 2000. It reveals that while income inequality might play a role, the more important aspect is that young people who use a lot of digital media are unhappier than those who use it only up to an hour a day. Interestingly, people who don’t use digital media at all, are unhappy, too, so the outcome of this could be that we should try to use digital media only moderately — at least in our private lives. I bet it’ll make a big difference.
  • Following the theory of Michael Bradley, projects don’t necessarily need a roadmap for success. Instead, he suggests to create a moral compass that points out why the project exists and what its purpose is.

Going Beyond…

We hope you enjoyed this Web Development Update. The next one is scheduled for April 13th. Stay tuned.

Source: Smashing Magazine

Getting Started With the Mojs Animation Library: The Burst Module

We started this series by learning how to animate HTML elements using mojs. In the second tutorial, we moved on to animation of built-in SVG shapes using the Shape module. The third tutorial covered more ways of animating SVG shapes using the ShapeSwirl and stagger modules.

Now, we will learn how to animate different SVG shapes in a burst formation using the Burst module. This tutorial will depend on concepts we covered in the previous three tutorials. If you have not already read them, I would suggest that you go through them first.

Creating Basic Burst Animations

The first thing that we need to do before we can create any burst animations is instantiate a Burst object. After that, we can just specify the values of different properties to control how the animation plays out. The names of a lot of properties in the Burst module are the same as the properties in the Shape module. However, these properties perform very different tasks in this case.

The left and right properties determine the initial position of the burst instead of particles inside it. Similarly, the x and y properties determine the shift of the whole burst instead of individual particles.

The radius of the circle formed by all the burst particles is controlled by the radius property. This is very different from the radius property of individual shapes, which determines the size of those shapes. In the case of a burst, the radius determines how much further apart the individual shapes in it are going to be.

The number of shapes or particles in a single burst can be specified using the count property. By default, there will be five particles in each burst that you create. All these particles are evenly spaced over the circumference of the burst. For example, if there are four particles, they will be placed at 90 degrees to each other. If there are three particles, they will be placed at 120 degrees.

If you don’t want the burst particles to cover the whole 360 degrees, you can specify the portion that should be covered using the degree property. Any value above 0 is valid for this property. The specified number of degrees will be evenly distributed between all the particles. If the degree value is over 360, the shapes might overlap.

The angle specified using the angle property determines the angle of the whole burst. In this case, individual particles are not rotated around their own center but around the center of the burst. This is similar to how the earth revolves around the sun, which is different from the rotation of the earth on its own axis.

The scale property scales the value of all physical properties of the burst and in turn individual shapes. Just like other burst properties, all shapes in it would be scaled at once. Setting the burst scale to 3 will increase the radius of the whole burst as well as the size of individual shapes by 3.

In the following code snippet, we are creating five different bursts using the properties we just discussed.

You can see that burstA and burstE only differ in the number of degrees that they have to cover. Since the particles in burstA have to cover 360 degrees (the default value), they are placed 360/20 = 18 degrees apart. On the other hand, the particles in burstE are placed 3600/20 = 180 degrees apart. Starting from zero, the first particle is placed at 0 degrees, and the next is placed at 180 degrees. 

The third particle is then placed at 360 degrees, which is basically equal to 0 degrees. The fourth particle is then placed at 540 degrees, but that is basically equal to 180 degrees. In other words, all the odd numbered particles are placed at 0 degrees, and all the even number particles are placed at 180 degrees. In the end, you only see two particles because all others overlap with the first two.

It is important to remember that you cannot directly control the duration, delay or easing function of the burst animations. The module determines all these values automatically based on the values of different children being animated.

Manipulating Individual Burst Particles

So far in this tutorial, all the particles in a burst had the same animation applied to them. Their angle, scale, radius, and position all changed by the same value. Moreover, we were not able to control the duration and delay of either the individual particles or the burst as a whole. The mojs Burst module does not have a set of properties which can directly change all these values. However, we can specify the animation value for individual particles, which in turn affects the burst animation.

All the particles in a burst animation are considered to be children of the original Burst object. Therefore, mojs allows us to control the animation of individual burst particles using a children property, which accepts an object as its value. You can use all the ShapeSwirl properties except x and y inside the children object. This makes sense because the individual particles in a burst animation have to appear at certain positions, and allowing us to randomly change the position of individual particles will change the configuration.

Any children property values that you don’t specify will be set to the default provided by the ShapeSwirl module. In the following example, we are animating 20 different lines of our burst animation. This time, the angle property has been set on individual particles instead of the Burst object so that only the lines rotate around their center instead of the whole object. As we learned in the previous tutorial, all the ShapeSwirl objects scale down from 1 to 0 by default. That’s why the lengths of the lines change from 40 to 0 in the animation.

As I mentioned earlier, we can animate all the ShapeSwirl properties inside the burst animations. Each child in the animation can have its own set of properties. If only one value is provided, it will be applied on all the child particles. If the values are provided as an array, they will be applied sequentially, one particle at a time.

Here is the JavaScript code to create five different burst animations using all the concepts we have learned so far.

In the first burst animation, the angle applied directly on the Burst object rotates the whole group around the center of the burst object. However, the angle applied inside the children property rotates all the triangles around their own centers. We also slowed down the burst animation by changing the animation duration for all the children to 4000ms.

In the second burst animation, the color of all the triangles is taken from the array passed to the fill property. We have specified only three fill colors, but the total number of triangles is 20. In such cases, mojs keeps cycling through the array elements and fills the triangles with the same three colors again and again.

In the fourth animation, we use rand strings, which we learned about in the previous tutorial, to randomly choose a scale value for all the child particles. We also set the value of isShowEnd property to false in order to hide the particles at the end of the animation.

In the fifth animation, we use the then() method from the Shape module tutorial to play another animation sequence after the first one finishes.

Final Thoughts

The aim of this series was to get you acquainted with the basics of the mojs animation library. Each tutorial focused on a single module and how you can use the properties in that module to create basic animations. 

This last tutorial used the concepts from the previous tutorials to create slightly more complicated animations. Mojs is a very powerful animation library, and the final results you get depend on how creative you can get with all the properties, so keep experimenting.

If there is anything that you would like me to clarify in this tutorial, please let me know in the comments.

Source: Nettuts Web Development

Ethical Design: The Practical Getting-Started Guide

By now, most people working in tech know and feel the deep concerns related to surveillance capitalism fostered and upheld by the tech giants. We understand that the root of the problem lies within the business model of capitalising and monetising user data. Stories of how people are being exploited surface on a daily basis, like the recent story about how Instagram withholds like notifications to certain users, with the purpose of increasing the rate of which they open the app. In the same story, The Globe and Mail describe how former high level employees of Facebook are growing a conscience and tell horrifying stories about how features are meticulously being built to exploit human behavior and make us addicts of social media.

As designers and developers we have an obligation to build experiences that are better than that. This article explains how unethical design happens, and how to do ethical design through a set of best practices. It also helps you understand how you can plant the seed to change the meaning within the company you work for and in the design community, even if you are not part of the management layer. Change starts with a movement!

Ethical Design

Let’s start with the core terminology: According to Merriam Webster, ethics is “the discipline dealing with what is good and bad and with moral duty and obligation.” For the purpose of this article, ethics will be defined as a system of moral principles that defines what is perceived as good and evil. Ethical design is, therefore, design made with the intent to do good, and unethical design is its black hat counterpart.

Ind.ie is a social enterprise striving for justice in the digital age. It is founded by Aral Balkan and Laura Kalbag who defined an “Ethical Hierarchy of Needs” that describe the core of ethical design very well.

Ethical Hierarchy of Needs
The ‘Ethical Hierarchy of Needs’ (licensed under CC BY 4.0) (Source: ind.ie)

As with any pyramid-shaped structure, the layers in the Ethical Hierarchy of Needs rest on the layer below it. If any layer is broken, the layers resting on top of it will collapse. If a design does not support human rights, it is unethical. If it supports human rights but does not respect human effort by being functional, convenient and reliable (and usable!), then it is unethical. If it respects human effort but does not respect human experience by making a better life for the people using it, then it is still unethical.

From a practical viewpoint, this means that products and services which exploit user data, use dark patterns and generally are only out to make money, disregarding its human purpose, are unethical. Let’s look at how unethical design manifests itself in business models and design decisions.

Unethical Design: The Black Hat Of The Business 

Surveillance Capitalism

Data-driven design can be used to do good. But more often than not it is used with monetary intent also known as surveillance capitalism.

As Aral Balkan, ethical designer and founder of ind.ie puts it:

“When a company like Facebook improves the experience of its products, it’s like the massages we give to Kobe beef: they’re not for the benefit of the cow but to make the cow a better product. In this analogy, you are the cow.”

Surveillance capitalism is unethical by nature because at its core, it takes advantage of rich data to profile people and understand their behavior with the sole purpose of making money. The most chilling thought of all is how data is being used not just to predict and manipulate current behavior, but how it is used to profile our future selves through machine learning, ultimately giving companies the power to impact our future decisions and behavioral patterns.

As Cracked Labs, independent research institute and creative laboratory, states in their report about Data Against People:

“Systems that make decisions about people based on their data produce substantial adverse effects that can massively limit their choices, opportunities, and life-chances”.

This happens on a daily basis to everyone who use Facebook, where the individualized feed is carefully filtered to show the posts most likely to trigger engagement and activity. Pricing is also becoming increasingly individualized because companies are able to use rich data to assess the long-term value of customers, also known as data-driven persuasion.

Data trade and data tracking is big business. According to the report “Corporate Surveillance in Everyday Life”, Oracle provides access to 5 billion (yes, billion!) unique user ID’s (this is confirmed on Oracle’s website). The word “scared” does not cover the emotional state which we should all be in over that fact.

Table view that shows the enormous amount of data held by large online platforms, credit card agencies and consumer data brokers.
An overview of the amount of profiles held by online platforms, credit reporting agencies and consumer data brokers as of June 2017. (Source: Corporate Surveillance in Everyday Life, CC BY-SA 4.0, Cracked Labs)

One can only imagine how companies will be able to utilize data to profile which of us are more likely to develop mental health or physical issues, thus putting us in the “no thanks” pile of applications for our future jobs. With this in mind, I fear for the future of my children.

To some the above sounds like something out of a science fiction movie, but it is not far-fetched at all. Unethical companies are exposed daily, from the VPN app who claimed to protect the data of their 24 million users, but sold it to Facebook to the software called Alphonso which, according to an article in The New York Times, is used in more than 250 game apps (some of which are designed for children) to monitor what tv ads people watch, even if the app is not in active use. The list of companies who harvest and use data with deeply unethical purposes goes on and on and on.

Black Hat Design

Nevertheless, data tracking is not the only way that unethical design plays out. Dark patterns fall under unethical design too, as they are black hat design patterns specifically designed to trick us into doing something we don’t necessarily want to do. It may not be considered unethical when a company makes use of the dark pattern called Roach Motel to make it nearly impossible to delete your account (looking at you, Skype). But looking at the motivation of the business side, it is not hard to see the unethical nature of the design, naming the Chinese shoe company who tricked people to swipe by adding a fake strand of hair on their Instagram ad as just one example.

Source: Smashing Magazine

Number().toFixed() Rounding Errors: Broken But Fixable

This article was originally published on David Kaye.

I found a rounding bug in Number().toFixed() in every JavaScript environment I’ve tried (Chrome, Firefox, Internet Explorer, Brave, and Node.js). The fix is surprisingly simple. Read on…

Warm Up

I found this version of the rounding bug in toFixed() while revising a number-formatting function that performs the same kind of thing as Intl.NumberFormat#format().

(1.015).toFixed(2) // returns "1.01" instead of "1.02"

The failing test is on line 42 here. I had missed it until December 2017, and that spurred me to check for other problems.

See my tweets about it:

Bug Reports

There is a long history of bug reports with respect to rounding errors using toFixed().

Here is a short sample of StackOverflow questions about this problem:

In general, these point out a bug for a value, but none reports a range or pattern of values returning erroneous results (at least none that I have found, I may have missed something). That leaves the programmers to focus on the small without seeing a larger pattern. I don’t blame them for that.

Finding the Pattern

Unexpected results based on input must arise from a shared pattern in the input. So, rather than review the specification for Number().toFixed(), I focused on testing with a series of values to determine where the bug shows up in each series.

Test Function

I created the following test function to exercise toFixed() over a series of integers ranging from 1 to a maxValue, adding the fraction such as .005 to each integer. The fixed (number of digits) argument to toFixed() is calculated from the length of the fraction value.

Continue reading %Number().toFixed() Rounding Errors: Broken But Fixable%

Source: Sitepoint

How BBC Interactive Content Works Across AMP, Apps, And The Web

In the Visual Journalism team at the BBC, we produce exciting visual, engaging and interactive content, ranging from calculators to visualizations new storytelling formats.

Each application is a unique challenge to produce in its own right, but even more so when you consider that we have to deploy most projects in many different languages. Our content has to work not only on the BBC News and Sports websites but on their equivalent apps on iOS and Android, as well as on third-party sites which consume BBC content.

Now consider that there is an increasing array of new platforms such as AMP, Facebook Instant Articles, and Apple News. Each platform has its own limitations and proprietary publishing mechanism. Creating interactive content that works across all of these environments is a real challenge. I’m going to describe how we’ve approached the problem at the BBC.

Example: Canonical vs. AMP

This is all a bit theoretical until you see it in action, so let’s delve straight into an example.

Here is a BBC article containing Visual Journalism content:

Screenshot of BBC News page containing Visual Journalism content
Our Visual Journalism content begins with the Donald Trump illustration, and is inside an iframe

This is the canonical version of the article, i.e., the default version, which you’ll get if you navigate to the article from the homepage.

Now let’s look at the AMP version of the article:

Screenshot of BBC News AMP page containing same content as before, but content is clipped and has a Show More button
This looks like the same content as the normal article, but is pulling in a different iframe designed specifically for AMP

While the canonical and AMP versions look the same, they are actually two different endpoints with different behavior:

  • The canonical version scrolls you to your chosen country when you submit the form.
  • The AMP version doesn’t scroll you, as you cannot scroll the parent page from within an AMP iframe.
  • The AMP version shows a cropped iframe with a ‘Show More’ button, depending on viewport size and scroll position. This is a feature of AMP.

Source: Smashing Magazine

Uncode WordPress Theme: Share Your Creativity with the World

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible.

The world we live in is a visual world. We process information contained in images faster than we do when reading a text. Creatives’ websites largely rely on stunning visual experiences that can command attention. These visuals usually make a strong impression on their visitors.

It takes a significant amount of planning to produce a website that can make a strong statement. The process also requires careful attention to detail.

Uncode is the ideal choice if your objective is to take full advantage of the power of visuals. The website-building tools and features you need will be at your fingertips. So, you don’t have to be an expert in website design to apply them.

Why Uncode?

Uncode has everything a creative type requires to create a website, blog, or portfolio. They will be able to capture a visitor’s attention and keep that visitor engaged and looking for more.

No special technical or coding skills are needed. Uncode is exceptionally easy to work with. It’s simply a matter of selecting a template and uploading your content. Then, the only thing left is to hit the Publish button. If you have your own idea for a template, you can build your own; all the tools you need are there.

Uncode’s selection of demos are themselves memorable visual experiences. They are designed to help you provide the same experiences to your visitors. Is a cool eCommerce design, a one-click gallery, or a hypnotic parallax image to your liking? It is all there, and much more.

Uncode’s New and Improved Features

A cool and exciting assortment of new features were introduced in Uncode version 1.7. With these features, you can create visual experiences that are even more memorable.

Slides Scroll and Snap Scroll

In terms of what you can do with a one-page website, Slides Scroll is a jaw-dropper. Do not attempt to create an attractive yet somewhat ho-hum page. Instead, you can apply this feature to accomplish the following:

  • You can mix and match galleries, slides, and content sections. Do this to get the maximum effect – no constraints.
  • You can place visuals wherever you want on a blank canvas while building a single, scrollable page.
  • Your site visitors can effortlessly move from section to section. They can experience awesome transitions you’ve created as they do so.

Use the Gallery Manager and Albums Gallery Features for Extra Sparkle

With Gallery Manager, you can arrange a showcase or portfolio of your work with just a few clicks. This makes it much easier for you to achieve the most impressive arrangement of visuals. You can do so in the shortest amount of time.

You’ll find Albums Gallery helpful when you have an abundance of material to display. You can place and locate independent or categorized galleries within a parent gallery.

A New Admin – and More

The new admin panel isn’t an upgrade. It’s been redesigned from the ground up. It sports an attractive new user interface and enhanced Demo Layout Installer. Do not forget about reorganized Theme Options.

The popular Adaptive Images feature has also undergone improvement. As an added touch, Uncode’s entire UI has been reworked, improved, and nicely matches a sleek new skin.

You’ll Find Great New Concepts to Work With

New concepts are forever being added. As usual, the following new concepts are based on user feedback.

Creative Director

Creative Director

Have you been itching to tell the world what you’re capable of creating? Then, the attention-getting Creative Director layout is what you are looking for.

Classic Firm

Classic Firm

Classic Firm

Classic Firm was created with a vision to satisfy the needs of artist collectives. It will also be just right for contemporary art studios.

Shop Techie

Shop Techie

This image doesn’t tell the whole story. Shop Techie takes full advantage of the Slide Scroll feature. It creates a stunning and exciting eCommerce experience.

Shop Parallax

Shop Parallax

Explore Shop Parallax to experience the hypnotic effect fullscreen slides can have. Users are enjoying this feature as they browse an online shop’s offerings.

Portfolio Albums

Portfolio Albums

No surprise here. Portfolio Albums is the ideal starting point for creating stunning photographic portfolios.

Showcase Updates

Uncode users are justifiably proud of their work. This showcase of their website creations offers visual proof of why this is so. Written testimonials are nice. But these hundreds of creative visuals say so much more.

Take time browsing through them. You are sure to come up with inspiration for your future endeavors.

Old Favorites

New features are exciting and always welcome. Especially when they create new opportunities for you. At the same time, Uncode’s time-tested and most popular features haven’t gone anywhere. Some have been improved upon, and others are untouched.

Visual Composer: Tailored to Better Suit Your Needs

Uncode’s tailored version of Visual Composer has always been popular. Working with Uncode’s Content Blocks, it makes organizing your content especially easy. The tailored version also removes any limitations on incorporating media into your sites.

Finding What Works Best: 6+ Menu Styles

When you have some good options to select from, it can be hard to come to a decision. On the other hand, it’s much easier when you focus on what will work best in your case. Whichever one you end up with will support intuitive, trouble-free navigation.

And the Winner for Most Popular Is: The Adaptive Images Feature

Have you ever experienced a problem with making things fit on mobile device screens? Uncode’s Adaptive Images automatic image re-scaling feature will take care of that.

Adaptive Images is but one of the many Uncode “most popular” features.

Professional Looking Layouts for Your Blogs and Portfolios

This is another favorite feature (perhaps with a capital F). These layouts have proven to be extremely popular with creative professionals. As they are easily modified, you can play around with any one of them. Do so until you get precisely what you’re looking for.

WooCommerce Single Product Features

Customize your online shop and give it some extra selling power. Uncode’s Single Product Features will help you with that. These include custom width layout controls, carousel, and stack layout options. They also have Product Zoom to add some extra pizzazz to your presentations. Plus, you can customize your product pages to the minutest of details.

Wrapping It Up: Why Is Uncode Ideal for Creatives?

  • Uncode‘s focus is on creating stunning visual experiences. These naturally lead to stunning websites.
  • Everything you need is there to help you showcase your work in ways that will stand out from the crowd.
  • Uncode does so much, so easily. You don’t even have to be a web designer to create breathtaking visuals. You don’t have to be a programmer either; everything happens with mouse clicks.
  • Create a blog or build an awesome portfolio in only a few hours. Then you can sit back and decide how to spend the rest of your day.

Continue reading %Uncode WordPress Theme: Share Your Creativity with the World%

Source: Sitepoint

Build a Preact App with Authentication

This article was originally published on OKTA Blog. Thank you for supporting the partners who make SitePoint possible.

React is a fast, and lightweight library, which has led to fast adoption across the SPA (single-page app) ecosystem. Preact is an even lighter-and-faster alternative to React, weighing in at a measly 3kb! For less complex applications, it can be a great choice.

In this tutorial, you’ll build a basic Preact application with a couple of pages and user authentication using the Okta Sign-In Widget.

Bootstrap Your App With PreactCLI

To get your project started, you’ll install the PreactCLI using NPM.

npm install -g preact-cli

Once you have the CLI installed, run the command to create a base Preact application:

preact create okta-preact-example

This command will chug along for a few minutes scaffolding a basic Preact app and installing all the dependencies. Once it’s done, you should see a bunch of information on the command line informing you of what you can do next.

Change into the application directory.

cd okta-preact-example

Then start the application, just to make sure everything worked as expected.

npm start

You should see a quick build run and the screen will clear and show you that the application is running at http://localhost:8080. When you open up that URL in your browser, you should see a page like this:

Base Preact Application

Some Things To Note About PreactCLI

Even though the PreactCLI-generated app looks a lot like a React app generated by create-react-app, and you can even use some of the React plugins (like React-Router) in your Preact application, there are some significant differences.

For instance, unlike the ReactCLI, there is no way to eject the Webpack configuration. Instead Preact encourages developers to customize Webpack by creating a file called preact.config.js, using Preact’s Webpack Config Helpers and exporting functions to change the way Webpack behaves.

Even though the PreactCLI says the application is running at, use http://localhost:8080. It’s the same thing and when you set up your application in the Okta dashboard, you’ll set http://localhost:8080 as your base URL and callback URL, so this just makes sure that you can call the Okta APIs.

Create Your Okta Application

Now that you have the basic shell of an application, it’s time to add user authentication. If you don’t already have one, create a free (forever) account at Okta.

Once you’ve created an account, go to the admin dashboard and click on “Applications” in the page menu. Then click the green “Add Application” button, then the green “Create New App” button, so that you see a modal window like:

Create Application Screen

Choose “SPA” from the Platform buttons. Click the “Next” button to create your application.

This will take you to a screen to “Application Settings” page of the Create Application wizard. Enter “OktaPreactExample” in the Application name field and add http://localhost:8080 as your base URI and as a login redirect URI. When you’re done, your form should look like this:

Create Integration Screen

You’ll need to create a user (if you don’t already have one) and assign your new application to them as well. Or you can log in with the credentials you use to log in to your Okta account (the admin user).

Install the Okta Sign In Widget

The easiest way to get Okta’s authentication into your new Preact application will be to use Okta’s Sign-In Widget. You’ll install it with npm using:

npm install @okta/okta-signin-widget --save

You’ll also need to install preact-router with:

npm install preact-router --save

Add an Auth Higher-Order Component

With that done, you now need to add some Higher-Order Components to help with authentication.

Add a file called auth.js in the /src/lib folder and add the following code:

import {h} from 'preact';
import { route } from 'preact-router';
import OktaSignIn from '@okta/okta-signin-widget/dist/js/okta-sign-in.min.js';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
import '@okta/okta-signin-widget/dist/css/okta-theme.css';

class Auth {
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);

    this.widget = new OktaSignIn({
      baseUrl: 'https://{yourOktaDomain}.com/',
      clientId: '{clientId}',
      redirectUri: 'http://localhost:8080',
      authParams: {
        responseType: ['id_token', 'token'],
        scopes: ['openid', 'email', 'profile']

  isAuthenticated() {
    // Checks if there is a current accessToken in the TokenManger.
    return !!this.widget.tokenManager.get('accessToken');

    return this.widget.tokenManager.get('idToken');

  login() {
    // Redirect to the login page

  async logout() {
    await this.widget.signOut();
    location = '/';

  handleAuthentication(tokens) {
    for (let token of tokens) {
      if (token.idToken) {
        this.widget.tokenManager.add('idToken', token);
      } else if (token.accessToken) {
        this.widget.tokenManager.add('accessToken', token);

// create a singleton
const auth = new Auth();
export const withAuth = WrappedComponent => props =>
  <WrappedComponent auth={auth} {...props} />;

In the first line of code, you can tell something’s different. The h module in Preact is what turns JSX into DOM elements. Normally, React would use the React library to generate React.createElement statements to make DOM elements from JSX. Preact uses the h library to make something like h('div', {class:'something'}, 'Content') statements to do that.

Next, you imported route from preact-router right below the h import. This is what is used by Preact to do the redirects in the login function. Notice that the Auth class is just a regular function and does not extend Component. In the constructor, the internal functions were bound with the this context from the Auth class.

Then enter your Okta organization URL and client ID to the Okta Sign-In Widget configuration. Your Organization URL will be the URL you use when you log into your Okta account (e.g. http://dev-12345.oktapreview.com) and you can get your client ID from the application’s property page in the administrative dashboard on the “General” tab for your application (obviously, yours won’t be blurred out):

Client ID Screen

You’ll also want to change the redirectUri property to http://localhost:8080 because the Preact uses port 8080 instead of 3000 for normal React apps.

The login function simply routes the user to the login page, while the logout function clears the tokens saved in the widget’s token manager, calls signOut on the widget, and redirects the user to the root of the application.

Finally, a singleton of the Auth class is created to be shared by all the components, and is passed in as a prop called auth to any component that you wrap in withAuth.

Create a Widget Wrapper

Create a file in your /src/lib folder called OktaSignInWidget.js. Enter the code for this component:

Continue reading %Build a Preact App with Authentication%

Source: Sitepoint

How To Make A WordPress Plugin Extensible

Have you ever used a plugin and wished it did something a bit differently? Perhaps you needed something unique that was beyond the scope of the settings page of the plugin.

I have personally encountered this, and I’m betting you have, too. If you’re a WordPress plugin developer, most likely some of your users have also encountered this while using your plugin.

Here’s a typical scenario: You’ve finally found that plugin that does everything you need — except for one tiny important thing. There is no setting or option to enable that tiny thing, so you browse the documentation and find that you can’t do anything about it. You request the feature in the WordPress plugin’s support forum — but no dice. In the end, you uninstall it and continue your search.

Imagine if you were the developer of this plugin. What would you do if a user asked for some particular functionality?

The ideal thing would be to implement it. But if the feature was for a very special use case, then adding it would be impractical. It wouldn’t be good to have a plugin setting that only 0.1% of your users would have a use for.

You’d only want to implement features that affect the majority of your users. In reality, 80% of users use 20% of the features (the 80/20 rule). So, make sure that any new feature is highly requested, and that 80% of your users would benefit from it, before implementing it. If you created a setting for every feature that is requested, then your plugin would become complicated and bloated — and nobody wants that.

Your best bet is to make the plugin extensible, code-wise, so that other people can enhance or modify it for their own needs.

In this article, you’ll learn about why making your plugin extensible is a good idea. I’ll also share a few tips of how I’ve learned to do this.

What Makes A Plugin Extensible?

In a nutshell, an extensible plugin means that it adheres to the “O” part of the SOLID principles of object-oriented programming — namely, the open/closed principle.

If you’re unfamiliar with the open/closed principle, it basically means that other people shouldn’t have to edit your code in order to modify something.

Applying this principle to a WordPress plugin, it would mean that a plugin is extensible if it has provisions in it that enable other people to modify its behavior. It’s just like how WordPress allows people to “hook” into different areas of WordPress, but at the level of the plugin.

A Typical Example Of A Plugin

Let’s see how we can create an extensible plugin, starting with a sample plugin that isn’t.

Suppose we have a plugin that generates a sidebar widget that displays the titles of the three latest posts. At the heart of the plugin is a function that simply wraps the titles of those three posts in list tags:

function get_some_post_titles() {
  $args = array(
      'posts_per_page' => 3,

  $posts = get_posts( $args );

  $output = '
    '; foreach ( $posts as $post ) { $output .= '
  • ' . $post->post_title . '
  • '; } $output .= '
'; return $output; }

While this code works and gets the job done, it isn’t quite extensible.

Why? Because the function is set in its own ways, there’s no way to change its behavior without modifying the code directly.

What if a user wanted to display more than three posts, or perhaps include links with the posts’ titles? There’s no way to do that with the code above. The user is stuck with how the plugin works and can nothing to change it.

Including A Hundred Settings Isn’t The Answer

There are a number of ways to enhance the plugin above to allow users to customize it.

One such way would be to add a lot of options in the settings, but even that might not satisfy all of the possibilities users would want from the plugin.

What if the user wanted to do any of the following (scenarios we’ll revisit later):

  • display WooCommerce products or posts from a particular category;
  • display the items in a carousel provided by another plugin, instead of as a simple list;
  • perform a custom database query, and then use those query’s posts in the list.

If we added a hundred settings to our widget, then we would be able to cover the use cases above. But what if one of these scenarios changes, and now the user wants to display only WooCommerce products that are currently in stock? The widget would need even more settings to accommodate this. Pretty soon, we’d have a gazillion settings.

Also, a plugin with a huge list of settings isn’t exactly user-friendly. Steer away from this route if possible.

So, how would we go about solving this problem? We’d make the plugin extensible.

Adding Our Own Hooks To Make It Extensible

By studying the plugin’s code above, we see a few operations that the main function performs:

  • It gets posts using get_posts.
  • It generates a list of post titles.
  • It returns the generated list.

If other people were to modify this plugin’s behavior, their work would mostly likely involve these three operations. To make our plugin extensible, we would have to add hooks around these to open them up for other developers.

In general, these are good areas to add hooks to a plugin:

  • around and within the major processes,
  • when building output HTML,
  • for altering post or database queries,
  • before returning values from a function.

A Typical Example Of An Extensible Plugin

Taking these rules of thumb, we can add the following filters to make our plugin extensible:

  • add myplugin_get_posts_args for modifying the arguments of get_posts,
  • add myplugin_get_posts for overriding the results of get_posts,
  • add myplugin_list_item for customizing the generation of a list entry,
  • add myplugin_get_some_post_titles for overriding the returned generated list.

Here’s the code again with all of the hooks added in:

function get_some_post_titles() {
  $args = array(
      'posts_per_page' => 3,

  // Let other people modify the arguments.
  $posts = get_posts( apply_filters( 'myplugin_get_posts_args', $args ) );

  // Let other people modify the post array, which will be used for display.
  $posts = apply_filters( 'myplugin_get_posts', $posts, $args );

  $output = '
    '; foreach ( $posts as $post ) { // Let other people modify the list entry. $output .= '
  • ' . apply_filters( 'myplugin_list_item', $post->post_title, $post ) . '
  • '; } $output .= '
'; // Let other people modify our output list. return apply_filters( 'myplugin_get_some_post_titles', $output, $args ); }

You can also get the code above in the GitHub archive.

I’m adding a lot of hooks here, which might seem impractical because the sample code is quite simple and small, but it illustrates my point: By adding just four hooks, other developers can now customize the plugin’s behavior in all sorts of ways.

Namespacing And Context For Hooks

Before proceeding, note two important things about the hooks we’ve implemented:

  • We’re namespacing the hooks with myplugin_.
    This ensures that the hook’s name doesn’t conflict with some other plugin’s hook. This is just good practice, because if another hook with the same name is called, it could lead to unwanted effects.
  • We’re also passing a reference to $args in all of the hooks for context.
    I do this so that if others use this filter to change something in the flow of the code, they can use that $args parameter as a reference to get an idea of why the hook was called, so that they can perform their adjustments accordingly.

The Effects Of Our Hooks

Remember the unique scenarios I talked about earlier? Let’s revisit those and see how our hooks have made them possible:

  • If the user wants to display WooCommerce products or posts from a particular category, then either they can use the filter myplugin_get_posts_args to add their own arguments for when the plugin queries posts, or they can use myplugin_get_posts to completely override the posts with their own list.
  • If the user wants to display the items in a carousel provided by another plugin, instead of as a simple list, then they can override the entire output of the function with myplugin_get_some_post_titles, and instead output a carousel from there.
  • If the user wants to perform a custom database query and then use that query’s posts in the list, then, similar to the first scenario, they can use myplugin_get_posts to use their own database query and change the post array.

Much better!

A Quick Example Of How To Use Our Filters

Developers can use add_filter to hook into our filters above (or use add_action for actions).

Taking our first scenario above, a developer can just do the following to display WooCommerce products using the myplugin_get_posts_args filter that we created:

add_filter( 'myplugin_get_posts_args', 'show_only_woocommerce_products' );
function show_only_woocommerce_products( $args ) {
   $args['post_type'] = 'product';
   return $args;

We Can Also Use Action Hooks

Aside from using apply_filters, we can also use do_action to make our code extensible. The difference between the two is that the first allows others to change a variable, while the latter allows others to execute additional functionality in various parts of our code.

JWT Authentication in Django

This tutorial will give an introduction to JSON Web Tokens (JWT) and how to implement JWT authentication in Django.

What Is JWT?

JWT is an encoded JSON string that is passed in headers to authenticate requests. It is usually obtained by hashing JSON data with a secret key. This means that the server doesn’t need to query the database every time to retrieve the user associated with a given token.

How JSON Web Tokens Work

When a user successfully logs in using their credentials, a JSON Web Token is obtained and saved in local storage. Whenever the user wants to access a protected URL, the token is sent in the header of the request. The server then checks for a valid JWT in the Authorization header, and if found, the user will be allowed access.

A typical content header will look like this:

Bearer eyJhbGciOiJIUzI1NiIsI

Below is a diagram showing this process:

How JSON Web Tokens Work

The Concept of Authentication and Authorization

Authentication is the process of identifying a logged-in user, while authorization is the process of identifying if a certain user has the right to access a web resource.

API Example

In this tutorial, we are going to build a simple user authentication system in Django using JWT as the authentication mechanism.


  • Django
  • Python

Let’s get started.

Create a directory where you will keep your project and also a virtual environment to install the project dependencies.

Activate the virtual environment:

Create a Django project.

Install DRF and django-rest-framework-jwt using pip.

Let’s go ahead and add DRF to the list of installed apps in the settings.py file.

Configure the JWT Settings

In order to use JWT, we need to configure django-rest-framework permissions to accept JSON Web Tokens.

In the settings.py file, add the following configurations:

Create a new app called users which will handle user authentication and management.

Add the users application to the list of installed apps in the settings.py file.

Setting Up the Database

We are going to use the PostgreSQL database because it’s more stable and robust.

Create the auth database and assign a user.

Switch over to the Postgres account on your machine by typing:

Access the Postgres prompt and create the database:

Create a role:

Grant database access to the user:

Install the psycopg2 package, which will allow us to use the database we configured:

Edit the currently configured SQLite database and use the Postgres database.

Creating Models

Django comes with a built-in authentication system which is very elaborate, but sometimes we need to make adjustments, and thus we need to create a custom user authentication system. Our user model will be inheriting from the AbstractBaseUser class provided by django.contrib.auth.models.

In users/models.py, we start by creating the User model to store the user details.

REQUIRED_FIELDS contains all required fields on your user model, except the username field and password, as these fields will always be prompted for.

UserManager is the class that defines the create_user and createsuperuser methods. This class should come before the AbstractBaseUser class we defined above. Let’s go ahead and define it.


Migrations provide a way of updating your database schema every time your models change, without losing data.

Create an initial migration for our users model, and sync the database for the first time.

Creating a Superuser

Create a superuser by running the following command:

Creating New Users

Let’s create an endpoint to enable registration of new users. We will start by serializing the User model fields. Serializers provide a way of changing data to a form that is easier to understand, like JSON or XML. Deserialization does the opposite, which is converting data to a form that can be saved to the database.

Create users/serializers.py and add the following code.


Next, we want to create a view so the client will have a URL for creating new users.

In users.views.py, add the following:

We set permission_classes to (AllowAny,) to allow any user (authenticated or not) to access this URL.

Configuring URLs

Create a file users/urls.py and add the URL to match the view we created. Also add the following code.

We also need to import URLs from the users application to the main django_auth/urls.py file. So go ahead and do that. We are using the include function here, so don’t forget to import it.

Now that we are done creating the endpoint, let’s do a test and see if we are on track. We will use Postman to do the tests. If you are not familiar with Postman, it’s a tool which presents a friendly GUI for constructing requests and reading responses.

Configuring URLs

As you can see above, the endpoint is working as expected.

Authenticating Users

We will make use of the Django-REST Framework JWT Python module we installed at the beginning of this tutorial. It adds JWT authentication support for Django Rest Framework apps.

But first, let’s define some configuration parameters for our tokens and how they are generated in the settings.py file.

  • JWT_VERIFY: It will raise a jwt.DecodeError if the secret is wrong.
  • JWT_VERIFY_EXPIRATION: Sets the expiration to True, meaning Tokens will expire after a period of time. The default time is five minutes.
  • JWT_AUTH_HEADER_PREFIX: The Authorization header value prefix that is required to be sent together with the token. We have set it as Bearer, and the default is JWT.

In users/views.py, add the following code.

In the code above, the login view takes username and password as input, and it then creates a token with the user information corresponding to the passed credentials as payload and returns it to the browser. Other user details such as name are also returned to the browser together with the token. This token will be used to authenticate in future requests.

The permission classes are set to allowAny since anyone can access this endpoint.

We also store the last login time of the user with this code.

Every time the user wants to make an API request, they have to send the token in Auth Headers in order to authenticate the request.

Let’s test this endpoint with Postman. Open Postman and use the request to authenticate with one of the users you created previously. If the login attempt is successful, the response will look like this:

A sample response

Retrieving and Updating Users

So far, users can register and authenticate themselves. However, they also need a way to retrieve and update their information. Let’s implement this.

In users.views.py, add the following code.

We first define the permission classes and set to IsAuthenticated since this is a protected URL and only authenticated users can access it. 

We then define a get method to retrieve user details. After retrieving user details, an authenticated user will then update their details as desired.

Update your URLs to define the endpoint as follows.

In order for the request to be successful, the headers should contain the JWT token as shown below.

Headers with the JWT Token

If you attempt to request a resource without the authentication header, you will get the following error.

An example error

If a user stays beyond the time specified in JWT_EXPIRATION_DELTA without making a request, the token will expire and they will have to request another token. This is also demonstrated below.



This tutorial has covered what is necessary to successfully build a solid back-end authentication system with JSON Web Tokens.

Source: Nettuts Web Development