

{"id":114751,"date":"2023-05-20T09:00:58","date_gmt":"2023-05-20T03:30:58","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=114751"},"modified":"2023-05-20T15:18:53","modified_gmt":"2023-05-20T09:48:53","slug":"debugging-in-express-js","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/","title":{"rendered":"Debugging in Express JS"},"content":{"rendered":"<p>Debugging is an essential part of software development, and Express js is no exception. When building web applications with Express.js, it is common to encounter bugs and errors that need to be fixed. In this article, we will explore the best practices for debugging Express js applications.<\/p>\n<h3>Logging in Express JS<\/h3>\n<p>Logging is one of the most important tools for debugging Express.js applications. It allows you to see what is happening inside your application, and it can help you identify bugs and errors quickly. Express.js provides a built-in logging middleware called morgan, which logs HTTP requests and responses. You can use morgan to log requests and responses to the console, a file, or any other destination of your choice.<\/p>\n<p>To use morgan, you need to install it using npm:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install morgan\r\n<\/pre>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/morgan-install-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114938\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/morgan-install-.webp\" alt=\"morgan install\" width=\"512\" height=\"217\" \/><\/a><\/p>\n<p>Once you have installed morgan, you can use it as middleware in your Express.js application:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require('express');\r\nconst morgan = require('morgan');\r\nconst app = express();\r\n\r\napp.use(morgan('dev'));\r\n<\/pre>\n<p>In this example, we have used morgan as middleware in our Express.js application. The &#8216;dev&#8217; option tells morgan to log requests and responses to the console in a developer-friendly format.<\/p>\n<h3>Debugging middleware<\/h3>\n<p>Express.js allows you to create custom middleware that can be used for debugging purposes. Middleware functions are functions that take three arguments: req, res, and next. They can be used to modify the request and response objects, or they can be used to perform other tasks.<\/p>\n<p>To create a debugging middleware, you can define a function that logs information to the console:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function debugMiddleware(req, res, next) {\r\n  console.log('Request received:', req.method, req.url);\r\n  next();\r\n}\r\n\r\napp.use(debugMiddleware);\r\n<\/pre>\n<p>In this example, we have created a debugging middleware that logs information about the incoming request to the console.<\/p>\n<h3>Debugging with breakpoints<\/h3>\n<p>Another useful tool for debugging Express.js applications is breakpoints. Breakpoints allow you to pause the execution of your code at a specific point and inspect the values of variables and objects. You can set breakpoints in your code using a debugger, such as the one built into the Chrome Developer Tools.<\/p>\n<p>To use breakpoints with Express.js, you need to start your application in debug mode:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">node --inspect index.js\r\n<\/pre>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/debugging-breakpoint-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114939\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/05\/debugging-breakpoint-.webp\" alt=\"debugging breakpoint\" width=\"512\" height=\"308\" \/><\/a><\/p>\n<p>In this example, we have started our Express.js application in debug mode using the &#8211;inspect flag. Once your application is running in debug mode, you can open the Chrome Developer Tools and navigate to the &#8220;Sources&#8221; tab. From there, you can select your application&#8217;s source file and set breakpoints by clicking on the line numbers.<\/p>\n<h3>Error handling middleware<\/h3>\n<p>Error handling is an essential part of debugging Express.js applications. When an error occurs in your application, you need to handle it gracefully and provide feedback to the user. Express.js provides a built-in error handling middleware that can be used to handle errors in your application.<\/p>\n<p>To use the error handling middleware, you need to define a middleware function with four arguments: err, req, res, and next:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function errorHandler(err, req, res, next) {\r\n  console.error(err.stack);\r\n  res.status(500).send('Something broke!');\r\n}\r\n\r\napp.use(errorHandler);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Something broke!In this example, we have defined an error handling middleware that logs the error stack to the console and sends a 500 error response to the client.<\/p>\n<h3>Advanced options for debugging in Express JS<\/h3>\n<p>When using Node.js, you can modify the behavior of the debug logging by setting environment variables. These variables affect the underlying &#8220;debug&#8221; module used in Node.js. Here are some advanced options that you can set:<\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Name<\/b><\/td>\n<td><b>Purpose<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DEBUG<\/span><\/td>\n<td><span style=\"font-weight: 400\">Enables or disables specific debugging namespaces. This allows you to selectively show or hide debug output from different parts of your code. You can set this to a comma-separated list of namespaces to enable multiple debug outputs. For example, setting DEBUG=app:*,api:* will enable debugging for all namespaces starting with app: or api:.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DEBUG_COLORS<\/span><\/td>\n<td><span style=\"font-weight: 400\">Determines whether or not to use colors in debug output. When set to a truthy value (e.g. 1 or true), colors will be used to highlight different parts of the debug output, making it easier to read. When set to a falsy value (e.g. 0 or false), colors will be disabled.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DEBUG_DEPTH<\/span><\/td>\n<td><span style=\"font-weight: 400\">Specifies the maximum depth for object inspection. This limits the number of levels that will be printed when inspecting objects. This can be useful for debugging objects with deep nesting, as it reduces the amount of output to look through.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DEBUG_FD<\/span><\/td>\n<td><span style=\"font-weight: 400\">Specifies the file descriptor to write debug output to. By default, debug output is written to stderr. However, you can set this variable to the file descriptor of a different output stream if you want to redirect the output somewhere else.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DEBUG_SHOW_HIDDEN<\/span><\/td>\n<td><span style=\"font-weight: 400\">Shows hidden properties on inspected objects. By default, util.inspect() does not show hidden properties on objects (e.g. properties with names that start with an underscore). However, you can set this variable to a truthy value to show these hidden properties in the debug output.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Conclusion<\/h3>\n<p>Debugging is an essential part of software development, and it is particularly important when building web applications with Express.js. In this article, we have explored some best practices for debugging Express.js applications, including logging, debugging middleware, breakpoints, and error handling middleware. By following these best practices, you can save time and frustration when debugging your Express.js applications.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Debugging is an essential part of software development, and Express js is no exception. When building web applications with Express.js, it is common to encounter bugs and errors that need to be fixed. In&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114793,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27631],"tags":[27659],"class_list":["post-114751","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express-js-tutorials","tag-debugging-in-express-js"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Debugging in Express JS - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn best practices for debugging Express js applications like logging, debugging middleware, breakpoints, and error handling middleware.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Debugging in Express JS - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn best practices for debugging Express js applications like logging, debugging middleware, breakpoints, and error handling middleware.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-20T03:30:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-20T09:48:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Debugging in Express JS - DataFlair","description":"Learn best practices for debugging Express js applications like logging, debugging middleware, breakpoints, and error handling middleware.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/","og_locale":"en_US","og_type":"article","og_title":"Debugging in Express JS - DataFlair","og_description":"Learn best practices for debugging Express js applications like logging, debugging middleware, breakpoints, and error handling middleware.","og_url":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-05-20T03:30:58+00:00","article_modified_time":"2023-05-20T09:48:53+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Debugging in Express JS","datePublished":"2023-05-20T03:30:58+00:00","dateModified":"2023-05-20T09:48:53+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/"},"wordCount":844,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp","keywords":["Debugging in Express JS"],"articleSection":["Express JS Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/","url":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/","name":"Debugging in Express JS - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp","datePublished":"2023-05-20T03:30:58+00:00","dateModified":"2023-05-20T09:48:53+00:00","description":"Learn best practices for debugging Express js applications like logging, debugging middleware, breakpoints, and error handling middleware.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-debugging.webp","width":1200,"height":628,"caption":"expressjs debugging"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/debugging-in-express-js\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Express JS Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/express-js-tutorials\/"},{"@type":"ListItem","position":3,"name":"Debugging in Express JS"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114751","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=114751"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114751\/revisions"}],"predecessor-version":[{"id":115416,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114751\/revisions\/115416"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114793"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=114751"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=114751"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=114751"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}