Build and Authenticate a NodeJS App With JSON Web Tokens: Part I
Build and Authenticate a NodeJS App With JSON Web Tokens: Part I
Today, we will build an entire application with NodeJS, starting with a blank canvas and finishing with a fully functional application with multiple routes, authentication, and even remote data access.
Join the DZone community and get the full member experience.Join For Free
Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.
In our tutorial today, we will write a complete NodeJS application using one of the most popular web frameworks for Node, Express.js. We'll cover everything from project setup to routing, calling external API's, and more. Before we dive into the code let's understand why NodeJS is so popular and widely used to give you a deeper understand of why you may want to use NodeJS for your applications.
The Rise of NodeJS
Node Package Manager
The Node Package Manager or npm is one of the biggest reasons for Node's popularity. NPM allowed developers to easily manage all of the wonderful libraries released by the open source community. Developers could simply type a command like
npm install lodash, and the Node Package Manager would go out and download the latest version of lodash into a special
node_modules directory and then the developer could access the lodash library by just requiring it in their code.
NPM was revolutionary and to this day remains one of the best package managers around. It was not the first package manager: NuGet exists for the .Net platform, pip for Python, gems for Ruby, and so on, but the simplicity of NPM has had a major role in Node's success.
NodeJS is not limited to building web applications. With Electron, for example, you can build native desktop applications with Node; we even have a tutorial on how to here. Utilities and build systems are very popular candidates with NodeJS, Bower is a popular front-end package manager built with Node, while Gulp, Grunt, and WebPack are task runners and build systems built with Node that can improve workflows and increase developer efficiency.
Due to the small footprint and low resource requirements for running NodeJS applications, NodeJS is leading the charge in serverless computing with platforms like Webtask, AWS Lambda, and Google Cloud Functions all supporting NodeJS almost exclusively.
Is NodeJS For Me?
The age-old debate and probably most difficult question to answer. It depends. This may seem like a cop-out answer, but it really depends. Here at Auth0, we use NodeJS extensively and it's proven its worth in helping us scale. Check out our Stories from the Trenches blog for more in-depth coverage on how we make use of various technologies throughout our organization.
NodeJS is great for many use cases, but not so good in others. If you need high I/O that doesn't require a lot of computation, such as serving assets or webpages, then Node will keep you satisfied. If you are doing complex operations, such as hashing passwords or running simulations, NodeJS will likely underperform. Examine your use case carefully and use the right tool for the job.
Building an Application with NodeJS
Now that we know more about NodeJS, we are ready to get coding and building our application. The application we'll be building today is called Awesome Polls. The United States just had its presidential elections and we are going to build an app to help us analyse the results. Imagine you're building this app for a news organization that wishes to have the most up to date data so that it can provide accurate reports to it's viewers.
Installing NodeJS and NPM
To install NodeJS head over to the official website located at https://nodejs.org and you'll see a giant green download button for your operating system. In our tutorial today, we'll be running the 6.x LTS version of Node. Simply download the executable, run it, and go through the steps to install NodeJS on your system.
If you are on a Mac, you can also install NodeJS and NPM via Homebrew. Simply run
homebrew install node from your terminal and in seconds Node and NPM will be installed.
We will want to ensure that both NPM and Node are installed. Once you've gone through the installation steps, either manually or via homebrew, we'll confirm that the installation was successful. To do that, close and re-open your terminal window and run the command
node -v. This command will let you know the current version of Node installed. Next, run
npm -v, and likewise you should see the version of the Node Package Manager installed on your system.
Note: Node.js has two versions. A 6.x stable/long-term support version and 7.x which is the cutting edge version, that supports some of the latest ES6 features. Both versions are production-ready, and for this tutorial we'll be using the 6.x version of Node.
NodeJS Project Setup
Now that we have Node and NPM installed, we are ready to continue. One of the best things about Node applications, for me personally, is the ability to have your application live anywhere in the file system. Each Node application is self-contained, so to set up our project, let's just create a directory on our desktop called
awesome-polls and we'll place our entire application in this directory.
The first file we'll add to this project is a
package.json file. This file will keep track of all of our dependencies as well as provide some useful info about our application. You can either manually create this file, or run the command
npm init and walk through the step-by-step process. Remember to navigate to the
awesome-polls directory in your terminal first, otherwise your
package.json file will be created elsewhere.
Now that we have our
package.json file, we can add and save our dependencies. There are multiple ways to do this. We could manually write our dependencies in the
package.json file, for example, but the preferred way is to actually run the
npm install command and pass the
--save flag which will automatically add the dependency to your
npm install express --save. In just a few seconds, Express will be downloaded and stored in a new directory in your file system called
node_modules. This directory will be located in your
awesome-polls directory and is a local dependency. You can also install global dependencies by passing a
-g flag, but you probably won't want to do this for the majority of libraries you install. Utilities such as Webpack, you'd install globally.
You can also install multiple dependencies at once. Let's install the rest of our dependencies. Write the following:
npm install body-parser connect-ensure-login cookie-parser debug dotenv express-session jade morgan passport passport-auth0 --save
These are all of the 3rd party open source libraries we will rely on to write our application. It's ok if you don't understand what many of these mean or do just yet, we'll get there. To close out this section, take a look at your
package.json file and you'll see that there is a new section now called
dependencies with the libraries we've included.
NodeJS Directory Structure
NodeJS and Express.js are both pretty unopinionated when it comes to directory structure. You are free to define your own and won't be penalized for having too many or too few layers of abstraction. At the end of the day, the code is compiled and code structure flattened, so feel free to experiment with what works best for you. This will also depend a lot on the size and scope of your application. Our demo app is fairly small so our structure will look like:
.env - // We will store our global environmental variables here package.json - // We will define our apps external dependencies here app.js - // This file will be our entry point into the application |- node_modules - // automatically generated, npm will store our external dependencies here |- public |- stylesheets |- style.css - // We'll store our global styles here |- routes |- index.js - // In this file we'll define our routes for the application |- views - // We'll place all of our UI views here |- error.jade - // Our view for the error |- index.jade - // Our main homepage view ...
Our directory structure is fairly simple. We'll build our app in an MVC style fashion. Our
views directory will hold all of our front-end views, while the
routes directory will handle the traditional controller logic. We won't have any models for this simple application. Again, it's ok if some of these files don't make sense just yet. I'll explain them all in detail shortly.
Published at DZone with permission of Ado Kukic , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.