DEV Community

loading...
Cover image for Tips And Tricks To Make Your Node.js Web App Faster

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

Solace Infotech Pvt. Ltd.
Solace Infotech delivers high-end IT solutions to businesses. We offer best class web solutions for your business that encourages you to prevail in your endeavors.
・4 min read

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’)));

Know more at- [https://solaceinfotech.com/blog/tips-and-tricks-to-make-your-node-js-web-app-faster/]

Discussion (0)