<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by bhavik prajapati on Medium]]></title>
        <description><![CDATA[Stories by bhavik prajapati on Medium]]></description>
        <link>https://medium.com/@bjprajapati?source=rss-3f40a54c3bc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZTf6v_OpOxkLXGPQ</url>
            <title>Stories by bhavik prajapati on Medium</title>
            <link>https://medium.com/@bjprajapati?source=rss-3f40a54c3bc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:37:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bjprajapati/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Winston for Logging in Node.js Applications]]></title>
            <link>https://bjprajapati.medium.com/using-winston-for-logging-in-node-js-applications-d15302947c28?source=rss-3f40a54c3bc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d15302947c28</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[bhavik prajapati]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 13:53:40 GMT</pubDate>
            <atom:updated>2024-06-22T13:53:40.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is a critical part of any application. It helps with debugging, monitoring, and maintaining your code. Winston is one of the most popular logging libraries for Node.js due to its flexibility and feature-rich capabilities. In this article, we will explore how to integrate Winston into your Node.js applications and make the most out of its features.</p><figure><img alt="Node.js Logging with Winston" src="https://cdn-images-1.medium.com/max/1024/1*UvDpt-weg_AK69bp5ltPFA.png" /><figcaption>Node.js Logging with Winston</figcaption></figure><h3>Overview:</h3><p>In this tutorial, we’ll cover:</p><ol><li>Setting up Winston in a Node.js project.</li><li>Configuring different logging levels.</li><li>Creating custom log formats.</li><li>Logging to multiple transports (console, file, etc.).</li><li>Creating custom log levels.</li><li>Logging to daily log files.</li><li>Using Winston in an Express application.</li></ol><h3>Prerequisites:</h3><ul><li>Basic knowledge of JavaScript and Node.js.</li><li>Familiarity with npm and Express (optional but recommended for the final step).</li></ul><h3>Setup:</h3><p><strong>Initialize a Node.js Project:</strong></p><pre><br>mkdir winston-logger-example<br>cd winston-logger-example<br>npm init -y</pre><p><strong>Install Winston:</strong></p><pre>npm install express winston winston-daily-rotate-file</pre><h3>Basic Setup:</h3><p>Create a logger.js file for setting up Winston:</p><pre>// logger.js<br><br>const { createLogger, format, transports } = require(&#39;winston&#39;);<br><br>const logger = createLogger({<br>  level: &#39;info&#39;,<br>  format: format.combine(<br>    format.colorize(),<br>    format.timestamp(),<br>    format.printf(({ timestamp, level, message }) =&gt; `${timestamp} ${level}: ${message}`)<br>  ),<br>  transports: [<br>    new transports.Console(),<br>    new transports.File({ filename: &#39;app.log&#39; })<br>  ]<br>});<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>createLogger:</strong> Initializes a new logger instance.</li><li><strong>format.combine:</strong> Combines multiple formats, here we are using colorize, timestamp, and printf.</li><li><strong>transports:</strong> Specifies where the logs should be sent. In this example, we log to the console and a file (app.log).</li></ul><h3>Configuring Logging Levels:</h3><p>Winston supports several logging levels, such as error, warn, info, http, verbose, debug, and silly. You can configure the minimum level of logs to capture.</p><pre>// logger.js<br><br>const { createLogger, format, transports } = require(&#39;winston&#39;);<br><br>const logger = createLogger({<br>  levels: {<br>    error: 0,<br>    warn: 1,<br>    info: 2,<br>    http: 3,<br>    verbose: 4,<br>    debug: 5,<br>    silly: 6<br>  },<br>  level: &#39;info&#39;, // Set the default log level<br>  format: format.combine(<br>    format.colorize(),<br>    format.timestamp(),<br>    format.printf(({ timestamp, level, message }) =&gt; `${timestamp} ${level}: ${message}`)<br>  ),<br>  transports: [<br>    new transports.Console(),<br>    new transports.File({ filename: &#39;app.log&#39; })<br>  ]<br>});<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>levels:</strong> Define custom logging levels.</li><li><strong>level:</strong> Set the minimum level of logs to capture (here it’s set to info).</li></ul><h3>Understanding Log Levels:</h3><p>Log levels determine the severity of the messages being logged. Winston uses npm-style logging levels, which are prioritized from most severe to least severe:</p><ul><li><strong>error:</strong> (0) For logging errors that might need immediate attention.</li><li><strong>warn:</strong> (1) For logging warnings that indicate potential issues.</li><li><strong>info:</strong> (2) For logging informational messages that highlight the progress of the application.</li><li><strong>http:</strong> (3) For logging HTTP requests.</li><li><strong>verbose:</strong> (4) For logging detailed information useful during debugging.</li><li><strong>debug:</strong> (5) For logging debugging information.</li><li><strong>silly:</strong> (6) For logging the most detailed information, often more than needed.</li></ul><p>The minimum log level can be set to filter out less severe messages. For example, if the log level is set to info, only info, warn, and error messages will be logged.</p><h3>Creating Custom Log Formats:</h3><p>You can create custom log formats to suit your needs. For example, you can add metadata or change the log message structure.</p><pre>// logger.js<br><br>const { createLogger, format, transports } = require(&#39;winston&#39;);<br><br>const customFormat = format.combine(<br>  format.colorize(),<br>  format.timestamp(),<br>  format.printf(({ timestamp, level, message, ...meta }) =&gt; {<br>    return `${timestamp} ${level}: ${message} ${Object.keys(meta).length ? JSON.stringify(meta, null, 2) : &#39;&#39;}`;<br>  })<br>);<br><br>const logger = createLogger({<br>  level: &#39;info&#39;,<br>  format: customFormat,<br>  transports: [<br>    new transports.Console(),<br>    new transports.File({ filename: &#39;app.log&#39; })<br>  ]<br>});<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>customFormat:</strong> Combines timestamp, log level, message, and optional metadata into a structured log format.</li></ul><h3>Logging to Multiple Transports:</h3><p>Winston can log to multiple destinations, such as different files, external logging services, or the console.</p><pre>// logger.js<br><br>const { createLogger, format, transports } = require(&#39;winston&#39;);<br><br>const logger = createLogger({<br>  level: &#39;info&#39;,<br>  format: format.combine(<br>    format.timestamp(),<br>    format.printf(({ timestamp, level, message }) =&gt; `${timestamp} ${level}: ${message}`)<br>  ),<br>  transports: [<br>    new transports.Console(),<br>    new transports.File({ filename: &#39;app.log&#39; }),<br>    new transports.File({ filename: &#39;error.log&#39;, level: &#39;error&#39; })<br>  ]<br>});<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>transports.File({ filename: ‘error.log’, level: ‘error’ }):</strong> Logs error messages to a separate file.</li></ul><h3>Creating Custom Log Levels:</h3><p>You can define your own custom log levels in Winston. This is useful if you have specific needs that aren’t covered by the default levels.</p><pre>// logger.js<br><br>const { createLogger, format, transports, config } = require(&#39;winston&#39;);<br><br>const customLevels = {<br>  levels: {<br>    critical: 0,<br>    error: 1,<br>    warn: 2,<br>    info: 3,<br>    debug: 4<br>  },<br>  colors: {<br>    critical: &#39;red&#39;,<br>    error: &#39;red&#39;,<br>    warn: &#39;yellow&#39;,<br>    info: &#39;green&#39;,<br>    debug: &#39;blue&#39;<br>  }<br>};<br><br>const logger = createLogger({<br>  levels: customLevels.levels,<br>  level: &#39;info&#39;, // Set the default log level<br>  format: format.combine(<br>    format.colorize({ all: true }),<br>    format.timestamp(),<br>    format.printf(({ timestamp, level, message }) =&gt; `${timestamp} ${level}: ${message}`)<br>  ),<br>  transports: [<br>    new transports.Console(),<br>    new transports.File({ filename: &#39;app.log&#39; })<br>  ]<br>});<br><br>winston.addColors(customLevels.colors);<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>customLevels:</strong> Define custom logging levels and their corresponding colors.</li><li><strong>winston.addColors:</strong> Apply custom colors to the logging levels.</li></ul><h3>Logging to Daily Log Files:</h3><p>Using the winston-daily-rotate-file transport, you can create a new log file for each day.</p><p><strong>Install </strong><strong>winston-daily-rotate-file:</strong></p><pre>npm install winston-daily-rotate-file</pre><p><strong>Configure Daily Rotate File Transport:</strong></p><pre>// logger.js<br><br>const { createLogger, format, transports } = require(&#39;winston&#39;);<br>const DailyRotateFile = require(&#39;winston-daily-rotate-file&#39;);<br><br>const logger = createLogger({<br>  level: &#39;info&#39;,<br>  format: format.combine(<br>    format.timestamp(),<br>    format.printf(({ timestamp, level, message }) =&gt; `${timestamp} ${level}: ${message}`)<br>  ),<br>  transports: [<br>    new transports.Console(),<br>    new DailyRotateFile({<br>      filename: &#39;application-%DATE%.log&#39;,<br>      datePattern: &#39;YYYY-MM-DD&#39;,<br>      zippedArchive: true,<br>      maxSize: &#39;20m&#39;,<br>      maxFiles: &#39;14d&#39;<br>    })<br>  ]<br>});<br><br>module.exports = logger;</pre><p><strong>Explanation:</strong></p><ul><li><strong>DailyRotateFile:</strong> Creates a new log file every day with the specified date pattern.</li><li><strong>zippedArchive:</strong> Compresses older log files.</li><li><strong>maxSize:</strong> Maximum size of a log file before rotating.</li><li><strong>maxFiles:</strong> Maximum number of days to keep log files.</li></ul><h3>Using Winston in an Express Application:</h3><p>Integrate Winston into an Express application to handle logging for HTTP requests and errors.</p><p><strong>Install Express:</strong></p><pre>npm install express</pre><p><strong>Set Up Express Server with Winston:</strong></p><pre>// server.js<br><br>const express = require(&#39;express&#39;);<br>const logger = require(&#39;./logger&#39;);<br><br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>// Middleware to log HTTP requests<br>app.use((req, res, next) =&gt; {<br>  logger.http(`${req.method} ${req.url}`);<br>  next();<br>});<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello, World!&#39;);<br>});<br><br>// Error handling middleware<br>app.use((err, req, res, next) =&gt; {<br>  logger.error(err.message);<br>  res.status(500).send(&#39;Internal Server Error&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  logger.info(`Server is running on http://localhost:${PORT}`);<br>});</pre><p><strong>Explanation:</strong></p><ul><li><strong>Logging HTTP Requests:</strong> Middleware logs all incoming HTTP requests using logger.http.</li><li><strong>Error Handling Middleware:</strong> Logs errors using logger.error.</li></ul><h3>Conclusion:</h3><p>By integrating Winston into your Node.js applications, you can create a powerful and flexible logging system that helps you debug, monitor, and maintain your code more effectively. Whether you need to log to the console, files, or external services, Winston’s rich feature set makes it an excellent choice for Node.js logging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d15302947c28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Advanced JavaScript Tricks You Don’t Know]]></title>
            <link>https://bjprajapati.medium.com/10-advanced-javascript-tricks-you-dont-know-f1929e40703d?source=rss-3f40a54c3bc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1929e40703d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[bhavik prajapati]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 03:31:02 GMT</pubDate>
            <atom:updated>2024-06-09T03:31:02.956Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Enhance your coding skills with these lesser-known JavaScript techniques.</strong></p><figure><img alt="Infographic illustrating advanced JavaScript tricks such as destructuring with aliasing, currying, debouncing, throttling, memoization, proxy, generators, console methods, structured cloning, and self-invoking functions" src="https://cdn-images-1.medium.com/max/1024/1*PQ2O_-QPWPELuYctLu0o0Q.jpeg" /></figure><p>JavaScript is a versatile language with many hidden features that can make your development process more efficient and your code cleaner. Here are 10 advanced JavaScript tricks that you might not know, but which can significantly enhance your coding skills.</p><h3>1. Destructuring with Aliasing</h3><p>Destructuring allows you to unpack values from arrays or properties from objects into distinct variables. Aliasing enables you to rename the variables during this process, which is particularly useful when dealing with data from external sources like APIs.</p><p><strong>Use Case:</strong> When fetching data from an API, and you want to give more meaningful names to the properties for better code readability and maintainability.</p><pre>const apiResponse = { first_name: &#39;John&#39;, user_age: 30, address: { city: &#39;New York&#39;, zip: &#39;10001&#39; } };<br>const { first_name: firstName, user_age: age, address: { city: hometown, zip: postalCode } } = apiResponse;<br>console.log(firstName); // John<br>console.log(age); // 30<br>console.log(hometown); // New York<br>console.log(postalCode); // 10001</pre><p><strong>Why Use It:</strong> It helps in making the variable names more self-explanatory and intuitive, which improves code readability and maintenance. By using aliasing, you can avoid name clashes and enhance the clarity of your code, making it easier to work with complex data structures.</p><h3>2. Currying</h3><p>Currying is the process of transforming a function that takes multiple arguments into a series of functions that each take a single argument. This technique allows you to create more flexible and reusable functions, which can be particularly useful in functional programming.</p><p><strong>Use Case:</strong> Create reusable and configurable functions for applying discounts. Instead of writing separate functions for different discount percentages, you can create a single curried function.</p><pre>const applyDiscount = (discount) =&gt; (price) =&gt; price - (price * discount / 100);<br>const tenPercentOff = applyDiscount(10);<br>const twentyPercentOff = applyDiscount(20);<br><br>console.log(tenPercentOff(100)); // 90<br>console.log(twentyPercentOff(100)); // 80<br><br>const applyTax = (taxRate) =&gt; (price) =&gt; price + (price * taxRate / 100);<br>const applyTenPercentTax = applyTax(10);<br><br>console.log(applyTenPercentTax(100)); // 110<br>console.log(applyTenPercentTax(twentyPercentOff(100))); // 88</pre><p><strong>Why Use It:</strong> It enables you to preset arguments in functions, leading to more modular and composable code. This can greatly simplify the creation of highly reusable utility functions, making your codebase cleaner and easier to maintain. Currying is especially useful in scenarios where functions need to be partially applied or reused with different configurations.</p><h3>3. Debouncing and Throttling</h3><p>Debouncing and throttling are techniques to control how often a function is executed. They are particularly useful for optimizing event handlers to prevent excessive function calls that can degrade performance.</p><p><strong>Debouncing:</strong></p><p>Debouncing ensures that a function is not called again until a certain amount of time has passed since the last call. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.</p><p><strong>Use Case:</strong> Optimizing a search input field to reduce the number of API calls. This can prevent server overload and improve the user experience by only initiating the search once the user has finished typing.</p><pre>function debounce(func, delay) {<br>  let timeoutId;<br>  return function(...args) {<br>    clearTimeout(timeoutId);<br>    timeoutId = setTimeout(() =&gt; func.apply(this, args), delay);<br>  };<br>}<br><br>const search = debounce((query) =&gt; {<br>  console.log(`Searching for ${query}`);<br>  // Imagine an API call here<br>}, 300);<br><br>document.getElementById(&#39;searchInput&#39;).addEventListener(&#39;input&#39;, (event) =&gt; {<br>  search(event.target.value);<br>});</pre><p><strong>Why Use It:</strong> Reduces the number of unnecessary function calls, improving performance and user experience by ensuring that the function is only called after the user has stopped performing the triggering action. This is particularly useful for actions that involve network requests or heavy computations.</p><p><strong>Throttling:</strong></p><p>Throttling ensures that a function is called at most once in a specified time period. This is useful for scenarios like scroll events where you want to limit the frequency of function calls.</p><p><strong>Use Case:</strong> Optimizing scroll event handling to improve performance. This can prevent the browser from being overwhelmed by too many event calls, ensuring smoother and more responsive interactions.</p><pre>function throttle(func, interval) {<br>  let lastCall = 0;<br>  return function(...args) {<br>    const now = Date.now();<br>    if (now - lastCall &gt;= interval) {<br>      lastCall = now;<br>      func.apply(this, args);<br>    }<br>  };<br>}<br><br>const handleScroll = throttle(() =&gt; {<br>  console.log(&#39;Scrolled&#39;);<br>  // Imagine complex calculations or DOM updates here<br>}, 300);<br><br>window.addEventListener(&#39;scroll&#39;, handleScroll);</pre><p><strong>Why Use It:</strong> Prevents performance issues by ensuring a function is called at controlled intervals, reducing the load on the browser and providing a better user experience. Throttling is particularly useful for event listeners that can be triggered frequently, such as scroll or resize events.</p><h3>4. Memoization</h3><p>Memoization is an optimization technique that involves caching the results of expensive function calls and returning the cached result when the same inputs occur again. This can significantly improve performance for functions with heavy computation, particularly those that are called frequently with the same arguments.</p><p><strong>Use Case:</strong> Improve performance of recursive functions like Fibonacci calculation. Without memoization, each call to the Fibonacci function would redundantly compute the same values multiple times, leading to exponential time complexity.</p><pre>const memoize = (fn) =&gt; {<br>  const cache = {};<br>  return (...args) =&gt; {<br>    const key = JSON.stringify(args);<br>    if (!cache[key]) {<br>      cache[key] = fn(...args);<br>    }<br>    return cache[key];<br>  };<br>};<br><br>const fibonacci = memoize((n) =&gt; {<br>  if (n &lt;= 1) return n;<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>});<br><br>console.log(fibonacci(40)); // 102334155</pre><p><strong>Why Use It:</strong> Avoids redundant calculations, significantly improving performance for functions with repeated inputs. Memoization can transform an inefficient, repetitive computation into a manageable, linear-time operation, making it an essential technique for optimizing performance-intensive tasks.</p><h3>5. Proxy</h3><p>The Proxy object allows you to create a proxy for another object, enabling you to intercept and redefine fundamental operations such as property lookup, assignment, enumeration, function invocation, etc. This provides a powerful way to add custom behavior to objects.</p><p><strong>Use Case:</strong> Validation and logging on object property access and assignment. For instance, you can enforce type constraints and log access attempts, providing better control and debugging capabilities.</p><pre>const user = {<br>  name: &#39;John&#39;,<br>  age: 30<br>};<br><br>const handler = {<br>  get: (target, prop) =&gt; {<br>    console.log(`Getting ${prop}`);<br>    return target[prop];<br>  },<br>  set: (target, prop, value) =&gt; {<br>    if (prop === &#39;age&#39; &amp;&amp; typeof value !== &#39;number&#39;) {<br>      throw new TypeError(&#39;Age must be a number&#39;);<br>    }<br>    console.log(`Setting ${prop} to ${value}`);<br>    target[prop] = value;<br>    return true;<br>  }<br>};<br><br>const proxyUser = new Proxy(user, handler);<br>console.log(proxyUser.name); // Getting name, John<br>proxyUser.age = 35; // Setting age to 35<br>// proxyUser.age = &#39;35&#39;; // Throws TypeError</pre><p><strong>Why Use It:</strong> Allows custom behavior for object operations, such as validation, logging, and more, enhancing control over object manipulation. Proxies can also be used to implement complex logic like access control and data binding. This makes them a versatile tool for managing and extending the behavior of objects.</p><h3>6. Generators</h3><p>Generators are functions that can be exited and later re-entered, maintaining their context and variable bindings across re-entrances. They are useful for implementing iterators and handling asynchronous tasks in a synchronous-like manner.</p><p><strong>Use Case:</strong> Implementing an iterator for custom object traversal. Generators provide a simple way to define custom iteration behavior, making it easier to traverse complex data structures.</p><pre>function* objectEntries(obj) {<br>  for (let key of Object.keys(obj)) {<br>    yield [key, obj[key]];<br>  }<br>}<br><br>const user = { name: &#39;John&#39;, age: 30, city: &#39;New York&#39; };<br><br>for (let [key, value] of objectEntries(user)) {<br>  console.log(`${key}: ${value}`);<br>}<br>// name: John<br>// age: 30<br>// city: New York</pre><p><strong>Why Use It:</strong> Provides a powerful tool for implementing custom iterators and simplifying asynchronous workflows. Generators make it easier to handle complex iteration logic and asynchronous processes, leading to more readable and maintainable code. They can also be used for tasks like managing asynchronous operations in a more straightforward, linear fashion using libraries like co.</p><h3>7. Making Good Use of Console</h3><p><strong>Use Case:</strong> Improve logging for debugging complex objects. The console methods like console.table, console.group, and console.time can provide more structured and informative debug information.</p><pre>// Basic logging<br>console.log(&#39;Simple log&#39;);<br>console.error(&#39;This is an error&#39;);<br>console.warn(&#39;This is a warning&#39;);<br><br>// Logging tabular data<br>const users = [<br>  { name: &#39;John&#39;, age: 30, city: &#39;New York&#39; },<br>  { name: &#39;Jane&#39;, age: 25, city: &#39;San Francisco&#39; },<br>];<br>console.table(users);<br><br>// Grouping logs<br>console.group(&#39;User Details&#39;);<br>console.log(&#39;User 1: John&#39;);<br>console.log(&#39;User 2: Jane&#39;);<br>console.groupEnd();<br><br>// Timing code execution<br>console.time(&#39;Timer&#39;);<br>for (let i = 0; i &lt; 1000000; i++) {<br>  // Some heavy computation<br>}<br>console.timeEnd(&#39;Timer&#39;);</pre><p><strong>Why Use It:</strong> Enhances the visibility and organization of debugging information, making it easier to diagnose and fix issues. Proper use of console methods can significantly improve the efficiency of your debugging process by providing clear, organized, and detailed logs.</p><h3>8. Structured Cloning with structuredClone</h3><p>Deep clone objects using the new structuredClone. Unlike the traditional shallow copy, structured cloning creates a deep copy of the object, ensuring that nested objects are also copied. This method avoids the limitations of JSON.parse(JSON.stringify(obj)), which cannot handle certain data types like functions, undefined, and circular references.</p><p><strong>Use Case:</strong> Creating a deep copy of complex objects. This is useful when you need to duplicate objects for operations that should not mutate the original data.</p><pre>const obj = { <br>  a: 1, <br>  b: { c: 2 },<br>  date: new Date(),<br>  arr: [1, 2, 3],<br>  nestedArr: [{ d: 4 }]<br>};<br>const clonedObj = structuredClone(obj);<br><br>console.log(clonedObj); <br>// { a: 1, b: { c: 2 }, date: 2023-06-08T00:00:00.000Z, arr: [1, 2, 3], nestedArr: [{ d: 4 }] }<br>console.log(clonedObj === obj); // false<br>console.log(clonedObj.b === obj.b); // false<br>console.log(clonedObj.date === obj.date); // false<br>console.log(clonedObj.arr === obj.arr); // false<br>console.log(clonedObj.nestedArr[0] === obj.nestedArr[0]); // false</pre><p><strong>Why Use It:</strong> Provides a built-in, efficient way to perform deep cloning of objects, avoiding the pitfalls and complexities of manual deep copy implementations. This method is more reliable and handles complex data structures better than alternatives like JSON.parse(JSON.stringify(obj)).</p><h3>9. Self-Invoking Functions</h3><p>Self-invoking functions, also known as Immediately Invoked Function Expressions (IIFE), are executed automatically after they are created. They are useful for encapsulating code to avoid polluting the global scope, which is essential in maintaining clean and modular code.</p><p><strong>Use Case:</strong> Encapsulating code to avoid polluting the global scope. This technique is particularly useful in older JavaScript environments where block scope (let and const) is not available, or in scenarios where immediate execution is needed for initialization logic.</p><pre>(function() {<br>  const privateVar = &#39;This is private&#39;;<br>  console.log(&#39;Self-invoking function runs immediately&#39;);<br>  // Initialization code here<br>})();<br><br>// Private variables are not accessible from outside<br>// console.log(privateVar); // ReferenceError: privateVar is not defined</pre><p><strong>Why Use It:</strong> Helps in maintaining clean code by avoiding global variables and executing initialization code without leaving traces in the global scope. This approach can prevent conflicts in larger codebases and ensure better encapsulation of functionality, improving code maintainability and avoiding side effects.</p><h3>10. Tagged Template Literals</h3><p>Tagged template literals allow you to customize the way template literals are processed. They are useful for creating specialized templates, such as for internationalization, sanitizing HTML, or generating dynamic SQL queries.</p><p><strong>Use Case:</strong> Sanitizing user input in HTML templates to prevent XSS attacks. This technique ensures that user-generated content is safely inserted into the DOM without executing any malicious scripts.</p><pre>function sanitize(strings, ...values) {<br>  return strings.reduce((result, string, i) =&gt; {<br>    let value = values[i - 1];<br>    if (typeof value === &#39;string&#39;) {<br>      value = value.replace(/&amp;/g, &#39;&amp;amp;&#39;)<br>                   .replace(/&lt;/g, &#39;&amp;lt;&#39;)<br>                   .replace(/&gt;/g, &#39;&amp;gt;&#39;)<br>                   .replace(/&quot;/g, &#39;&amp;quot;&#39;)<br>                   .replace(/&#39;/g, &#39;&amp;#39;&#39;);<br>    }<br>    return result + value + string;<br>  });<br>}<br><br>const userInput = &#39;&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;&#39;;<br>const message = sanitize`User input: ${userInput}`;<br>console.log(message); // User input: &amp;lt;script&amp;gt;alert(&quot;xss&quot;)&amp;lt;/script&amp;gt;</pre><p><strong>Why Use It:</strong> Provides a powerful mechanism to control and customize the output of template literals, enabling safer and more flexible template creation. Tagged template literals can be used to enforce security, format strings, and generate dynamic content, enhancing the robustness and versatility of your code.</p><h3>Conclusion</h3><p>JavaScript is a language rich with features that can help you write cleaner, more efficient code. By incorporating these advanced tricks into your coding practices, you can improve your productivity and enhance the readability of your code. From destructuring with aliasing to currying, debouncing, throttling, and more, these tips can make your code cleaner and more efficient. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1929e40703d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your Node.js API: Best Practices and Essential Techniques]]></title>
            <link>https://bjprajapati.medium.com/securing-your-node-js-api-best-practices-and-essential-techniques-0a2603f9d179?source=rss-3f40a54c3bc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2603f9d179</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[bhavik prajapati]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 04:50:29 GMT</pubDate>
            <atom:updated>2024-06-08T04:50:29.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Illustration of a secure Node.js API infrastructure, featuring a server surrounded by shields and locks, with visual elements like code snippets, a secure connection symbol, and the Node.js logo, using blue and green colors to convey security and reliability." src="https://cdn-images-1.medium.com/max/1024/1*SNef6fBEvsEEGcGX0pkmBw.png" /><figcaption>Ensuring the Security of Your Node.js API: Best Practices for Robust Protection</figcaption></figure><p>Node.js has become a popular choice for building APIs due to its efficiency and scalability. However, with the rise in cyber threats, securing your Node.js API has never been more critical. In this article, we’ll explore some of the best practices and essential techniques to safeguard your API against potential vulnerabilities.</p><h3>1. Use HTTPS</h3><p>HTTPS encrypts the data exchanged between the client and the server, preventing man-in-the-middle attacks. Ensure your API endpoints are only accessible over HTTPS.</p><p>To enable HTTPS, you’ll need an SSL certificate. Here’s a basic setup using the https module:</p><pre>const https = require(&#39;https&#39;);<br>const fs = require(&#39;fs&#39;);<br>const express = require(&#39;express&#39;);<br>const app = express();<br><br>const options = {<br>  key: fs.readFileSync(&#39;path/to/your/private.key&#39;),<br>  cert: fs.readFileSync(&#39;path/to/your/certificate.crt&#39;)<br>};<br><br>https.createServer(options, app).listen(443, () =&gt; {<br>  console.log(&#39;Server is running on https://localhost:443&#39;);<br>});</pre><h3>2. Validate Input</h3><p>Always validate and sanitize user inputs to prevent SQL injection, XSS attacks, and other malicious inputs. Libraries like Joi and express-validator can help enforce validation rules.</p><p>Using Joi for validation:</p><pre>const Joi = require(&#39;joi&#39;);<br><br>const schema = Joi.object({<br>  username: Joi.string().alphanum().min(3).max(30).required(),<br>  password: Joi.string().pattern(new RegExp(&#39;^[a-zA-Z0-9]{3,30}$&#39;)).required()<br>});<br><br>app.post(&#39;/register&#39;, (req, res, next) =&gt; {<br>  const { error } = schema.validate(req.body);<br>  if (error) {<br>    return res.status(400).send(error.details[0].message);<br>  }<br>  next();<br>});</pre><h3>3. Implement Authentication</h3><p>Use robust authentication mechanisms such as OAuth, JWT (JSON Web Tokens), or API keys. JWT is particularly popular for its simplicity and security.</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br><br>// Generate a token<br>const token = jwt.sign({ userId: user.id }, &#39;your-secret-key&#39;, { expiresIn: &#39;1h&#39; });<br><br>// Middleware to verify a token<br>function authenticateToken(req, res, next) {<br>  const token = req.headers[&#39;authorization&#39;];<br>  if (!token) return res.sendStatus(401);<br><br>  jwt.verify(token, &#39;your-secret-key&#39;, (err, user) =&gt; {<br>    if (err) return res.sendStatus(403);<br>    req.user = user;<br>    next();<br>  });<br>}<br><br>app.get(&#39;/protected&#39;, authenticateToken, (req, res) =&gt; {<br>  res.send(&#39;This is a protected route&#39;);<br>});</pre><h3>4. Enforce Authorization</h3><p>Ensure that authenticated users have the necessary permissions to access specific resources. Role-based access control (RBAC) can help manage user roles and permissions effectively.</p><pre>const roles = {<br>  admin: [&#39;read&#39;, &#39;write&#39;, &#39;delete&#39;],<br>  user: [&#39;read&#39;, &#39;write&#39;]<br>};<br><br>function authorize(role, action) {<br>  return (req, res, next) =&gt; {<br>    const userRole = req.user.role;<br>    if (roles[userRole] &amp;&amp; roles[userRole].includes(action)) {<br>      next();<br>    } else {<br>      res.sendStatus(403);<br>    }<br>  };<br>}<br><br>app.post(&#39;/admin&#39;, authenticateToken, authorize(&#39;admin&#39;, &#39;write&#39;), (req, res) =&gt; {<br>  res.send(&#39;Admin route&#39;);<br>});</pre><h3>5. Rate Limiting</h3><p>Implement rate limiting to prevent abuse and DDoS attacks. Libraries like express-rate-limit can help you set up rate limiting for your API endpoints.</p><pre>const rateLimit = require(&#39;express-rate-limit&#39;);<br><br>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000, // 15 minutes<br>  max: 100 // limit each IP to 100 requests per windowMs<br>});<br><br>app.use(limiter);</pre><h3>6. Secure Your Dependencies</h3><p>Regularly update your dependencies and use tools like npm audit to identify and fix vulnerabilities in third-party packages.</p><p>Run the following command to check for vulnerabilities:</p><pre>npm audit</pre><h3>7. Use Helmet for HTTP Headers</h3><p>Helmet helps secure your API by setting various HTTP headers. It can prevent many common vulnerabilities.</p><pre>const helmet = require(&#39;helmet&#39;);<br>app.use(helmet());</pre><h3>8. Content Security Policy (CSP)</h3><p>Implement CSP to prevent XSS attacks by whitelisting trusted content sources. Helmet can also help with CSP.</p><pre>app.use(helmet.contentSecurityPolicy({<br>  directives: {<br>    defaultSrc: [&quot;&#39;self&#39;&quot;],<br>    scriptSrc: [&quot;&#39;self&#39;&quot;, &#39;trusted-cdn.com&#39;]<br>  }<br>}));</pre><h3>9. Logging and Monitoring</h3><p>Maintain logs of all activities and monitor them for suspicious behavior. Tools like Winston for logging and PM2 for monitoring can be highly effective.</p><p>Using Winston for logging:</p><pre>const winston = require(&#39;winston&#39;);<br><br>const logger = winston.createLogger({<br>  level: &#39;info&#39;,<br>  format: winston.format.json(),<br>  transports: [<br>    new winston.transports.File({ filename: &#39;error.log&#39;, level: &#39;error&#39; }),<br>    new winston.transports.File({ filename: &#39;combined.log&#39; })<br>  ]<br>});<br><br>app.use((req, res, next) =&gt; {<br>  logger.info(`HTTP ${req.method} ${req.url}`);<br>  next();<br>});</pre><p>Using PM2 for monitoring:</p><pre>pm2 start app.js --name &quot;my-api&quot;<br>pm2 monit</pre><h3>10. Regular Security Audits</h3><p>Conduct regular security audits and penetration testing to identify and mitigate potential security risks.</p><p>You can use tools like nmap, OWASP ZAP, and Burp Suite for penetration testing. Regularly review your code and dependencies for vulnerabilities.</p><h3>Conclusion</h3><p>Securing your Node.js API is an ongoing process that requires diligence and attention to detail. By following these best practices, you can significantly reduce the risk of security breaches and protect your application and its users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2603f9d179" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>