Tips And Tricks To Make Your Node.js Web App Faster

Tips and tricks to make your node.js web app faster

Whenever we think about developing a web app, Javascript is the only language that comes to the mind. As per the stack report, Javascript is a popular programming language for web app development because it is easy to learn and works well when combined with other languages and can be used to build various apps. But with the latest trends, market competition increases and businesses are looking for the tools, technologies and  frameworks that allow them to hold a tight grip on various operating platforms with a single solution. Many organizations find Node.js a perfect solution for server-side development to meet the continuous need for apps that can run seamlessly and carefully on all platforms. But working on a Node.js project is not simple. If you may have experienced the issues regarding speed. Here we discuss some tips that are known to speed up your Node.js web application development tremendously. So, let’s see each of them one by one.

Know the amazing new features of Node.js 16 at- What’s New In Node.js 16?

Tips And Tricks To Make Your Node.js Web App Faster-

1. Limited Use Of Synchronous Functions-

Since Node.js is designed with single thread architectures and asynchronous coding is heavily used in Node.js to ensure non-blocking operational flow. With the availability of various synchronous components, it would block the applications and show down the app performance. Asynchronous coding lets you use queues to monitor workflow, allowing you to append extra tasks and add additional callbacks without blocking the main thread. While you are using the Asynchronous methods, in some cases, it is feasible to find your web page making some blocking calls. Don’t worry! This is common when you use third-party modules. So, you need to keep an eye on libraries and try to avoid them dominating synchronous calls.

2. Run In Parallel-

To deliver the HTML page for any dashboard, the node.js application needs to retrieve a lot of data for the dashboard. You need to make multiple internal API calls to fetch different data. When delivering the dashboard you may execute following hypothetical calls:

The user profile – getUserProfile().
The site list – getSiteList().
Subscriptions – getSubscriptions().
currnet site – getCurrentSite().
Notifications – getNotifications().

Basically, it needs to retrieve the data from user browsing session to verify they’re logged in and it needs to pull in data about the user and site for the dashboard. So as to retrieve this data, app needed to make some calls to internal API functions. Some of them could take up to 2 seconds to complete. Every request was made by a separate express middleware, means they were running in series. Each request would wait for previous one to complete before starting.

As node.js is well suited to run multiple asynchronous functions in parallel, and various internal API requests didn’t depend on each other, here come the parallelism- fire off all requests at once and then continue once all they’ve completed. 

You can do something like this:

function runInParallel() { 
async.parallel([
getUserProfile,
getSiteList,
getSubscription,
getCurrentSite,
getNotifications
], function(err, results) {
  //This callback runs when all functions complete });
}

3. Use Caching-

If you are fetching data that doesn’t change frequently, you may cache itto improve performance. For instance, following snippet fetched the latest posts to display on a view:

var router = express.Router();
router.route('/latestPosts').get(function(req, res) {
  Post.getLatest(function(err, posts) {
    if (err) {
      throw err;
    }
    res.render('posts', { posts: posts });
  });
});

If you don’t publish blog posts frequently, you can cache the posts array and clear the cache after interval. For instance, you can use redis module to do this. For that, you need to have Redis installed   on your server. Then you can use a client called node_redis to store key/value pairs. This snippet shows how we can cache the posts:

var redis = require('redis'),
    client = redis.createClient(null, null, { detect_buffers: true }),
    router = express.Router();
router.route('/latestPosts').get(function(req,res){
  client.get('posts', function (err, posts) {
    if (posts) {
      return res.render('posts', { posts: JSON.parse(posts) });
    }
    Post.getLatest(function(err, posts) {
      if (err) {
        throw err;
      }
      client.set('posts', JSON.stringify(posts));    
      res.render('posts', { posts: posts });
    });
  });
});

Thus, first of all we check if the posts exist in the Redis cache. If so, we deliver the posts array from cache. Otherwise, we retrieve the content from DB and then cache it. And after an interval we can clear the Redis cache so as to fetch the new cache.

4. Use GZip Compression-

Enabling the gzip compression can hugely impact the performance of web apps. When a gzip compatible browser requests for some resource, the server can compress the response before sending it to the browser. If you don’t use gzip for compressing static resources it may take more time to fetch for the browser. In Express app, you can use built-in express.static() middleware to provide the static content. Also, you can use middleware compression and provide the static content. Here, is a code snippet that shows how to do it:

var compression = require(‘compression’);
app.use(compression()); //use compression
app.use(express.static(path.join(_dirname, ‘public’)));

5. Make Use Of Client Side Rendering When Possible-

Because of the client-side MVC/MVVM frameworks like Ember, Meteor, and AngularJS eases the creation of single page applications. Rather than, rendering on the server side you will only expose APIs that send JSON responses to the client. On the client side, you can use a framework to consume the JSON and display on the UI. Sending JSON from server can save bandwidth and so improve speed because you don’t send layout markup with every request. Instead you just send simple JSON that is then rendered on the client side.

6. Use Standard V8 Functions-

Various operations on collections like reduce, map and forEach are not supported by all browsers. To solve the browser compatibility issues you can use some client side libraries on the front end. With Node.js you can use built-in functions for manipulating collections on server side.

7. Use nginx In Front Of Node-

Nginx is a lightweight server used to reduce load on your Node.js server. Rather than serving static files from Node, you can configure nginx to provide static content. You can also set up nginx to compress the response using gzip so that the response size is small. Hence if you’re running a production app you may need to use nginx to improve the speed. 

8. Minify And Concatenate JavaScript-

Your web app speed can be improved by minifying and concatenating various JS files into one. When the browser encounters a <script> element the page rendering is blocked until the script is fetched and executed. For instance, if a page includes six Javascript files, the browser will make six separate HTTP requests to fetch those. Performance can be improved to great extent by minifying and concatenating those six files into one. Similar applicable to CSS files also. You can use a build tool such as Gulp/Grunt to minify and concatenate asset files.

9. Optimize Queries-

Consider that you have a blogging app that shows the latest posts on the home page. You may write something like this to fetch data using Mongoose:

Post.find().limit(10).exec(function(err, posts) {
  //send posts to client
});

But, the issue is find() function in Mongoose fetches all fields of object and there might be some fields in the Post object that are not needed on the homepage. For example, comments field holds a comments array for a specific post. If you’re not showing the comments, you can exclude it while fetching. And this will improve the speed. We can optimize the above query with-

Post.find().limit(10).exclude('comments').exec(function(err, posts) {
  //send posts to client
});

10. Don’t Store Too Much In Sessions-

In an Express web app, the session data is stored in memory. When you store huge amounts of data in the session, it adds significant overhead to the server. Hence, you can switch to some other type of storage to keep session data or try to reduce the amount of data stored in session. For instance, when users log into an app, you can store their id in the session rather than storing the entire object. Consequently, on each request you can recover the object from the id. You may also need to use MongoDB or Redis to store session data.

Wrap Up-

Most of the web development companies and freelancers uses Node.js to build great web apps. Knowing the above tips and tricks will help you to improve the performance of Node.js web app. There can be some other tips too. If you are also thinking develop web app with Node.js, then you must know these tips. You can hire Node.js developers of Solace team for effective web app development. Connect with Solace and get a free quote for web app development. We will be happy to help you.

Related Post