Categories
Node.js Basics

Node.js Basics — Getting Started

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Installation

We can install the latest Node.js version at https://nodejs.org/en/download/

This lets us download binaries for Windows and macOS.

If we’re using Linux, then we can run:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_14.x | bash -
apt-get install -y nodejs

to install Node.js 14.x.

Then we can create a file called example.js and write:

console.log("Hello world")

If we run node example.js , we should see ‘Hello world’ displayed.

Requiring Packages

Node.js comes with its own module system.

It uses the CommonJS module system which lets us import modules.

Modules are just JavaScript files that export something so other modules can use the exported items.

For example, to create and use modules, we can write:

index.js

const util = require("./utils");
util.logger.log("cool");

utils/index.js

const Logger = require("./logger");
exports.logger = new Logger();

utils/logger.js

class Logger{
  log(...args) {
    console.log(args);
  };
}
module.exports = Logger;

In the utils folder, we have 2 modules, which are index.js and logger.js

logger.js exports the Logger class by setting the class as the value of the module.exports property.

Then in utils/index.js , we called require with the relative path to the logger.js file to import the Logger class.

We export the logger by creating the exports.logger property and then assigning the Logger instance to it.

Then in index.js , we call require to import utils/index.js by writing:

const util = require("./utils");

If the file we require is called index.js , then we don’t need to include the file name.

Also, we don’t need to include the file extension for JavaScript modules.

Then to call the log method, we run:

util.logger.log("This is pretty cool");

We access exports.logger by using the utils.logger property.

Now we should see 'cool' displayed on the screen.

NPM

NPM is the most popular package manager for JavaScript apps.

To download packages with it, we can run the npm install command.

For example, if we want to install the chalk package so that we can see colored text on our console, we run npm install chalk .

Then we can use the package by writing:

const chalk = require("chalk");
console.log("I am just normal text")
console.log(chalk.green( "I am green text" ))

We call chalk.green by calling the chalk.green method from the chalk package.

The module will be installed into the node_modules folder of your project folder.

When we require it, it’ll automatically be picked up by Node.js from that folder.

Then package.json and package-lock.json file will be created when we install the packages.

If they aren’t there, we can run:

npm init

to add those files.

We’ll be asked some questions like the project name and other project data.

Conclusion

We can create Node.js apps by creating modules or using third party modules and use them in our own modules.

Categories
Node.js Basics

Node.js Basics — Add Authentication to an Express App with Passport

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Authentication

In the real world, many HTTP requests can only be made when the user is authenticated.

We can do this easily in a Node.js app.

To make our lives easier, we use the Express web framework to create our HTTP server instead of using the built-in http module.

We also need passport and passport-local to let us add authentication and the body-parser package to parse request bodies.

To install all the packages, we run:

npm install express body-parser passport passport-local

Then we can write the following code to add authentication with passport :

const express = require('express');
const bodyParser = require('body-parser');
const Passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const users = {
  foo: {
    username: 'foo',
    password: 'bar',
    id: 1
  },
  bar: {
    username: 'bar',
    password: 'foo',
    id: 2
  }
}

const localStrategy = new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password'
  },
  function(username, password, done) {
    user = users[username];
    if (user === undefined) {
      return done(null, false, {
        message: 'Invalid user'
      });
    }
    if (user.password !== password) {
      return done(null, false, {
        message: 'Invalid password'
      });
    }
    done(null, user);
  })

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static('public'));
app.use(Passport.initialize());
Passport.use('local', localStrategy);

app.get('/', (req, res) => {
  res.sendFile('public/index.html');
});

app.post(
  '/login',
  Passport.authenticate('local', {
    session: false
  }),
  function(request, response) {
    response.send('User Id ' + request.user.id);
  }
);

app.listen(3000, () => console.log('server started'));

We require the passport and passport-local packages.

Then we use the LocalStrategy constructor to create our authentication mechanism.

The userField and passwordField are set to the properties of the objects in the users object so that we can get the properties for the username and password.

Then in the function we passed into the 2nd argument of LocalStrategy , we check the user and check the password.

The done fucntion is called to let us return the response message we want depending on the validity of the username or password.

The last done call is run when both the username and password are valid.

Then we call Passport.use to create the 'local' authentication strategy so that we can use the code above with the Passport.authenticate function.

Then we can get the data for the authenticated user with the request.user property.

The data is obtained from calling:

done(null, user);

Now when we make a POST request to the /login route with the request body:

{
    "username": "foo",
    "password": "bar"
}

Then we get:

User Id 1

returned from the server.

If we have a username and password combination that isn’t in the users object, then we get an Unauthorized response body and a 401 status code.

Conclusion

To make adding authentication to our code easier, we can use Passport to let us add the middleware to add basic authentication easier.