Error Handling In Express: Node.js

User inputs are very unpredictable on the web. So error handling becomes very important while building any real-time web application.

error-handling-in-express-nodejs

Express facilitates very good support for error handling, with its connect middleware.

Page Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res){
res.send(404, "Not found :-(");
});
 
app.get('/', function(req, res){
res.send("Homepage!");
});

When the user visits root of the website ( / ), a message called “Homepage!” is displayed to the user. But what if he tries to access a URL route which is not defined Ex: /user It displays Cannot GET /users message. We can set up a separate middleware to deal with situations like this. When we encounter a URL which doesn’t have a custom route definition, it’ll look for the file in the public directory, if the file is not found, it’ll look through our final middleware and executes whatever is present inside it.

User Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
app.use(function(err, req, res, next){
res.send(404, err.message);
next();
});
 
app.get('/user/:username', function(req, res, next){
if(req.params.username === 'kiran')
{
var err = new Error('User Not Found');
next(err);
}
res.send(req.params.username);
});

In real world application, we need to validate the user request before trying to serve them data. Here, if the user requests /user/kiran we’ll let the user know that the user kiran is not present in our database. So we setup a custom error handling middleware for situations like this. Here we create an error object and set a message, and pass this error object as parameter to next. call to next passes the control to the middleware which matches its signature, and executes whatever is present inside the middleware. [ Note the presence of err object inside the middleware callback method. ]

Error Handling In Express: Node.js


[youtube https://www.youtube.com/watch?v=noBowQTXSS4]

YouTube Link: https://www.youtube.com/watch?v=noBowQTXSS4 [Watch the Video In Full Screen.]



Note: Error handling can significantly increase the performance of your web application, due to the fact that your application need not figure out what to do next, in case of an error. You explicitly write error handling code for most common situations and the application behaves in a predictable manner.

Call to next() passes the execution control to the next level.

Sessions In Express: Node.js

After learning about cookies, lets look briefly about sessions in Express applications.

sessions-express-nodejs

If you’ve ever worked on any serious web application, you already know the importance of session. Creating session for logged in users, tracking the shopping cart items, storing the URL for redirect etc are some of the basic uses of sessions.

session middleware in Express: Node.js
app.js

1
2
3
4
5
6
var express = require('express');
 
var app = express();
 
app.use(express.cookieParser());
app.use(express.session({secret: 'some secret key'}));

session middleware needs cookieParser() because session objects lookup for the cookie for matching up the requests.

setting session variable in Express: Node.js
app.js

1
2
3
4
app.get('/user/:user', function(req, res){
req.session.name = req.params.user;
res.send('<p>Session Set: <a href="/user">View Here</a></p>');
});

session is present inside request object. So assign the string or the value to req.session.sessionName

Fetching session value in Express: Node.js
app.js

1
2
3
4
5
6
app.get('/user', function(req, res){
if(req.session.name)
 res.send(req.session.name+'<br /><a href="/logout">Logout</a>');
else
 res.send('user logged out!');
});

Here we check if the req.session.name has been set. If set, we show link to logout and also show current value present in the session variable. If the user is coming from /logout page, then we show “user logged out!” message.

destroy session value in Express: Node.js
app.js

1
2
3
4
app.get('/logout', function(req, res){
req.session.destroy();
res.send('<br />logged out!<br /><a href="/user">Check Session</a>');
});

Once the user clicks on /logout we destroy all the session by using req.session.destroy() We also give link to /user page, to check the fact that the session has already been destroyed.

Sessions In Express: Node.js


[youtube https://www.youtube.com/watch?v=vmDCakoxdwY]

YouTube Link: https://www.youtube.com/watch?v=vmDCakoxdwY [Watch the Video In Full Screen.]



Note: Make sure to have good session secret key – a combination of alphanumeric plus special characters. And make sure not to reveal it to anyone. Because, using this secret key / hash, someone with bad intention could possibly revoke the session and use your application as an authentic user, if care is not taken!

The main difference with cookie and a session is – session is stored on the server side and cookie on the client side.

Cookies In Express: Node.js

Cookies are one of the important recipe for building an effective web application.

cookies-express-nodejs

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website you are surfing and stored in a user/client computer. Every time the user loads that website again, the browser sends this cookie back to the server to notify the website of the user’s previous activity.

This way, using cookie, we could track user activities like her navigational behaviors, previous purchases on our site or previous leads etc.

Setting Cookie in Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
var express = require('express');
 
var app = express();
app.use(express.cookieParser());
 
app.get('/user/:user', function(req, res){
res.cookie('username', req.params.user)
    .send('<p>Cookie Set: <a href="/user">View Here</a>');
});
</p>

Using express’s cookieParser() middleware we can enable working with cookies.
Once the user navigates to /user/someUserName URL, the cookie is set with the name username and the value is actually fetched out of the request object’s params.

General Syntax for setting Cookie

res.cookie('cookieName', value, {expires: new Date() + 99999, maxAge: 99999});

Set a name to the cookie, give it some value. Also you can set the optional settings like, expiration date or the maxAge the cookie will be alive on the client computer.

Accessing Cookie in Express: Node.js
app.js

1
2
3
app.get('/user', function(req, res){
res.send(req.cookies.username);
});

Once the user visits /user route, we fetch the value present in the req.cookies.username and display it to the user.

Cookie In Express: Node.js


[youtube https://www.youtube.com/watch?v=mdvQ74KL-fU]

YouTube Link: https://www.youtube.com/watch?v=mdvQ74KL-fU [Watch the Video In Full Screen.]



Note: We could see the value stored in a cookie, by using chrome’s console window and typing document.cookie

Clearning Cookie in Express: Node.js
app.js

1
2
3
4
app.get('/user', function(req, res){
res.clearCookie('username')
           .send(req.cookies.username);
});

You could remove a cookie by using clearCookie method of response object.

Once the cookie has been removed, you can set it again explicitly using Chromes console window.
Type: document.cookie = “username = Microsoft”
now refresh the browser, and you’ll see Microsoft being displayed!

Middleware In Express: Node.js

We’ve been using middlewares in our previous video tutorials. Today, we’ll have a look at these middlewares.

middleware-connect-express-nodejs

Connect is a middleware framework of Node.js

But since connect is one of the dependencies of Express, we need not install it separately. If we have installed Express, then we already have connect.

Middeware in Express: Node.js
app.js

1
2
3
4
5
6
7
8
var express = require('express');
var app = express();
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.cookieParser());
 app.use(express.session({secret: "some secret key"}));
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

express.bodyParser extensible request body parser
express.methodOverride faux HTTP method support
express.cookieParser cookie parser
express.session session management support with bundled MemoryStore
express.static streaming static file server supporting Range and more
express.directory directory listing middleware

Middleware In Express: Node.js


[youtube https://www.youtube.com/watch?v=c4ScybD2690]

YouTube Link: https://www.youtube.com/watch?v=c4ScybD2690 [Watch the Video In Full Screen.]



For list of all supported middleware, visit senchalabs
Also check the list of all the 3rd-party middleware supported by Connect.

Note: Ordering of these middleware is very important.
For Example:
1. You can only override method after you’ve parsed the body, so methodOverride() must come only after bodyParser()
2. Similarly, session middleware depends on cookieParser(), so session middleware must come only after cookieParser()

As your application becomes popular you’ll need middlewares to handle csrf( Cross-site request forgery ), DDos attacks etc. Also it’s very important to validate the user requests before you allow the user request to fetch the data from your database. Learn to use middleware properly, and I’m sure, it’ll be a life-saver for your application.

Advanced Routing Using Express: Node.js

After learning basics of routing, lets look at some of the advances/complex routing techniques of Express.

routes node server request response technotip Basic Routing Using Express: Node.js

In this video tutorial, we shall teach you how to work with multiple params and also defining routes with regular expressions.

Two params in a Route: Express
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var companies = [
   {
      "name": "Apple",
      "product": "iPhone"
   },
   {
      "name": "Google",
      "product": "Nexus"
   },
   {
      "name": "Oracle",
      "product": "sql"
   },
   {
      "name": "Microsoft",
      "product": "Windows"
   }
 ];
 
app.get('/user/:from-:to', function(req, res){
    var from = parseInt(req.params.from, 10),
        to   = parseInt(req.params.to,   10);
 
  res.json( companies.slice(from, to+1) );
});

Here we have an array of objects – which in real-time application we get from a database ( Ex: MongoDB ). Now we define a route, and get two params in a single URL. By fetching and parsing those two params, we pass it to slice method of array and get array objects within the range/limit. Also note the use of response in json formatting while sending the data using response object.

Regular Expressions in Routes: Express
app.js

1
2
3
4
5
6
7
8
9
app.get(/\/user\/(\d*)\/?(edit)?/, function(req, res){
 
if(req.params[0])
 res.send("Viewing user id: "+req.params[0]); 
else if(req.params[1])
 res.send("editing user with an id "+req.params[0]);
else
 res.send("Enter User ID!!");
});

we enter our regular expression between two forward slashes. And to escape the forward slash present inside our regular expression, we make use of escape character i.e., a back slash. After /user/ we can have zero or more digits, after that an optional edit keyword followed by an optional trailing forward slash.

These routes match our pattern:
/user/
/user/userId/
/user/userId/edit
/user/userId/edit/

Depending on which URL the user is requesting, we could serve the purpose, using conditionals.

Advanced Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=jYqhlVYnr30]

YouTube Link: https://www.youtube.com/watch?v=jYqhlVYnr30 [Watch the Video In Full Screen.]



Note: In our example we are simply displaying the view and edit modes. But in real-time applications you could replace it with some database queries and make sure the operations makes proper sense.