How to Use TypeScript to Build a Node API with Express

Like it or not, JavaScript has been helping developers power the Internet since 1995. In that time, JavaScript usage has grown from small user experience enhancements to complex full-stack applications using Node.js on the server and one of many frameworks on the client such as Angular, React, or Vue.
Today, building JavaScript applications at scale remains a challenge. More and more teams are turning to TypeScript to supplement their JavaScript projects.
Node.js server applications can benefit from using TypeScript, as well. The goal of this tutorial is to show you how to build a new Node.js application using TypeScript and Express.
The Case for TypeScript
As a web developer, I long ago stopped resisting JavaScript, and have grown to appreciate its flexibility and ubiquity. Language features added to ES2015 and beyond have significantly improved its utility and reduced common frustrations of writing applications.
However, larger JavaScript projects demand tools such as ESLint to catch common mistakes, and greater discipline to saturate the code base with useful tests. As with any software project, a healthy team culture that includes a peer review process can improve quality and guard against issues that can creep into a project.
The primary benefits of using TypeScript are to catch more errors before they go into production and make it easier to work with your code base.
TypeScript is not a different language. It’s a flexible superset of JavaScript with ways to describe optional data types. All “standard” and valid JavaScript is also valid TypeScript. You can dial in as much or little as you desire.
As soon as you add the TypeScript compiler or a TypeScript plugin to your favorite code editor, there are immediate safety and productivity benefits. TypeScript can alert you to misspelled functions and properties, detect passing the wrong types of arguments or the wrong number of arguments to functions, and provide smarter autocomplete suggestions.
Build a Guitar Inventory Application with TypeScript and Node.js
Among guitar players, there’s a joke everyone should understand.

Q: “How many guitars do you need?”
A: “n + 1. Always one more.”

In this tutorial, you are going to create a new Node.js application to keep track of an inventory of guitars. In a nutshell, this tutorial uses Node.js with Express, EJS, and PostgreSQL on the backend, Vue, Materialize, and Axios on the frontend, Okta for account registration and authorization, and TypeScript to govern the JavaScripts!

Create Your Node.js Project
Open up a terminal (Mac/Linux) or a command prompt (Windows) and type the following command:
node –version

If you get an error, or the version of Node.js you have is less than version 8, you’ll need to install Node.js. On Mac or Linux, I recommend you first install nvm and use nvm to install Node.js. On Windows, I recommend you use Chocolatey.
After ensuring you have a recent version of Node.js installed, create a folder for your project.
mkdir guitar-inventory
cd guitar-inventory

Use npm to initialize a package.json file.
npm init -y

Hello, world!
In this sample application, Express is used to serve web pages and implement an API. Dependencies are installed using npm. Add Express to your project with the following command.
npm install express

Next, open the project in your editor of choice.

If you don’t already have a favorite code editor, I use and recommend Visual Studio Code. VS Code has exceptional support for JavaScript and Node.js, such as smart code completing and debugging, and there’s a vast library of free extensions contributed by the community.

Create a folder named src. In this folder, create a file named index.js. Open the file and add the following JavaScript.
const express = require( “express" );
const app = express();
const port = 8080; // default port to listen

// define a route handler for the default home page
app.get( "/", ( req, res ) => {
res.send( "Hello world!" );
} );

// start the Express server
app.listen( port, () => {
console.log( `server started at http://localhost:${ port }` );
} );

Next, update package.json to instruct npm on how to run your application. Change the main property value to point to src/index.js, and add a start script to the scripts object.
"main": "src/index.js",
"scripts": {
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},

Now, from the terminal or command line, you can launch the application.
npm run start

If all goes well, you should see this message written to the console.
server started at http://localhost:8080

Launch your browser and navigate to http://localhost:8080. You should see the text “Hello world!”

Note: To stop the web application, you can go back to the terminal or command prompt and press CTRL+C.

Set Up Your Node.js Project to Use TypeScript
The first step is to add the TypeScript compiler. You can install the compiler as a developer dependency using the –save-dev flag.
npm install –save-dev typescript

The next step is to add a tsconfig.json file. This file instructs TypeScript how to compile (transpile) your TypeScript code into plain JavaScript.
Create a file named tsconfig.json in the root folder of your project, and add the following configuration.
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*"
]
}
},
"include": [
"src/**/*"
]
}

Based on this tsconfig.json file, the TypeScript compiler will (attempt to) compile any files ending with .ts it finds in the src folder, and store the results in a folder named dist. Node.js uses the CommonJS module system, so the value for the module setting is commonjs. Also, the target version of JavaScript is ES6 (ES2015), which is compatible with modern versions of Node.js.
It’s also a great idea to add tslint and create a tslint.json file that instructs TypeScript how to lint your code. If you’re not familiar with linting, it is a code analysis tool to alert you to potential problems in your code beyond syntax issues.
Install tslint as a developer dependency.
npm install –save-dev typescript tslint

Next, create a new file in the root folder named tslint.json file and add the following configuration.
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {
"trailing-comma": [ false ]
},
"rulesDirectory": []
}

Next, update your package.json to change main to point to the new dist folder created by the TypeScript compiler. Also, add a couple of scripts to execute TSLint and the TypeScript compiler just before starting the Node.js server.
"main": "dist/index.js",
"scripts": {
"prebuild": "tslint -c tslint.json -p tsconfig.json –fix",
"build": "tsc",
"prestart": "npm run build",
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},

Finally, change the extension of the src/index.js file from .js to .ts, the TypeScript extension, and run the start script.
npm run start

Note: You can run TSLint and the TypeScript compiler without starting the Node.js server using npm run build.

TypeScript errors
Oh no! Right away, you may see some errors logged to the console like these.
ERROR: /Users/reverentgeek/Projects/guitar-inventory/src/index.ts[12, 5]: Calls to ‘console.log’ are not allowed.

src/index.ts:1:17 – error TS2580: Cannot find name ‘require’. Do you need to install type definitions for node? Try `npm i @types/node`.

1 const express = require( "express" );
~~~~~~~

src/index.ts:6:17 – error TS7006: Parameter ‘req’ implicitly has an ‘any’ type.

6 app.get( "/", ( req, res ) => {
~~~

The two most common errors you may see are syntax errors and missing type information. TSLint considers using console.log to be an issue for production code. The best solution is to replace uses of console.log with a logging framework such as winston. For now, add the following comment to src/index.ts to disable the rule.
app.listen( port, () => {
// tslint:disable-next-line:no-console
console.log( `server started at http://localhost:${ port }` );
} );

TypeScript prefers to use the import module syntax over require, so you’ll start by changing the first line in src/index.ts from:
const express = require( "express" );

to:
import express from "express";

Getting the right types
To assist TypeScript developers, library authors and community contributors publish companion libraries called TypeScript declaration files. Declaration files are published to the DefinitelyTyped open source repository, or sometimes found in the original JavaScript library itself.
Update your project so that TypeScript can use the type declarations for Node.js and Express.
npm install –save-dev @types/node @types/express

Next, rerun the start script and verify there are no more errors.
npm run start

Build a Better User Interface with Materialize and EJS
Your Node.js application is off to a great start, but perhaps not the best looking, yet. This step adds Materialize, a modern CSS framework based on Google’s Material Design, and Embedded JavaScript Templates (EJS), an HTML template language for Express. Materialize and EJS are a good foundation for a much better UI.
First, install EJS as a dependency.
npm install ejs

Next, make a new folder under /src named views. In the /src/views folder, create a file named index.ejs. Add the following code to /src/views/index.ejs.

<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Guitar Inventory</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<div class="container">
<h1 class="header">Guitar Inventory</h1>
<a class="btn" href="/guitars"><i class="material-icons right">arrow_forward</i>Get started!</a>
</div>
</body>
</html>

Update /src/index.ts with the following code.
import express from "express";
import path from "path";
const app = express();
const port = 8080; // default port to listen

// Configure Express to use EJS
app.set( "views", path.join( __dirname, "views" ) );
app.set( "view engine", "ejs" );

// define a route handler for the default home page
app.get( "/", ( req, res ) => {
// render the index template
res.render( "index" );
} );

// start the express server
app.listen( port, () => {
// tslint:disable-next-line:no-console
console.log( `server started at http://localhost:${ port }` );
} );

Add an asset build script for Typescript
The TypeScript compiler does the work of generating the JavaScript files and copies them to the dist folder. However, it does not copy the other types of files the project needs to run, such as the EJS view templates. To accomplish this, create a build script that copies all the other files to the dist folder.
Install the needed modules and TypeScript declarations using these commands.
npm install –save-dev ts-node shelljs fs-extra nodemon rimraf npm-run-all
npm install –save-dev @types/fs-extra @types/shelljs

Here is a quick overview of the modules you just installed.

ts-node. Use to run TypeScript files directly.
shelljs. Use to execute shell commands such as to copy files and remove directories.
fs-extra. A module that extends the Node.js file system (fs) module with features such as reading and writing JSON files.
rimraf. Use to recursively remove folders.
npm-run-all. Use to execute multiple npm scripts sequentially or in parallel.
nodemon. A handy tool for running Node.js in a development environment. Nodemon watches files for changes and automatically restarts the Node.js application when changes are detected. No more stopping and restarting Node.js!

Make a new folder in the root of the project named tools. Create a file in the tools folder named copyAssets.ts. Copy the following code into this file.
import * as shell from "shelljs";

// Copy all the view templates
shell.cp( "-R", "src/views", "dist/" );

Update npm scripts
Update the scripts in package.json to the following code.
"scripts": {
"clean": "rimraf dist/*",
"copy-assets": "ts-node tools/copyAssets",
"lint": "tslint -c tslint.json -p tsconfig.json –fix",
"tsc": "tsc",
"build": "npm-run-all clean lint tsc copy-assets",
"dev:start": "npm-run-all build start",
"dev": "nodemon –watch src -e ts,ejs –exec npm run dev:start",
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},

Note: If you are not familiar with using npm scripts, they can be very powerful and useful to any Node.js project. Scripts can be chained together in several ways. One way to chain scripts together is to use the pre and post prefixes. For example, if you have one script labeled start and another labeled prestart, executing npm run start at the terminal will first run prestart, and only after it successfully finishes does start run.

Now run the application and navigate to http://localhost:8080.
npm run dev

The home page is starting to look better! Of course, the Get Started button leads to a disappointing error message. No worries! The fix for that is coming soon!
A Better Way to Manage Configuration Settings in Node.js
Node.js applications typically use environment variables for configuration. However, managing environment variables can be a chore. A popular module for managing application configuration data is dotenv.
Install dotenv as a project dependency.
npm install dotenv
npm install –save-dev @types/dotenv

Create a file named .env in the root folder of the project, and add the following code.
# Set to production when deploying to production
NODE_ENV=development

# Node.js server configuration
SERVER_PORT=8080

Note: When using a source control system such as git, do not add the .env file to source control. Each environment requires a custom .env file. It is recommended you document the values expected in the .env file in the project README or a separate .env.sample file.

Now, update src/index.ts to use dotenv to configure the application server port value.
import dotenv from "dotenv";
import express from "express";
import path from "path";

// initialize configuration
dotenv.config();

// port is now available to the Node.js runtime
// as if it were an environment variable
const port = process.env.SERVER_PORT;

const app = express();

// Configure Express to use EJS
app.set( "views", path.join( __dirname, "views" ) );
app.set( "view engine", "ejs" );

// define a route handler for the default home page
app.get( "/", ( req, res ) => {
// render the index template
res.render( "index" );
} );

// start the express server
app.listen( port, () => {
// tslint:disable-next-line:no-console
console.log( `server started at http://localhost:${ port }` );
} );

You will use the .env for much more configuration information as the project grows.
Easily Add Authentication to Node and Express
Adding user registration and login (authentication) to any application is not a trivial task. The good news is Okta makes this step very easy. To begin, create a free developer account with Okta. First, navigate to developer.okta.com and click the Create Free Account button, or click the Sign Up button.

After creating your account, click the Applications link at the top, and then click Add Application.

Next, choose a Web Application and click Next.

Enter a name for your application, such as Guitar Inventory. Verify the port number is the same as configured for your local web application. Then, click Done to finish creating the application.

Copy and paste the following code into your .env file.
# Okta configuration
OKTA_ORG_URL=https://{yourOktaDomain}
OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}

In the Okta application console, click on your new application’s General tab, and find near the bottom of the page a section titled “Client Credentials.” Copy the Client ID and Client secret values and paste them into your .env file to replace {yourClientId} and {yourClientSecret}, respectively.

Enable self-service registration
One of the great features of Okta is allowing users of your application to sign up for an account. By default, this feature is disabled, but you can easily enable it. First, click on the Users menu and select Registration.

Click on the Edit button.
Change Self-service registration to Enabled.
Click the Save button at the bottom of the form.

Secure your Node.js application
The last step to securing your Node.js application is to configure Express to use the Okta OpenId Connect (OIDC) middleware.
npm install @okta/oidc-middleware express-session
npm install –save-dev @types/express-session

Next, update your .env file to add a HOST_URL and SESSION_SECRET value. You may change the SESSION_SECRET value to any string you wish.
# Node.js server configuration
SERVER_PORT=8080
HOST_URL=http://localhost:8080
SESSION_SECRET=MySuperCoolAndAwesomeSecretForSigningSessionCookies

Create a folder under src named middleware. Add a file to the src/middleware folder named sessionAuth.ts. Add the following code to src/middleware/sessionAuth.ts.
import { ExpressOIDC } from "@okta/oidc-middleware";
import session from "express-session";

export const register = ( app: any ) => {
// Create the OIDC client
const oidc = new ExpressOIDC( {
client_id: process.env.OKTA_CLIENT_ID,
client_secret: process.env.OKTA_CLIENT_SECRET,
issuer: `${ process.env.OKTA_ORG_URL }/oauth2/default`,
redirect_uri: `${ process.env.HOST_URL }/authorization-code/callback`,
scope: "openid profile"
} );

// Configure Express to use authentication sessions
app.use( session( {
resave: true,
saveUninitialized: false,
secret: process.env.SESSION_SECRET
} ) );

// Configure Express to use the OIDC client router
app.use( oidc.router );

// add the OIDC client to the app.locals
app.locals.oidc = oidc;
};

At this point, if you are using a code editor like VS Code, you may see TypeScript complaining about the @okta/oidc-middleware module. At the time of this writing, this module does not yet have an official TypeScript declaration file. For now, create a file in the src folder named global.d.ts and add the following code.
declare module "@okta/oidc-middleware";

Refactor routes
As the application grows, you will add many more routes. It is a good idea to define all the routes in one area of the project. Make a new folder under src named routes. Add a new file to src/routes named index.ts. Then, add the following code to this new file.
import * as express from "express";

export const register = ( app: express.Application ) => {
const oidc = app.locals.oidc;

// define a route handler for the default home page
app.get( "/", ( req: any, res ) => {
res.render( "index" );
} );

// define a secure route handler for the login page that redirects to /guitars
app.get( "/login", oidc.ensureAuthenticated(), ( req, res ) => {
res.redirect( "/guitars" );
} );

// define a route to handle logout
app.get( "/logout", ( req: any, res ) => {
req.logout();
res.redirect( "/" );
} );

// define a secure route handler for the guitars page
app.get( "/guitars", oidc.ensureAuthenticated(), ( req: any, res ) => {
res.render( "guitars" );
} );
};

Next, update src/index.ts to use the sessionAuth and routes modules you created.
import dotenv from "dotenv";
import express from "express";
import path from "path";
import * as sessionAuth from "./middleware/sessionAuth";
import * as routes from "./routes";

// initialize configuration
dotenv.config();

// port is now available to the Node.js runtime
// as if it were an environment variable
const port = process.env.SERVER_PORT;

const app = express();

// Configure Express to use EJS
app.set( "views", path.join( __dirname, "views" ) );
app.set( "view engine", "ejs" );

// Configure session auth
sessionAuth.register( app );

// Configure routes
routes.register( app );

// start the express server
app.listen( port, () => {
// tslint:disable-next-line:no-console
console.log( `server started at http://localhost:${ port }` );
} );

Next, create a new file for the guitar list view template at src/views/guitars.ejs and enter the following HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Guitar Inventory</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<div class="container">
<h1 class="header">Guitar Inventory</h1>
<p>Your future list of guitars!</p>
</div>
</body>
</html>

Finally, run the application.
npm run dev

Note: To verify authentication is working as expected, open a new browser or use a private/incognito browser window.

Click the Get Started button. If everything goes well, log in with your Okta account, and Okta should automatically redirect you back to the “Guitar List” page!

Add a Navigation Menu to Your Node + Typescript App
With authentication working, you can take advantage of the user profile information returned from Okta. The OIDC middleware automatically attaches a userContext object and an isAuthenticated() function to every request. This userContext has a userinfo property that contains information that looks like the following object.
{
sub: ’00abc12defg3hij4k5l6′,
name: ‘First Last’,
locale: ‘en-US’,
preferred_username: ‘account@company.com’,
given_name: ‘First’,
family_name: ‘Last’,
zoneinfo: ‘America/Los_Angeles’,
updated_at: 1539283620
}

The first step is get the user profile object and pass it to the views as data. Update the src/routes/index.ts with the following code.
import * as express from "express";

export const register = ( app: express.Application ) => {
const oidc = app.locals.oidc;

// define a route handler for the default home page
app.get( "/", ( req: any, res ) => {
const user = req.userContext ? req.userContext.userinfo : null;
res.render( "index", { isAuthenticated: req.isAuthenticated(), user } );
} );

// define a secure route handler for the login page that redirects to /guitars
app.get( "/login", oidc.ensureAuthenticated(), ( req, res ) => {
res.redirect( "/guitars" );
} );

// define a route to handle logout
app.get( "/logout", ( req: any, res ) => {
req.logout();
res.redirect( "/" );
} );

// define a secure route handler for the guitars page
app.get( "/guitars", oidc.ensureAuthenticated(), ( req: any, res ) => {
const user = req.userContext ? req.userContext.userinfo : null;
res.render( "guitars", { isAuthenticated: req.isAuthenticated(), user } );
} );
};

Make a new folder under src/views named partials. Create a new file in this folder named nav.ejs. Add the following code to src/views/partials/nav.ejs.
<nav>
<div class="nav-wrapper">
<a href="/" class="brand-logo"><% if ( user ) { %><%= user.name %>’s <% } %>Guitar Inventory</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><a href="/guitars">My Guitars</a></li>
<% if ( isAuthenticated ) { %>
<li><a href="/logout">Logout</a></li>
<% } %>
<% if ( !isAuthenticated ) { %>
<li><a href="/login">Login</a></li>
<% } %>
</ul>
</div>
</nav>

Modify the src/views/index.ejs and src/views/guitars.ejs files. Immediately following the <body> tag, insert the following code.
<body>
<% include partials/nav %>

With these changes in place, your application now has a navigation menu at the top that changes based on the login status of the user.

Create an API with Node and PostgreSQL
The next step is to add the API to the Guitar Inventory application. However, before moving on, you need a way to store data.
Create a PostgreSQL database
This tutorial uses PostgreSQL. To make things easier, use Docker to set up an instance of PostgreSQL. If you don’t already have Docker installed, you can follow the install guide.
Once you have Docker installed, run the following command to download the latest PostgreSQL container.
docker pull postgres:latest

Now, run this command to create an instance of a PostgreSQL database server. Feel free to change the administrator password value.
docker run -d –name guitar-db -p 5432:5432 -e ‘POSTGRES_PASSWORD=p@ssw0rd42’ postgres

Note: If you already have PostgreSQL installed locally, you will need to change the -p parameter to map port 5432 to a different port that does not conflict with your existing instance of PostgreSQL.

Here is a quick explanation of the previous Docker parameters.

-d – This launches the container in daemon mode, so it runs in the background.
-name – This gives your Docker container a friendly name, which is useful for stopping and starting containers.
-p – This maps the host (your computer) port 5432 to the container’s port 5432. PostgreSQL, by default, listens for connections on TCP port 5432.
-e – This sets an environment variable in the container. In this example, the administrator password is p@ssw0rd42. You can change this value to any password you desire.
postgres – This final parameter tells Docker to use the postgres image.

Note: If you restart your computer, may need to restart the Docker container. You can do that using the docker start guitar-db command.

Install the PostgreSQL client module and type declarations using the following commands.
npm install pg pg-promise
npm install –save-dev @types/pg

Database configuration settings
Add the following settings to the end of the .env file.
# Postgres configuration
PGHOST=localhost
PGUSER=postgres
PGDATABASE=postgres
PGPASSWORD=p@ssw0rd42
PGPORT=5432

Note: If you changed the database administrator password, be sure to replace the default p@ssw0rd42 with that password in this file.
Add a database build script
You need a build script to initialize the PostgreSQL database. This script should read in a .pgsql file and execute the SQL commands against the local database.
In the tools folder, create two files: initdb.ts and initdb.pgsql. Copy and paste the following code into initdb.ts.
The post How to Use TypeScript to Build a Node API with Express appeared first on SitePoint.

Link: https://www.sitepoint.com/how-to-use-typescript-to-build-a-node-api-with-express/

Need to Node – Volume 23

This week brings a rather low amount of activity in the Node.js organization thanks to the holiday season and people coming out at the end of conference season exhausted as usual. Nevertheless, there have been a few developments in Node.js and the broader ecosystem since the last Need to Node that you should definitely be keeping an eye on. Let’s dig in.

Link: https://dzone.com/articles/need-to-node-volume-23?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

How to Create and Verify JWTs with Node

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Authentication on the internet has evolved quite a bit over the years. There are many ways to do it, but what worked well enough in the 90s doesn’t quite cut it today. In this tutorial, I’ll briefly cover some older, simpler forms of authentication, then show you how a more modern and more secure approach. By the end of this post, you’ll be able to create and verify JWTs yourself in Node. I’ll also show you how you can leverage Okta to do it all for you behind the scenes.
Traditionally, the simplest way to do authorization is with a username and password. This is called Basic Authorization and is done by just sending username:password as an encoded string that can be decoded by anybody looking. You could think of that string as a “token”. The problem is, you’re sending your password with every request. You could also send your username and password a single time, and let the server create a session ID for you. The client would then send that ID along with every request instead of a username and password. This method works as well, but it can be a hassle for the client to store and maintain sessions, especially for large sets of users.
The third method for managing authorization is via JSON Web Tokens, or JWTs. JWTs have become the de facto standard over the last few years. A JWT makes a set of claims, (e.g. “I’m Abe Froman, the Sausage King of Chicago”) that can be verified. Like Basic Authorization, the claims can be read by anybody. Unlike Basic Auth, however, you wouldn’t be sharing your password with anyone listening in. Instead, it’s all about trust.
Trust, but Verify… Your JWTs

OK, maybe don’t believe everything you read on the internet. You might be wondering how someone can just make some claims and expect the server to believe them. When you make a claim using a JWT, it’s signed off by a server that has a secret key. The server reading the key can easily verify that the claim is valid, even without knowing the secret that was used. However, it would be nearly impossible for someone to modify the claims and make sure the signature was valid without having access to that secret key.
Why Use a JWT?
Using a JWT allows a server to offload authentication to a 3rd party they trust. As long as you trust the 3rd party, you can let them ensure that the user is who they say they are. That 3rd party will then create a JWT to be passed to your server, with whatever information is necessary. Typically this includes at least the user’s user id (standardly referred to as sub for “subject”), the “issuer” (iss) of the token, and the “expiration time” (exp). There are quite a few standardized claims, but you can really put any JSON you want in a claim. Just remember the more info you include, the longer the token will be.
Build a Simple Node App
To create and verify your own JWTs, you’ll first need to set up a Node server (well, you don’t have to, but that’s what I’ll be teaching you today). To get started, run the following commands to set up a new project:
mkdir fun-with-jwts
cd fun-with-jwts
npm init -y
npm install express@4.16.4
npm install -D nodemon@1.18.6

Next, create a new file index.js that will contain a super simple node server. There are three endpoints in here, that are just stubbed with TODOs as notes for what to implement.
The /create endpoint will require basic authorization to log you in. If you were writing a real OAuth server, you would probably use something other than Basic Auth. You would also need to look up the user in a database and make sure they provided the right password. To keep things simple for the demo, I’ve just hard-coded a single username and password here, so we can focus on the JWT functionality.
The /verify endpoint takes a JWT as a parameter to be decoded.
const express = require(‘express’)
const app = express()
const port = process.env.PORT || 3000

app.get(‘/create’, (req, res) => {
if (req.headers.authorization !== ‘Basic QXp1cmVEaWFtb25kOmh1bnRlcjI=’) {
res.set(‘WWW-Authenticate’, ‘Basic realm=”401"’)
res.status(401).send(‘Try user: AzureDiamond, password: hunter2’)
return
}

res.send(‘TODO: create a JWT’)
})

app.get(‘/verify/:token’, (req, res) => {
res.send(`TODO: verify this JWT: ${req.params.token}`)
})

app.get(‘/’, (req, res) => res.send(‘TODO: use Okta for auth’))

app.listen(port, () => console.log(`JWT server listening on port ${port}!`))

You can now run the server by typing node_modules/.bin/nodemon .. This will start a server on port 3000 and will restart automatically as you make changes to your source code. You can access it by going to http://localhost:3000 in your browser. To hit the different endpoints, you’ll need to change the URL to http://localhost:3000/create or http://localhost:3000/verify/asdf. If you prefer to work in the command line, you can use curl to hit all those endpoints:
$ curl localhost:3000
TODO: use Okta for auth

$ curl localhost:3000/create
Try user: AzureDiamond, password: hunter2

$ curl AzureDiamond:hunter2@localhost:3000/create
TODO: create a JWT

$ curl localhost:3000/verify/asdf
TODO: verify this JWT: asdf

Create JSON Web Tokens in Your Node App
A JSON Web Token has three parts. The header, the payload, and the signature, separated by .s.
The header is a base64 encoded JSON object specifying which algorithm to use and the type of the token.
The payload is also a base64 encoded JSON object containing pretty much anything you want. Typically it will at least contain an expiration timestamp and some identifying information.
The signature hashes the header, the payload, and a secret key together using the algorithm specified in the header.
There are a number of tools out there to create JWTs for various languages. For Node, one simple one is njwt. To add it to your project, run
npm install njwt@0.4.0

Now replace the res.send(‘TODO: create a JWT’) line in index.js with the following:
const jwt = require(‘njwt’)
const claims = { iss: ‘fun-with-jwts’, sub: ‘AzureDiamond’ }
const token = jwt.create(claims, ‘top-secret-phrase’)
token.setExpiration(new Date().getTime() + 60*1000)
res.send(token.compact())

Feel free to mess around with the payload. With the setExpiration() function above, the token will expire in one minute, which will let you see what happens when it expires, without having to wait too long.
To test this out and get a token, log in via the /create endpoint. Again, you can go to your browser at http://localhost:3000/create, or use curl:
$ curl AzureDiamond:hunter2@localhost:3000/create
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6IndvcmxkISIsIm51bWJlciI6MC41MzgyNzE0MTk3Nzg5NDc4LCJpYXQiOjE1NDIxMDQ0NDgsImV4cCI6MTU0MjEwNDUwOCwiaXNzIjoiZnVuLXdpdGgtand0cyIsInN1YiI6IkF6dXJlRGlhbW9uZCJ9.LRVmeIzAYk5WbDoKfSTYwPx5iW0omuB76Qud-xR8We4

Verify JSON Web Tokens in Your Node App
Well, that looks a bit like gibberish. You can see there are two .s in the JWT, separating the header, payload, and signature, but it’s not human readable. The next step is to write something to decode that string into something that makes a little more legible.
Replace the line containing TODO: verify this JWT with the following:
const jwt = require(‘njwt’)
const { token } = req.params
jwt.verify(token, ‘top-secret-phrase’, (err, verifiedJwt) => {
if(err){
res.send(err.message)
}else{
res.send(verifiedJwt)
}
})

In the route /verify/:token, the :token part tells express that you want to read that section of the URL in as a param, so you can get it on req.params.token. You can then use njwt to try to verify the token. If it fails, that could mean a number of things, like the token was malformed or it has expired.
Back on your website, or in curl, create another token using http://localhost:3000/create. Then copy and paste that into the URL so you have http://localhost:3000/verify/eyJhb…R8We4. You should get something like the following:
{
"header": { "typ": "JWT", "alg": "HS256" },
"body": {
"iss": "fun-with-jwts",
"sub": "AzureDiamond",
"jti": "3668a38b-d25d-47ee-8da2-19a36d51e3da",
"iat": 1542146783,
"exp": 1542146843
}
}

If you wait a minute and try again, you’ll instead get jwt expired.
Add OIDC Middleware to Your Node App to Handle JWT Functionality
Well, that wasn’t so bad. But I sure glossed over a lot of details. That top-secret-phrase isn’t really very top secret. How do you make sure you have a secure one and it’s not easy to find? What about all the other JWT options? How do you actually store that in a browser? What’s the optimal expiration time for a token?
This is where Okta comes in to play. Rather than dealing with all this yourself, you can leverage Okta’s cloud service to handle it all for you. After a couple minutes of setup, you can stop thinking about how to make your app secure and just focus on what makes it unique.
Why Auth with Okta?
Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation

If you don’t already have one, sign up for a forever-free developer account.
Create an Okta Server
You’re going to need to save some information to use in your app. Create a new file named .env. In it, enter your Okta organization URL.
The post How to Create and Verify JWTs with Node appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/11/13/create-and-verify-jwts-with-node

Node.js vs. Django:  Is JavaScript Better Than Python?

Node.js (55, 432 ★ on GitHub) and Django (37, 614 ★ on GitHub) are two powerful tools for building web applications.
Node.js has a “JavaScript everywhere” motive to ensure JavaScript is used on the server-side and client-side of web applications and Django has a “framework for perfectionists with deadlines” motive to help developers build applications quickly.

Link: https://dzone.com/articles/nodejs-vs-djangois-javascript-better-than-python?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Build a Basic CRUD App with Angular and Node

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
In recent years, single page applications (SPAs) have become more and more popular. A SPA is a website that consists of just one page. That lone page acts as a container for a JavaScript application. The JavaScript is responsible for obtaining the content and rendering it within the container. The content is typically obtained from a web service and RESTful APIs have become the go-to choice in many situations. The part of the application making up the SPA is commonly known as the client or front-end, while the part responsible for the REST API is known as the server or back-end. In this tutorial, you will be developing a simple Angular single page app with a REST backend, based on Node and Express.
You’ll be using Angular as it follows the MVC pattern and cleanly separates the View from the Models. It is straightforward to create HTML templates that are dynamically filled with data and automatically updated whenever the data changes. I have come to love this framework because it is very powerful, has a huge community and excellent documentation.
For the server, you will be using Node with Express. Express is a framework that makes it easy to create REST APIs by allowing to define code that runs for different requests on the server. Additional services can be plugged in globally, or depending on the request. There are a number of frameworks that build on top of Express and automate the task of turning your database models into an API. This tutorial will not make use of any of these in order to keep this focused.
Angular encourages the use of TypeScript. TypeScript adds typing information to JavaScript and, in my opinion, is the future of developing large scale applications in JavaScript. For this reason, you will be developing both client and server using TypeScript.
Here are the libraries you’ll be using for the client and the server:

Angular: The framework used to build the client application
Okta for Authorisation: A plugin that manages single sign-on authorization using Okta, both on the client and the server
Angular Material: An angular plugin that provides out-of-the-box Material Design
Node: The actual server running the JavaScript code
Express: A routing library for responding to server requests and building REST APIs
TypeORM: A database ORM library for TypeScript

Start Your Basic Angular Client Application
Let’s get started by implementing a basic client using Angular. The goal is to develop a product catalog which lets you manage products, their prices, and their stock levels. At the end of this section, you will have a simple application consisting of a top bar and two views, Home and Products. The Products view will not yet have any content and nothing will be password protected. This will be covered in the following sections.
To start you will need to install Angular. I will assume that you already have Node installed on your system and you can use the npm command. Type the following command into a terminal.
npm install -g @angular/cli@7.0.2

Depending on your system, you might need to run this command using sudo because it will install the package globally. The angular-cli package provides the ng command that is used to manage Angular applications. Once installed go to a directory of your choice and create your first Angular application using the following command.
ng new MyAngularClient

Using Angular 7, this will prompt you with two queries. The first asks you if you want to include routing. Answer yes to this. The second query relates to the type of style sheets you want to use. Leave this at the default CSS.
ng new will create a new directory called MyAngularClient and populate it with an application skeleton. Let’s take a bit of time to look at some of the files that the previous command created. At the src directory of the app, you will find a file index.html that is the main page of the application. It doesn’t contain much and simply plays the role of a container. You will also see a style.css file. This contains the global style sheet that is applied throughout the application. If you browse through the folders you might notice a directory src/app containing five files.
app-routing.module.ts
app.component.css
app.component.html
app.component.ts
app.component.spec.ts
app.module.ts

These files define the main application component that will be inserted into the index.html. Here is a short description of each of the files:

app.component.css file contains the style sheets of the main app component. Styles can be defined locally for each component
app.component.html contains the HTML template of the component
app.component.ts file contains the code controlling the view
app.module.ts defines which modules your app will use
app-routing.module.ts is set up to define the routes for your application
app.component.spec.ts contains a skeleton for unit testing the app component

I will not be covering testing in this tutorial, but in real life applications, you should make use of this feature. Before you can get started, you will need to install a few more packages. These will help you to quickly create a nicely designed responsive layout. Navigate to the base directory of the client, MyAngularClient, and type the following command.
npm i @angular/material@7.0.2 @angular/cdk@7.0.2 @angular/animations@7.0.1 @angular/flex-layout@7.0.0-beta.19

The @angular/material and @angular/cdk libraries provide components based on Google’s Material Design, @angular/animations is used to provide smooth transitions, and @angular/flex-layout gives you the tools to make your design responsive.
Next, create the HTML template for the app component. Open src/app/app.component.html and replace the content with the following.

Link: https://developer.okta.com/blog/2018/10/30/basic-crud-angular-and-node

[DZone Research] Backend Web Development: Node.js and Java

This post is part of the Key Research Findings in the 2018 DZone Guide to Dynamic Web and Mobile Development. 
Introduction
For this year’s DZone Guide to Databases, we surveyed software professionals from across the IT industry. We received 1,202 responses with a 64% completion rating. Based on these numbers, we calculated the margin of error at 3%. In this article, we discuss the continued growth of Node.js in the web developer community and the most popular backend langauge, Java.

Link: https://dzone.com/articles/dzone-research-backend-development?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Need to Node – Volume 22

The past few weeks have had some interesting activity across the organization while we prepare for the release of Node.js v10 LTS while juggling security releases, dependency updates, and an upcoming Foundation-sponsored event. Check out some of what’s happened in the Node.js GitHub organization over the past week:

Link: https://dzone.com/articles/need-to-node-volume-22?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Building a Node.js Service With AWS Lambda, DynamoDB, and Serverless Framework

As a developer, my favorite new technology is serverless computing. The convenience and cost make it a compelling choice for running options in the cloud — especially for proofs-of-concept or quick ways to prove out ideas. Using serverless computing to get up and running takes very little effort and the costs of running an application in the cloud are minimal. Serverless really empowers developers to act on ideas as quickly as possible.
In this post, I’m going to briefly touch on what serverless computing is and the pros and cons of using it. Then I will build a Node.js service to do CRUD operations using AWS Lambda, DynamoDB, and the Serverless Framework. You can view the finished product on GitHub.

Link: https://dzone.com/articles/building-a-nodejs-service-with-aws-lambda-dynamodb?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

JEC: Working With jslets in Node.js

This article shows how to create web applications, a la JAVA, over Node.js by using the “JavaScript Enterprise Container" (JEC) specification and its default implementation: GlassCat application server.
Prerequisites
In order to follow this tutorial, you need to install a GlassCat server instance and deploy a basic JEC project.

Link: https://dzone.com/articles/jec-working-with-jslets-in-nodejs?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Secure a Node API with OAuth 2.0 Client Credentials

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Securing server-to-server API services can be tricky. OAuth 2.0 is an excellent way to offload user authentication to another service, but what if there is no user to authenticate? In this article, I’ll show you how you can use OAuth 2.0 outside the context of a user, in what is also known as the Client Credentials Flow.
Instead of storing and managing API keys for your clients (other servers), you can use a third-party service to manage authorization for you. The way this works is that an API client sends a request to an OAuth server asking for an API token. That token is then sent from the API client to your API service along with their request. Once you have the client’s token, you can verify its validity without needing to store any information about the client.

How the Client Credentials Flow Verification Works
One way to verify tokens you receive to your API service is to forward the token to the OAuth server to ask if it is valid. The downside to this method is each API request sent to your server requires a request sent to the OAuth server as well, which increases the time it takes for you to respond to your client. An alternative is to use something called local validation, a strategy popularized by JSON Web Tokens (JWT). A JWT contains your claims (client data) in unencrypted, machine-readable JSON.
When using the local validation pattern to validate an API token (JWT), you can use math to validate that:
The token your API is receiving hasn’t been tampered with The token your API is receiving hasn’t expired That certain pieces of JSON data encoded in the token are what you expect them to be
How is that secure? you might be wondering. JWTs contain three parts: a header, a payload, and a signature. The header and payload are simple base64 encoded strings, which can easily be decrypted and read. The signature uses an algorithm listed in the header, along with a private key, to create a hash of the header and payload. The hash can’t be recreated without the private key, but it can be verified with a public key.
In a way, this is like a driver’s license or a passport. It’s quite difficult to forge, but it’s very easy for somebody to look at it and see your name, date of birth, and other information. You can scan the barcode, test it with a black light, or look for watermarks to help verify its validity.
While similar in concept, a valid JWT would actually be far more difficult to forge. Someone with enough skill can create a convincing driver’s license, but without the private key it could take a modern computer years to brute force a valid JWT signature. Tokens should also have an expiration. While configurable, a solid default is one hour. This means a client would need to request a new token every 60 minutes if it needs to make a new request to your API server. This is an extra layer of security in case your token is compromised. Who knows? Maybe there’s a quantum computer out there that can recreate the signature within a couple hours.
Now that you understand the basics of the OAuth 2.0 client credentials flow works, let’s build a Node API that uses Client Credentials and Okta.
What is Okta?
In short, we make identity management easier, more secure, and more scalable than what you’re used to. Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications. Our API enables you to:

Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation for more information

Register for a forever-free developer account, and when you’re done, come back to learn more about building secure APIs in Node!
Create a Basic Node API
In order to get started, I’ll show you how to create a basic API in Node. Node keeps a list of dependencies along with other metadata in a file called package.json.
Assuming you have Node installed already, create a new folder for your API server. You can then use npm to generate a package.json for you. The command npm init will prompt you for some information, but you can just keep hitting Enter to stick to the defaults.
$ mkdir client-credentials-flow
$ cd client-credentials-flow
$ git init
$ npm init

The quickest way to get an API server up and running in Node is by using Express. You can add Express as a dependency with the command npm install express@4.16.3 –save. This creates a folder called node_modules where express and anything it depends on are downloaded, and your app can then use those. To make development go faster, you can also add a dev dependency called nodemon, which will restart your server whenever you make code changes. To add a dev-dependency, use the -D flag: npm install -D nodemon@1.17.5.
When building Node apps, you usually want to ignore storing the node_modules folder in your git repo. You can do that by adding node_modules to your .gitignore file.
echo node_modules >> .gitignore

Package managers will also include a file (e.g. package-lock.json or yarn.lock) so that when you download the node_modules on another machine (with npm install or yarn), the same version gets downloaded. This helps prevent any inconsistencies between servers, and keeps you from wondering why something works on your machine, but not in production. Make sure to commit that file to your git repo as well:
$ git add .
$ git commit -m “Adding package files."

You can also add scripts to your package.json folder to run these commands. Create a start script with the command node . (the . tells it to run the script listed in your package.json as main, which by default is index.js. You’ll also want to create a dev script with the command nodemon *.js node .. Command line dependencies, like nodemon, are in the path when running inside a node script. You can now run these commands with npm start or npm run dev. Your package.json file should now look something like this:
package.json
{
"name": "client-credentials-flow",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon *.js node .",
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3"
},
"devDependencies": {
"nodemon": "^1.17.5"
}
}

Now for the most basic “Hello World” express app:
index.js
const express = require(‘express’)
const app = express()

app.get(‘/’, (req, res) => res.send(‘Hello World!’))

const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}`))

That’s it! To start it, type npm run dev in a terminal window. You can leave this running while we make changes, and it will automatically restart to reflect new changes. Now go to http://localhost:3000 in your browser (or on the command line with curl http://localhost:3000) and you should see Hello World! echoed back.
Register with an OAuth 2.0 Provider for Your Node API
Now to secure the app. This is where you need to set up an OAuth 2.0 service. Okta is a cloud-based service that allows developers to easily and securely store OAuth 2.0 tokens, user accounts, and user data, then connect them with one or multiple applications. Okta also provides libraries for many languages, including Node, to make their API very easy for a developer to integrate into a huge variety of apps.
You can use Okta to quickly and easily set up server-to-server authentication. If you don’t already have an account, sign up for a free Okta Developer account. Once you register, you’ll be given a unique Okta Org URL (e.g. https://{yourOktaDomain}) and an email to activate your new account.
You’ll need two parts in order to make client-to-server authentication work: an authorization server, and a test client/application.
Create an Authorization Server
The authorization server is where clients can request a token to use on your API server. Inside the Okta dashboard, click on the API tab in the header, then select the Authorization Servers tab. Click Add Authorization Server, then give your server a useful name and description. The Audience should be an absolute path for the server that will be consuming the tokens.

Once you create the authorization server, you will need a scope for your clients to access. Click the Scopes tab and add a scope. You can have many of these, which can help define what parts of the API are being used, or even who is using it.

Now that you have a scope, you also need to specify some rules to say who has access to it. Click the Access Policies tab and create a new policy. For now, just allow access to All clients. Then click Add Rule and give it a name. Since this is only for client credentials, remove the other grant types for acting on behalf of a user (Authorization Code, Implicit, and Resource Owner Password) so the only grant type is Client Credentials. Aside from that, just use the default settings for now.

Back on the Settings tab, take note of the Issuer. This is the address clients will use to request a token, and what your API server will use to verify that those tokens are valid.
Create a Test Client
In your Okta dashboard, click on Applications in the top header. Applications are also known as clients, so this is where you can create a test client. Click Add Application and choose Service (Machine-to-Machine). The only information it needs is a name, so you can use something like Test Client. This will give you the credentials for your client (in this testing case, that would be you).

Secure your Node API
You now have all the pieces of the puzzle to make it so only authenticated users get the beloved “Hello World” welcome message, and everybody else gets an error.
Safely Store Your Credentials
You’ll want to store your credentials safely. One way of doing this is to keep a file locally that isn’t stored in git (especially useful if your code is open source, but still a good thing to do regardless). This also lets you use the same code for multiple applications (e.g. dev and production environments).
The post Secure a Node API with OAuth 2.0 Client Credentials appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/06/06/node-api-oauth-client-credentials