How to do it...

Let's look at how we can add authentication. To work with JWT, we'll be using jsonwebtoken from https://github.com/auth0/node-jsonwebtoken. Install it with the help of the following command:

npm install jsonwebtoken --save

Our code example for JWT will be larger than in previous examples, and it should be separated into many files. However, I avoided doing this in order to make it clearer. First, we'll need to make some declarations, and the key lines are in bold:

// Source file: src/jwt_server.js/* @flow */"use strict";const express = require("express");const app = express();const jwt = require("jsonwebtoken");const bodyParser = require("body-parser");const validateUser = require("./validate_user.js");const SECRET_JWT_KEY ...

Get Modern JavaScript Web Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.