<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: officiabreezy</title>
    <description>The latest articles on DEV Community by officiabreezy (@officiabreezy).</description>
    <link>https://dev.to/officiabreezy</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1112830%2Fcb7f8a4f-8c2f-4fb3-975f-fdc67bc3c4c9.png</url>
      <title>DEV Community: officiabreezy</title>
      <link>https://dev.to/officiabreezy</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/officiabreezy"/>
    <language>en</language>
    <item>
      <title>From Localhost to Cloud: Deploying a Node.js Bot app to AWS EC2 (My 3rd Deployment, Different Method!)</title>
      <dc:creator>officiabreezy</dc:creator>
      <pubDate>Tue, 17 Feb 2026 11:23:02 +0000</pubDate>
      <link>https://dev.to/officiabreezy/from-localhost-to-cloud-deploying-a-nodejs-bot-app-to-aws-ec2-my-3rd-deployment-different-5586</link>
      <guid>https://dev.to/officiabreezy/from-localhost-to-cloud-deploying-a-nodejs-bot-app-to-aws-ec2-my-3rd-deployment-different-5586</guid>
      <description>&lt;p&gt;A practical walkthrough of deploying a Node.js bot app to AWS EC2 using GitHub + PM2 + systemd — my third EC2 deployment using a completely different approach each time&lt;/p&gt;

&lt;h1&gt;
  
  
  From Localhost to Cloud: Deploying a Node.js Bot App to AWS EC2
&lt;/h1&gt;

&lt;p&gt;This is my &lt;strong&gt;third time&lt;/strong&gt; deploying to AWS EC2, and I've used a different method each time:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;🐳 &lt;strong&gt;1st deployment&lt;/strong&gt; — Docker containers&lt;/li&gt;
&lt;li&gt;📁 &lt;strong&gt;2nd deployment&lt;/strong&gt; — Manual file upload (SCP)&lt;/li&gt;
&lt;li&gt;🔄 &lt;strong&gt;3rd deployment (this one)&lt;/strong&gt; — GitHub + PM2 + systemd&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each approach taught me something unique. This time I wanted a workflow that was easy to update, automatically recovers from crashes, and survives server reboots — without the overhead of Docker for a simple Node.js app.&lt;/p&gt;

&lt;p&gt;Here's exactly what I did, step by step.&lt;/p&gt;




&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;A reporter bot that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Listens for new members joining servers&lt;/li&gt;
&lt;li&gt;Sends real-time notifications with member details&lt;/li&gt;
&lt;li&gt;Logs all activity with automatic daily log rotation (7-day retention)&lt;/li&gt;
&lt;li&gt;Runs &lt;strong&gt;24/7 in the cloud&lt;/strong&gt; — even when my PC is off&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tech stack: &lt;strong&gt;Node.js, discord.js, axios, winston, PM2, AWS EC2 (Ubuntu 22.04)&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Step 1: Launch an EC2 Instance
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Log in to &lt;a href="https://console.aws.amazon.com/" rel="noopener noreferrer"&gt;AWS Console&lt;/a&gt; → EC2 → &lt;strong&gt;Launch Instance&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Configure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;OS&lt;/strong&gt;: Ubuntu Server 22.04 LTS (Free tier eligible)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Instance type&lt;/strong&gt;: t2.micro (Free tier)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Key pair&lt;/strong&gt;: Create new → download the &lt;code&gt;.pem&lt;/code&gt; file (keep this safe!)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Security Group&lt;/strong&gt;: Open ports 22 (SSH), 80 (HTTP), 443 (HTTPS)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Click &lt;strong&gt;Launch Instance&lt;/strong&gt; and wait for it to start&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Step 2: Connect to Your EC2 Instance
&lt;/h2&gt;

&lt;p&gt;From your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Make your key file readable (Linux/Mac/Git Bash)&lt;/span&gt;
&lt;span class="nb"&gt;chmod &lt;/span&gt;400 your-key.pem

&lt;span class="c"&gt;# Connect via SSH&lt;/span&gt;
ssh &lt;span class="nt"&gt;-i&lt;/span&gt; your-key.pem ubuntu@&amp;lt;your-ec2-public-ip&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should now see the Ubuntu welcome screen. You're in! 🎉&lt;/p&gt;




&lt;h2&gt;
  
  
  Step 3: Set Up the Server
&lt;/h2&gt;

&lt;p&gt;Once connected, install the required tools:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Update system packages&lt;/span&gt;
&lt;span class="nb"&gt;sudo &lt;/span&gt;apt update &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;sudo &lt;/span&gt;apt upgrade &lt;span class="nt"&gt;-y&lt;/span&gt;

&lt;span class="c"&gt;# Install Node.js (v20)&lt;/span&gt;
curl &lt;span class="nt"&gt;-fsSL&lt;/span&gt; https://deb.nodesource.com/setup_20.x | &lt;span class="nb"&gt;sudo&lt;/span&gt; &lt;span class="nt"&gt;-E&lt;/span&gt; bash -
&lt;span class="nb"&gt;sudo &lt;/span&gt;apt &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-y&lt;/span&gt; nodejs

&lt;span class="c"&gt;# Verify installation&lt;/span&gt;
node &lt;span class="nt"&gt;--version&lt;/span&gt;
npm &lt;span class="nt"&gt;--version&lt;/span&gt;

&lt;span class="c"&gt;# Install Git&lt;/span&gt;
&lt;span class="nb"&gt;sudo &lt;/span&gt;apt &lt;span class="nb"&gt;install &lt;/span&gt;git &lt;span class="nt"&gt;-y&lt;/span&gt;

&lt;span class="c"&gt;# Install PM2 globally (process manager)&lt;/span&gt;
&lt;span class="nb"&gt;sudo &lt;/span&gt;npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-g&lt;/span&gt; pm2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Step 4: Clone Your Repository from GitHub
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;⚠️ GitHub no longer accepts passwords. Use a &lt;strong&gt;Personal Access Token (PAT)&lt;/strong&gt; instead.&lt;/p&gt;

&lt;p&gt;Go to: GitHub → Settings → Developer Settings → Personal Access Tokens → Generate New Token (check the &lt;code&gt;repo&lt;/code&gt; scope)&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Clone using your token&lt;/span&gt;
git clone https://&amp;lt;YOUR_TOKEN&amp;gt;@github.com/yourusername/your-repo.git

&lt;span class="c"&gt;# Navigate into project&lt;/span&gt;
&lt;span class="nb"&gt;cd &lt;/span&gt;your-repo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;🔐 &lt;strong&gt;Security tip&lt;/strong&gt;: Never hardcode tokens in your source code. Use environment variables with a &lt;code&gt;.env&lt;/code&gt; file in production.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Step 5: Install Dependencies
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Create logs directory (if your app needs it)&lt;/span&gt;
&lt;span class="nb"&gt;mkdir&lt;/span&gt; &lt;span class="nt"&gt;-p&lt;/span&gt; logs

&lt;span class="c"&gt;# Install npm packages&lt;/span&gt;
npm &lt;span class="nb"&gt;install&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see all packages installed successfully.&lt;/p&gt;




&lt;h2&gt;
  
  
  Step 6: Start Your App with PM2
&lt;/h2&gt;

&lt;p&gt;PM2 is a production process manager for Node.js. It keeps your app running, auto-restarts on crashes, and manages logs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Start the application&lt;/span&gt;
pm2 start index.js &lt;span class="nt"&gt;--name&lt;/span&gt; &lt;span class="s2"&gt;"my-app"&lt;/span&gt;

&lt;span class="c"&gt;# Check it's running&lt;/span&gt;
pm2 status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌────┬──────────┬──────────┬──────┬───────────┬──────────┬──────────┐
│ id │ name     │ mode     │ ↺    │ status    │ cpu      │ memory   │
├────┼──────────┼──────────┼──────┼───────────┼──────────┼──────────┤
│ 0  │ my-app   │ fork     │ 0    │ online    │ 0%       │ 45.0mb   │
└────┴──────────┴──────────┴──────┴───────────┴──────────┴──────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Status: online ✅&lt;/strong&gt; — your app is running!&lt;/p&gt;




&lt;h2&gt;
  
  
  Step 7: Configure Auto-Start on Reboot
&lt;/h2&gt;

&lt;p&gt;This is the most important step for a "set it and forget it" deployment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Generate the startup command&lt;/span&gt;
pm2 startup

&lt;span class="c"&gt;# PM2 will output a command — copy and run it. It looks like:&lt;/span&gt;
&lt;span class="nb"&gt;sudo env &lt;/span&gt;&lt;span class="nv"&gt;PATH&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nv"&gt;$PATH&lt;/span&gt;:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd &lt;span class="nt"&gt;-u&lt;/span&gt; ubuntu &lt;span class="nt"&gt;--hp&lt;/span&gt; /home/ubuntu

&lt;span class="c"&gt;# Save the current process list&lt;/span&gt;
pm2 save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now your app will &lt;strong&gt;automatically start&lt;/strong&gt; whenever the EC2 instance reboots!&lt;/p&gt;




&lt;h2&gt;
  
  
  Step 8: Verify Everything is Working
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# View live logs&lt;/span&gt;
pm2 logs my-app

&lt;span class="c"&gt;# Monitor CPU and memory&lt;/span&gt;
pm2 monit

&lt;span class="c"&gt;# Check disk space&lt;/span&gt;
&lt;span class="nb"&gt;df&lt;/span&gt; &lt;span class="nt"&gt;-h&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Comparing My 3 Deployment Methods
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Docker&lt;/th&gt;
&lt;th&gt;Manual SCP&lt;/th&gt;
&lt;th&gt;GitHub + PM2&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Setup time&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;td&gt;Fast&lt;/td&gt;
&lt;td&gt;Fast&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Update process&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Rebuild image&lt;/td&gt;
&lt;td&gt;Re-upload files&lt;/td&gt;
&lt;td&gt;&lt;code&gt;git pull&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Auto-restart&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;With compose&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;✅ Built-in&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Boot persistence&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;With compose&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;✅ systemd&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Best for&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Complex apps&lt;/td&gt;
&lt;td&gt;Learning&lt;/td&gt;
&lt;td&gt;Solo projects&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Learning curve&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  What I Learned From Each:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;🐳 Docker&lt;/strong&gt;: Great for complex apps with multiple services. Containerization ensures consistency across environments. But for a simple Node.js bot, it felt like overkill.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📁 Manual SCP&lt;/strong&gt;: Forced me to understand exactly what's happening on the server — no abstractions. Best for learning fundamentals but tedious for frequent updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🔄 GitHub + PM2 (this one)&lt;/strong&gt;: Sweet spot for solo projects. Easy updates (&lt;code&gt;git pull &amp;amp;&amp;amp; pm2 restart&lt;/code&gt;), built-in crash recovery, and systemd integration for boot persistence.&lt;/p&gt;




&lt;h2&gt;
  
  
  Disk Space Management
&lt;/h2&gt;

&lt;p&gt;One thing to keep in mind — my bot generates daily log files. Here's what my disk usage looked like after deployment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;&lt;span class="nb"&gt;df&lt;/span&gt; &lt;span class="nt"&gt;-h&lt;/span&gt;
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       6.8G  3.2G  3.6G  47% /

&lt;span class="nv"&gt;$ &lt;/span&gt;&lt;span class="nb"&gt;du&lt;/span&gt; &lt;span class="nt"&gt;-sh&lt;/span&gt; ~/reporter/logs/
232K    /home/ubuntu/reporter/logs/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;47% used with plenty of headroom.&lt;/strong&gt; My winston logger is configured with &lt;code&gt;maxFiles: "7d"&lt;/code&gt; which automatically deletes logs older than 7 days — keeping disk usage minimal.&lt;/p&gt;




&lt;h2&gt;
  
  
  Useful PM2 Commands
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Check status&lt;/span&gt;
pm2 status

&lt;span class="c"&gt;# View live logs&lt;/span&gt;
pm2 logs my-app

&lt;span class="c"&gt;# View last 100 lines&lt;/span&gt;
pm2 logs my-app &lt;span class="nt"&gt;--lines&lt;/span&gt; 100

&lt;span class="c"&gt;# Restart app&lt;/span&gt;
pm2 restart my-app

&lt;span class="c"&gt;# Stop app&lt;/span&gt;
pm2 stop my-app

&lt;span class="c"&gt;# Monitor CPU/Memory in real-time&lt;/span&gt;
pm2 monit

&lt;span class="c"&gt;# List all processes&lt;/span&gt;
pm2 list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;There's no single "best" deployment method&lt;/strong&gt; — the right tool depends on your project complexity and update frequency.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Try multiple approaches&lt;/strong&gt; — each method teaches you something different about how servers actually work.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;PM2 is a game changer&lt;/strong&gt; for Node.js deployments — crash recovery and systemd integration make it production-ready with minimal setup.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;AWS Free Tier is perfect for learning&lt;/strong&gt; — t2.micro with 6.8GB disk is more than enough for simple Node.js apps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Always use environment variables&lt;/strong&gt; for sensitive tokens in production — never hardcode credentials in your source code.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This GitHub + PM2 + systemd approach has become my favorite for solo Node.js projects. It strikes the right balance between simplicity and reliability — easy to set up, easy to update, and runs 24/7 without babysitting.&lt;/p&gt;

&lt;p&gt;If you're just getting started with cloud deployments, I'd recommend this exact stack. Once you're comfortable, try Docker for more complex multi-service applications.&lt;/p&gt;

&lt;p&gt;Happy deploying! 🚀&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Have you deployed to AWS EC2? What method do you prefer? Drop a comment below!&lt;/em&gt;&lt;/p&gt;




</description>
      <category>aws</category>
      <category>node</category>
      <category>devops</category>
      <category>cloudcomputing</category>
    </item>
    <item>
      <title>Middleware function Execution Problem and Solution</title>
      <dc:creator>officiabreezy</dc:creator>
      <pubDate>Mon, 01 Jul 2024 17:43:40 +0000</pubDate>
      <link>https://dev.to/officiabreezy/middleware-function-execution-problem-and-solution-4325</link>
      <guid>https://dev.to/officiabreezy/middleware-function-execution-problem-and-solution-4325</guid>
      <description>&lt;p&gt;What is Middleware?&lt;br&gt;
A middleware can be defined as a function that will have all the access for requesting an object, responding to an object, and moving to the next middleware function in the application request-response cycle. Middleware stand as a bridge between client requests and server responses. It's also responsible for handling tasks like logging, authentication, error handling and so on.&lt;/p&gt;

&lt;p&gt;Middleware Problem&lt;br&gt;
middleware problem i encountered make me understand how middleware flow works, while developing a Node.js application with Express, authentication middleware was not working because the functions were not executed in a proper way, the logging  was not capturing necessary information and the error handling was not consistent&lt;/p&gt;

&lt;p&gt;Solution to the Problem &lt;br&gt;
firstly, you need to identify the cause of middleware execution issues and the order in which the middleware functions were declared in the application. middleware is a bridge between incoming request and the response that is why we call it request-response cycle below is a version of middleware setup in server.js;&lt;/p&gt;

&lt;p&gt;const express = require('express');&lt;br&gt;
const app = express();&lt;br&gt;
const authMiddleware = require('./middlewares/auth');&lt;br&gt;
const errorHandler = require('./middleware/errorHandler');&lt;br&gt;
const Routes = require('./routes/contactRoutes');&lt;br&gt;
const userRoutes = require('./routes/userRoutes');&lt;br&gt;
const { getContacts,createContact, getContact, deleteContact, updateContact } = require('./controller/contactController');&lt;br&gt;
const router = require('./routes/userRoutes');&lt;/p&gt;

&lt;p&gt;const port = process.env.PORT || 5000;&lt;/p&gt;

&lt;p&gt;app.use(express.json());&lt;br&gt;
app.use(express.urlencoded({extended:true}));&lt;/p&gt;

&lt;p&gt;app.use('/api/v1/contact',Routes);&lt;br&gt;
app.use('/api/v1/user',userRoutes);&lt;br&gt;
app.use(errorHandler)&lt;/p&gt;

&lt;p&gt;app.listen(port, () =&amp;gt; {&lt;br&gt;
    console.log('listening on port ' + port);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;note: To make all this work properly You would have installed all the necessary packages in Node.js including express, dotenv, etc.&lt;/p&gt;

&lt;p&gt;The Authentication Middleware was used to check for a valid JWT and handle unauthorized access for example let say we have admin routes whereby only admin can perform some functions like get the list of all the contacts, delete contact or update contact. if all the 3 routes mention can only be access by admin then a user will be denied access because he/she don't have access to those routes.&lt;/p&gt;

&lt;p&gt;const jwt = require('jsonwebtoken');&lt;/p&gt;

&lt;p&gt;const authMiddleware = (req, res, next) =&amp;gt; {&lt;br&gt;
    const token = req.headers['authorization'];&lt;br&gt;
    if (!token) {&lt;br&gt;
        return res.status(401).json({ message: 'Access denied. No token provided.' });&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
} catch (err) {
    res.status(400).json({ message: 'Invalid token.' });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;};&lt;/p&gt;

&lt;p&gt;module.exports = authMiddleware;&lt;/p&gt;

&lt;p&gt;Error Handling Middleware&lt;br&gt;
Is used to catch and response to errors efficiently&lt;br&gt;
below is a code for error handling;&lt;/p&gt;

&lt;p&gt;const errorMiddleware = (err, req, res, next) =&amp;gt; {&lt;br&gt;
    console.error(err.message);&lt;br&gt;
    res.status(500).json({ message: 'Internal Server Error' });&lt;br&gt;
};&lt;/p&gt;

&lt;p&gt;module.exports = errorMiddleware;&lt;/p&gt;

&lt;p&gt;In conclusion,&lt;br&gt;
i make sure the middleware function were executed in a correct order to improve the performance of my application and improve my experience in knowledge of web applications. As i start my internship journey at HNG Tech Limited I'm eager to tackle new challenges and continue to grow as a backend developer&lt;/p&gt;

&lt;p&gt;This article is in fulfillment of my stage 0 task for the HNG Internship. HNG Internship is a program to educate, contribute to growth and give opportunity to learning tech. Check them out for more information, &lt;a href="https://hng.tech/internship"&gt;https://hng.tech/internship&lt;/a&gt;, &lt;a href="https://hng.tech/hire"&gt;https://hng.tech/hire&lt;/a&gt;, or &lt;a href="https://hng.tech/premium"&gt;https://hng.tech/premium&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>middleware</category>
    </item>
    <item>
      <title>The Importance of Middleware in Node.js</title>
      <dc:creator>officiabreezy</dc:creator>
      <pubDate>Mon, 03 Jul 2023 21:24:15 +0000</pubDate>
      <link>https://dev.to/officiabreezy/-the-importance-of-middleware-in-nodejs-1cfb</link>
      <guid>https://dev.to/officiabreezy/-the-importance-of-middleware-in-nodejs-1cfb</guid>
      <description>&lt;p&gt;&lt;span&gt;&lt;br&gt;
Node.js has gained significant popularity in the world of server-side JavaScript development. It offers a powerful and scalable environment for building web applications and APIs. One of the key features that makes Node.js highly versatile is its robust middleware architecture. In this article, we'll explore the importance of middleware in Node.js and how it enhances the development process. &lt;/span&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Understanding Middleware in Node.js&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In the context of Node.js, middleware refers to a series of functions that are executed in a sequential order during the request-response lifecycle. These functions have access to the request and response objects and can perform various tasks such as modifying request/response data, logging, error handling, authentication, and much more. Middleware acts as a bridge between the web server and the application, allowing for modular and reusable code.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Key Benefits of Middleware in Node.js&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Code Reusability and Modularity
&lt;/h3&gt;

&lt;p&gt;Middleware enables code reusability and modularity in Node.js applications. By breaking down the application logic into smaller middleware functions, developers can focus on specific functionalities and easily reuse them across different routes or projects. This approach not only promotes cleaner code organization but also reduces duplication and improves maintainability.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Request Processing and Response Modification
&lt;/h3&gt;

&lt;p&gt;Middleware functions in Node.js have access to the request and response objects, allowing developers to intercept and modify them as needed. This ability is invaluable when implementing common functionalities such as request validation, data parsing, request logging, response compression, and caching. Middleware functions can intercept incoming requests, process them, and modify the response before it's sent back to the client.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Error Handling and Exception Management.
&lt;/h3&gt;

&lt;p&gt;Error handling is a critical aspect of any robust application. Middleware simplifies the process of handling errors and exceptions in Node.js. By defining error-handling middleware, developers can centralize the error-handling logic and avoid repetitive error handling code in every route or controller. Middleware can catch and handle errors, log them, and send appropriate responses to clients, enhancing the overall reliability and stability of the application.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Authentication and Authorization.
&lt;/h3&gt;

&lt;p&gt;Implementing authentication and authorization is a common requirement for many web applications. Middleware simplifies this process by providing a flexible and modular way to enforce security measures. Developers can create middleware functions to handle authentication, verify user credentials, and manage user sessions. This approach allows for centralized and consistent security implementation across different routes and endpoints.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Routing and URL Handling.
&lt;/h3&gt;

&lt;p&gt;Middleware plays a crucial role in routing and URL handling in Node.js applications. Frameworks like Express.js heavily rely on middleware to define routes and handle URL-based operations. Middleware functions can intercept incoming requests, examine the URL, and determine the appropriate route or action to execute. This flexibility allows developers to define complex routing rules, implement middleware-based access control, and create custom routing behaviors.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Performance Optimization.
&lt;/h3&gt;

&lt;p&gt;Middleware can contribute to performance optimization in Node.js applications. Developers can use middleware functions to implement caching mechanisms, compress responses, optimize database queries, or implement rate limiting and throttling. By strategically placing middleware in the request-response pipeline, developers can improve application performance, reduce server load, and enhance the overall user experience.&lt;/p&gt;

&lt;p&gt;&lt;span&gt;&lt;em&gt;&lt;code&gt;Conclusion&lt;/code&gt;&lt;/em&gt;&lt;br&gt;
&lt;span&gt;  &lt;span&gt;&lt;br&gt;
Middleware plays a vital role in Node.js development, providing a powerful and flexible mechanism for extending and enhancing the functionality of web applications. Its modular and reusable nature promotes code organization, improves maintainability, and reduces duplication. Middleware empowers developers to implement common functionalities such as request processing, response modification, error handling, authentication, and routing in a consistent and centralized manner. By leveraging middleware effectively, developers can build scalable, robust, and efficient Node.js applications that meet the needs of modern web development.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>markdown</category>
      <category>programming</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
