<?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 Paudelronish on Medium]]></title>
        <description><![CDATA[Stories by Paudelronish on Medium]]></description>
        <link>https://medium.com/@paudelronish?source=rss-ef4b39e1fb87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1W5h26g-jKTqK5dRMNCSxA@2x.jpeg</url>
            <title>Stories by Paudelronish on Medium</title>
            <link>https://medium.com/@paudelronish?source=rss-ef4b39e1fb87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:57:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paudelronish/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[Why Is Google Antigravity Still Stuck on Claude Opus 4.6?]]></title>
            <link>https://medium.com/@paudelronish/why-is-google-antigravity-still-stuck-on-claude-opus-4-6-3a67f2361226?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a67f2361226</guid>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 09:33:21 GMT</pubDate>
            <atom:updated>2026-09-27T09:33:21.259Z</atom:updated>
            <content:encoded><![CDATA[<p>I use both Antigravity (IDE + CLI) and Claude Code as part of my regular toolchain. And here’s the thing that’s been bugging me: since the day I started using Antigravity, that model picker has shown Opus 4.6 as the top Claude option. “hasn’t updated in a while” it has <em>never</em> changed, the entire time I’ve had the tool open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfKEavlatXP7avYpv5t3Nw.png" /></figure><p>Meanwhile, on the Claude side, the model’s kept moving. Anthropic shipped Opus 5, then Opus 5.5 on top of that real, noticeable improvements in reasoning and output quality.</p><p>That gap bugged me enough that I went and looked into why.</p><p>Antigravity doesn’t connect directly to Anthropic’s servers. Instead, Google builds its own bridge to Claude kind of like a middleman. Every time Anthropic releases a new Claude model, Google has to test it, connect it, and add it to Antigravity before you can use it there. This doesn’t happen automatically.</p><p>Someone at Google has to do this work by hand. And it looks like nobody has done it since I started using the tool.</p><p>A Google spokesperson said it clearly: Gemini is their “main model,” and other models like Claude are just for “special cases,” with limits on how much you can use them.</p><p>Google makes and sells Gemini. Every time someone uses Claude inside Antigravity instead of Gemini, that’s a small loss for Google’s own product.So keeping Claude stuck on an old version, while Gemini keeps getting updated, quietly pushes people back toward using Gemini instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a67f2361226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Next.js Middleware is Having an Identity Crisis]]></title>
            <link>https://medium.com/@paudelronish/why-next-js-middleware-is-having-an-identity-crisis-8ad740bbec9a?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad740bbec9a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 03:23:23 GMT</pubDate>
            <atom:updated>2025-10-08T03:23:23.990Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever worked with <strong>Next.js Middleware</strong>, you might have noticed something confusing: it <strong>doesn’t behave like Express middleware</strong>, and the docs throw a lot of warnings mid-way. No wonder it’s having an identity crisis! Let’s break it down.</p><h3><strong>What is Next.js Middleware?</strong></h3><p><strong>Next.js Middleware</strong> is a special piece of code that runs <strong>before a request is fully processed</strong>. It’s meant to:</p><ul><li>Inspect incoming requests</li><li>Modify requests or responses</li><li>Redirect users</li><li>Rewrite URLs</li><li>Add or modify headers</li></ul><p>It runs on the <strong>Edge Runtime</strong>, which is a lightweight JavaScript environment distributed globally, closer to users, so things happen <strong>fast and near the user</strong>.</p><h3>So What Exactly is Edge Runtime? Let’s Visualized it..</h3><p>Imagine your app has a <strong>central server</strong>. Every user request from anywhere in the world — has to travel all the way there.</p><p>Chaos ensues: slow responses, traffic jams, and frustrated users.</p><p>Now imagine <strong>lightweight servers at the edge</strong>, closer to users, handling simple tasks instantly:<br> ✅ Checking authentication<br> ✅ Redirecting requests<br> ✅ Adding headers or rewrites</p><p>But they <strong>cannot</strong>:<br> ❌ Query the database<br> ❌ Run heavy computations<br> ❌ Handle complex business logic</p><p>Those still go to the <strong>central server </strong>the heavy-lifter.</p><p>💡 <strong>Tech translation:</strong></p><ul><li>Central server = Main Server Runtime (Node.js)</li><li>Edge servers = Edge Runtime</li><li>Quick auth/redirects = Middleware / Proxy</li><li>Heavy lifting = Database / API calls</li></ul><h3>What Middleware Can and Cannot Do</h3><h4>✅ What it’s good at:</h4><ul><li>Checking authentication tokens or cookies</li><li>Redirecting users to the correct page</li><li>Adding headers or lightweight modifications</li><li>Handling A/B testing, feature flags, or geolocation-based routing</li></ul><h4>❌ What it’s not for:</h4><ul><li>Fetching data from your database</li><li>Performing heavy computations</li><li>Running complex business logic</li></ul><p>Why? Because <strong>Edge Runtime is not a full Node.js server</strong>. It doesn’t support filesystem access, TCP connections, or heavy processing it’s lightweight and fast, like a bouncer at the club door, not the bartender serving drinks.</p><h3>How It’s Different from Express Middleware</h3><p>Express middleware is <strong>flexible and full-powered</strong>: you can access databases, run computations, and call APIs directly.</p><p>Next.js Middleware (soon to be renamed <strong>Proxy</strong>) is <strong>specialized for routing and request manipulation</strong>.</p><p>So if you tried writing await db.query() inside Next.js Middleware, you’d get an error. That’s the main point of confusion.</p><h3>Why the Name Change to Proxy Makes Sense</h3><p>Calling it “Middleware” led many developers to assume it behaves like Express middleware which it doesn’t.</p><p>Next.js is now renaming it to <strong>Proxy</strong>, which is much clearer:</p><ul><li>It proxies requests, checks headers, rewrites URLs, and redirects users.</li><li>It’s not a general-purpose server function.</li></ul><p>This resolves the <strong>naming confusion</strong> and gives developers a better mental model of what this piece of code actually does.</p><h3>Takeaways</h3><ol><li>Next.js Middleware is <strong>lightweight, fast, and runs at the edge</strong>.</li><li>It’s <strong>not a full server</strong> like Express middleware.</li><li>The renaming to <strong>Proxy</strong> solves the mental model issue.</li><li>Use it for <strong>routing, headers, redirects, and auth checks</strong>, but <strong>not heavy computations or DB queries</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWsBFaaEDDLZKaiBc2GF2g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad740bbec9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Polar Payments for Subscriptions and One-Time Payments in Next.js]]></title>
            <link>https://medium.com/@paudelronish/how-to-integrate-polar-payments-for-subscriptions-and-one-time-payments-in-next-js-fc79da765379?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc79da765379</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[polar]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[stripe-integration]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 17:35:51 GMT</pubDate>
            <atom:updated>2025-09-16T17:35:51.458Z</atom:updated>
            <content:encoded><![CDATA[<p>Firstly, let’s get introduced to <strong>Polar</strong>.<br> So, what exactly is Polar?</p><p>Polar is an <strong>open-source billing infrastructure platform</strong> designed specifically for developers, designers, and digital creators who want to monetize their products without the complexity of traditional payment systems. On top of that, it offers <strong>20% lower fees</strong> compared to traditional solutions making it not just developer-friendly, but also cost-effective.</p><p>With Polar, you don’t have to worry about reinventing payments. It handles <strong>both recurring subscriptions and one-time payments</strong> automatically, and all you need to do is plug into its clean <strong>API + webhook system</strong>.In this guide, we’ll walk through:</p><ul><li>Setting up a checkout flow</li><li>Handling webhooks for subscription creation</li><li>Mapping checkouts to payments in your backend</li><li>Implementing subscription revocation (cancellation)</li><li>Handling both recurring and one-time payments</li></ul><p>By the end, you’ll have a working subscription + payment integration in <strong>Next.js</strong> using the official <strong>Polar SDK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaMJ0z1WvjVrUr2aBcH_bg.png" /></figure><h3>1. Prerequisites</h3><ul><li>A <strong>Next.js app</strong> (with API routes or Route Handlers)</li><li><strong>Prisma</strong> or any database for tracking payments</li><li>A <strong>Polar account</strong> (sandbox environment works locally)</li><li><strong>Ngrok</strong> (for local webhook testing)</li></ul><h3>2. Creating a Checkout</h3><p>When a user clicks “Buy”, you’ll create a Polar checkout session.</p><pre>// src/lib/polar.ts<br>import { Polar } from &quot;@polar-sh/sdk&quot;;<br><br>export const polarApi = new Polar({<br>  accessToken: process.env.POLAR_ACCESS_TOKEN!,<br>  server: process.env.NODE_ENV === &quot;production&quot; ? &quot;production&quot; : &quot;sandbox&quot;,<br>});</pre><p>Now, generate a checkout:</p><pre>import { polarApi } from &quot;@/lib/polar&quot;;<br><br>export async function createCheckout(email: string) {<br>  const checkout = await polarApi.checkouts.create({<br>    productId: process.env.POLAR_PRODUCT_ID!, // recurring OR one-time<br>    customerEmail: email,<br>    successUrl: &quot;http://localhost:3000/success&quot;,<br>    cancelUrl: &quot;http://localhost:3000/cancel&quot;,<br>  });<br><br>  return checkout.url;<br>}</pre><p>👉 <strong>Important:</strong> Store checkout.id in your backend before redirecting the user.</p><h3>3. Handling Webhooks</h3><p>Polar notifies your backend about payments and subscriptions using <strong>webhooks</strong>.</p><p>Set up your webhook handler in Next.js with <strong>@polar-sh/nextjs</strong>:</p><pre>// app/api/webhook/polar/route.ts<br>import { Webhooks } from &quot;@polar-sh/nextjs&quot;;<br>import { prisma } from &quot;@/lib/db&quot;;<br><br>export const POST = Webhooks({<br>  webhookSecret: process.env.POLAR_WEBHOOK_SECRET!,<br>  onPayload: async (payload) =&gt; {<br>    console.log(&quot;🔔 Webhook received:&quot;, payload.type);<br><br>    if (payload.type === &quot;subscription.created&quot;) {<br>      const subscription = payload.data;<br>      const checkoutId = subscription.checkoutId;<br><br>      if (checkoutId) {<br>        await prisma.payment.updateMany({<br>          where: { checkoutId },<br>          data: { subscriptionId: subscription.id },<br>        });<br>        console.log(&quot;✅ Subscription linked to payment&quot;);<br>      }<br>    }<br><br>    if (payload.type === &quot;checkout.updated&quot;) {<br>      const checkout = payload.data;<br>      await prisma.payment.updateMany({<br>        where: { checkoutId: checkout.id },<br>        data: { status: checkout.status },<br>      });<br>      console.log(&quot;✅ Checkout updated:&quot;, checkout.status);<br>    }<br>  },<br>});</pre><h3>Webhook Setup in Polar Dashboard</h3><p>Go to <strong>Polar → Settings → Webhooks</strong> and set your endpoint:</p><ul><li><strong>Live:</strong> <a href="https://yourdomain.com/api/webhook/polar">https://yourdomain.com/api/webhook/polar</a></li><li><strong>Local (Ngrok):</strong> <a href="https://your-ngrok-url.ngrok-free.app/api/webhook/polar">https://your-ngrok-url.ngrok-free.app/api/webhook/polar</a></li></ul><p>This ensures Polar can notify your app when subscriptions or one-time payments are created.</p><h3>4. Canceling (Revoking) a Subscription</h3><p>To let users unsubscribe, call Polar’s API from your backend:</p><pre>// src/lib/cancelSubscription.ts<br>import { polarApi } from &quot;@/lib/polar&quot;;<br><br>export async function cancelSubscription(subscriptionId: string) {<br>  try {<br>    await polarApi.subscriptions.cancel(<br>      process.env.POLAR_ORG_ID!, <br>      subscriptionId<br>    );<br>    console.log(&quot;🛑 Subscription canceled:&quot;, subscriptionId);<br>  } catch (err: any) {<br>    console.error(&quot;❌ Cancel failed:&quot;, err.response?.data || err.message);<br>  }<br>}</pre><h3>5. Handling Recurring vs One-Time Payments</h3><ul><li><strong>Recurring (Subscription)</strong></li></ul><ol><li>User goes through checkout.</li><li>subscription.created webhook fires → link subscription to backend record.</li><li>Polar automatically manages recurring invoices/renewals.</li></ol><ul><li><strong>One-Time (Checkout)</strong></li></ul><ol><li>User completes checkout.</li><li>checkout.updated webhook fires → mark payment as completed.</li><li>No subscription record is created.</li></ol><p>👉 You don’t need to manually check if it’s one-time or recurring — <strong>Polar recognizes it from the product config</strong>.</p><h3>6. Testing Locally with Ngrok</h3><p>Run:</p><pre>npx ngrok http 3000</pre><p>Copy the HTTPS forwarding URL and set it as your webhook in Polar:</p><pre>https://random-id.ngrok-free.app/api/webhook/polar</pre><h3>7. Key Learnings</h3><ul><li>Always map checkoutId → your backend records.</li><li>Webhooks are the source of truth (not client-side).</li><li>Subscriptions require both checkout.updated and subscription.created handling.</li><li>Cancellations require both organizationId and subscriptionId.</li><li>We’re using the official <strong>Next.js Polar SDK</strong> for clean integration.</li></ul><h3>8. Final Thoughts</h3><p>With this setup, you now have a <strong>production-ready payment system</strong> in Next.js:<br> ✅ Subscriptions with recurring billing<br> ✅ One-time purchases<br> ✅ Backend-backed checkout mapping<br> ✅ Webhook handling<br> ✅ Subscription revocation</p><p>Polar keeps your payment flow robust and developer-friendly, while you focus on building your actual product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7M-Kqu8RY47cz_XRfNXjg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc79da765379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simplest Error Reporting Guide.]]></title>
            <link>https://medium.com/@paudelronish/ever-been-hit-with-a-error-like-cannot-read-property-x-of-undefined-in-production-and-had-no-043d9b159128?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/043d9b159128</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Sun, 25 May 2025 04:49:04 GMT</pubDate>
            <atom:updated>2025-05-26T03:38:43.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As developers, we all encounter errors. But not all errors are created equal especially when working with client-server architectures.</p><p>Ever been hit with a error like &quot;Cannot read property &#39;x&#39; of undefined&quot; in production and had no clue where it came from?<br> I have and it wasted <strong>hours</strong> of my time.</p><p>That all changed when I started sending <strong>real-time error alerts to Telegram</strong>, and more importantly, when I <strong>attached context IDs</strong> like product_83792 or user_129. Debugging became instant.</p><p>In this post, I’ll show you how to go from <strong>“What just broke?”</strong> to <strong>“I know exactly which product failed” </strong>in seconds.In this post, I’ll walk through:</p><ul><li>Why separating client and server error reporting matters,</li><li>How I use Telegram bots to send real-time alerts,</li><li>Why attaching a unique contextId (like product or user ID) helps debug and prioritize faster</li></ul><figure><img alt="err-tracking" src="https://cdn-images-1.medium.com/max/839/1*MnnCR4vNUMylV3F0Yifr0g.png" /></figure><h3>Why Split Client and Server Error Reporting?</h3><p>Client-side errors are usually tied to:</p><ul><li>UI bugs</li><li>Device/browser issues</li><li>User interactions</li></ul><p>Server-side errors usually deal with:</p><ul><li>API failures</li><li>Database issues</li><li>Business logic problems</li></ul><p><strong>Separation helps with triage.</strong> Server issues might need hotfixes, while client bugs may be due to unsupported environments.</p><h3>🚨 Real-Time Alerts via Telegram</h3><p>To streamline the alert process, I built a small utility in Node.js that sends structured error logs to a <strong>Telegram channel</strong>.</p><p>Here’s a snippet:</p><pre>export async function sendErrorToTelegram(<br> error: Error,<br> context?: string,<br> contextId?: string<br>): Promise&lt;void&gt; {<br> …<br> const errorMessage = `<br>🚨 Server Error Detected 🚨<br>Context: ${context || &quot;Unknown&quot;}<br>Context ID: ${contextId || &quot;N/A&quot;}<br>Error Message: ${error.message}<br>Stack Trace: ${error.stack || &quot;No stack trace available&quot;}<br>Timestamp: ${new Date().toISOString()}<br> `;<br> …<br>}</pre><p>This function uses Telegram’s Bot API to notify a group or thread instantly when something fails on the server.</p><h3>🧩 Why You Must Include a Context ID</h3><p>Imagine running an e-commerce store and getting the following alert:</p><blockquote><em>Error Message: “Cannot read property </em><em>price of undefined&quot;</em></blockquote><p>Now imagine this happens in a batch of 1,000 products. Without knowing <strong>which product</strong>, you’re hunting in the dark.</p><p>By attaching a contextId, like the <strong>product ID</strong>, you get:</p><ul><li>Faster debugging</li><li>Direct traceability</li><li>Easier grouping of repeated issues</li><li>Accountability and audit trail</li></ul><p>Example alert with contextId:</p><pre>Context: ProductService<br>Context ID: product_87239<br>Error Message: Cannot read property `price` of undefined</pre><p>Now you know exactly which service and product are impacted.</p><h3>🔐 Escape Markdown Gotchas</h3><p>Telegram’s MarkdownV2 requires escaping special characters. To ensure smooth formatting, I added this line:</p><pre>const escapedText = errorMessage.replace(/[_*[\]()~`&gt;#+=|{}.!-]/g, &quot;\\$&amp;&quot;);</pre><p>Without this, your logs can break formatting or fail to send.</p><h3>💬 Conclusion</h3><p><strong>Context-aware error logging isn’t just a “nice to have” — it’s essential for debugging efficiently in production.</strong><br> Whether you’re building SaaS, mobile apps, or internal tools, a small detail like adding a contextId can save you hours of guesswork.</p><p>Yes, you can (and should) use tools like <strong>Sentry</strong>, <strong>LogRocket</strong>, or <strong>Datadog</strong> for robust monitoring.<br> But for showcasing and instant alerts, I wired up <strong>Telegram</strong> to DM me every time my server messes up — complete with context and ID.</p><p>Because let’s be honest:</p><blockquote>“Cannot read property ‘x’ of undefined”<em><br> …is useless if you don’t know </em>where<em> it happened.</em></blockquote><p>Let your monitoring work <em>for</em> you, not against you.</p><h3>🔗 TL;DR</h3><ul><li>Separate client and server logs</li><li>Add context and contextId to every error</li><li>Use real-time reporting tools like Telegram</li><li>Escape special characters for proper formatting</li></ul><p>#ErrorMonitoring #Debugging #DevTips #TelegramBot #FullStackDev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=043d9b159128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stream Like a Pro, Secure Like a Fortress: The Simplest Guide to HLS Multi-Quality Encoding]]></title>
            <link>https://medium.com/@paudelronish/stream-like-a-pro-secure-like-a-fortress-the-ultimate-guide-to-hls-multi-quality-encoding-92fb02db62e5?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/92fb02db62e5</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 10:08:59 GMT</pubDate>
            <atom:updated>2025-02-19T08:30:51.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s streaming landscape, viewers expect Netflix-quality experiences on everything from 4K TVs to smartphones on spotty cellular connections. Meanwhile, content creators need robust protection against increasingly sophisticated piracy attempts. The solution? HTTP Live Streaming (HLS) with adaptive quality encoding and security-focused segmentation.</p><p>This comprehensive guide will walk you through building a production-ready video streaming platform with Express.js and AWS S3, complete with multi-quality encoding and security features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*EIS__-rMQduWxKCKZUKMkg.png" /></figure><h3>What is HLS and Why It Matters</h3><p>HTTP Live Streaming (HLS) is a protocol developed by Apple that has become the industry standard for video streaming. Unlike progressive download (where viewers download the entire file), HLS works by breaking videos into small segments (.ts files) that are delivered via HTTP. A manifest file (.m3u8) tells the player which segments to request based on network conditions.</p><p>The key advantages of HLS include:</p><p>— Adaptive bitrate streaming: Viewers automatically get the highest quality their connection can handle</p><p>— Broad compatibility: Works across devices without plugins</p><p>— Improved security: Segmentation makes unauthorized copying more difficult</p><p>— Efficient delivery: Only sends what viewers need, when they need it</p><h3>Setting Up Your Express Server</h3><p>First, let’s create the Express server that will handle video uploads and processing:</p><pre>// server.ts<br><br>import express from &#39;express&#39;;<br>import multer from &#39;multer&#39;;<br>import { uploadVideoController } from &#39;./controllers/videoController&#39;;<br><br>const app = express();<br>const upload = multer({<br>  storage: multer.memoryStorage(),<br>  limits: {<br>    fileSize: 1024 * 1024 * 1024, // 1GB limit<br>  },<br>});<br><br>// Video upload endpoint<br>app.post(&#39;/api/videos/upload&#39;,<br>  upload.single(&#39;video&#39;),<br>  uploadVideoController<br>);<br>// Error handling middleware<br>app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) =&gt; {<br>  console.error(&#39;🔥 Server error:&#39;, err);<br>  res.status(500).json({<br>    success: false,<br>    message: &#39;Internal server error&#39;,<br>    error: process.env.NODE_ENV === &#39;development&#39; ? err.message : undefined<br>  });<br>});<br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`🚀 Server running on port ${PORT}`);<br>});</pre><h3>The Magic of Multi-Quality Encoding</h3><p>The power of HLS lies in its ability to serve different quality levels from a single source video. Through FFmpeg’s encoding capabilities, we can create multiple renditions (360p, 720p, 1080p) that the player can seamlessly switch between, ensuring viewers on mobile get lighter files while those on high-speed connections enjoy full HD.</p><h3>Configuration Setup</h3><p>Before diving into the implementation, let’s set up our AWS configuration:</p><pre>// config/index.ts<br>import { S3Client } from &quot;@aws-sdk/client-s3&quot;;<br><br>export const BUCKET_NAME = process.env.AWS_BUCKET_NAME;<br>export const s3 = new S3Client({<br>  region: process.env.AWS_REGION,<br>  credentials: {<br>    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,<br>    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,<br>  },<br>});</pre><h3>Quality Profiles</h3><p>Our implementation supports multiple quality levels to ensure optimal viewing across devices:</p><pre>const videoQualities = [<br>  {<br>    name: &quot;360p&quot;,<br>    height: 360,<br>    bitrate: &quot;800k&quot;,<br>    maxrate: &quot;856k&quot;,<br>    bufsize: &quot;1200k&quot;,<br>  },<br>  {<br>    name: &quot;720p&quot;, <br>    height: 720,<br>    bitrate: &quot;2500k&quot;,<br>    maxrate: &quot;2675k&quot;,<br>    bufsize: &quot;3750k&quot;,<br>  },<br>  {<br>    name: &quot;1080p&quot;,<br>    height: 1080,<br>    bitrate: &quot;5000k&quot;,<br>    maxrate: &quot;5350k&quot;,<br>    bufsize: &quot;7500k&quot;,<br>  },<br>];</pre><p>Image showcasing how the ffmpeg convert quality levels through one video:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*nPs6cPvwVmeouoal1Cu3ZQ.png" /></figure><h3>Advanced Video Processing Pipeline</h3><h3>FFmpeg Integration</h3><p>Our solution uses FFmpeg for video processing. Here’s how we ensure FFmpeg is available:</p><pre>async function checkFFmpeg(): Promise&lt;void&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const ffmpeg = spawn(&quot;ffmpeg&quot;, [&quot;-version&quot;]);<br>    ffmpeg.on(&quot;error&quot;, (error) =&gt; {<br>      if (error.message.includes(&quot;ENOENT&quot;)) {<br>        reject(new Error(&quot;FFmpeg is not installed or not found in system PATH&quot;));<br>      } else {<br>        reject(error);<br>      }<br>    });<br>    ffmpeg.on(&quot;close&quot;, (code) =&gt; {<br>      if (code === 0) {<br>        resolve();<br>      } else {<br>        reject(new Error(`FFmpeg check failed with code ${code}`));<br>      }<br>    });<br>  });<br>}</pre><h3>Segment Generation</h3><p>The heart of our HLS implementation is the segment generation process:</p><pre>async function convertToHLSSegments(<br>  videoBuffer: Buffer,<br>  outputDir: string<br>): Promise&lt;Record&lt;string, Buffer&gt;&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const segments: Record&lt;string, Buffer&gt; = {};<br>    const inputPath = path.join(outputDir, `input_${Date.now()}.mp4`);<br><br>    try {<br>      fs.writeFileSync(inputPath, videoBuffer);<br><br>      // Generate master playlist content<br>      const masterPlaylistContent =<br>        &quot;#EXTM3U\n#EXT-X-VERSION:3\n&quot; +<br>        videoQualities<br>          .map(<br>            (quality) =&gt;<br>              `#EXT-X-STREAM-INF:BANDWIDTH=${<br>                parseInt(quality.bitrate) * 1000<br>              },RESOLUTION=${quality.height}p\n${quality.name}.m3u8`<br>          )<br>          .join(&quot;\n&quot;);<br><br>      // Write master playlist<br>      fs.writeFileSync(<br>        path.join(outputDir, &quot;master.m3u8&quot;),<br>        masterPlaylistContent<br>      );<br><br>      const ffmpegArgs = [<br>        &quot;-i&quot;,<br>        inputPath,<br>        &quot;-preset&quot;,<br>        &quot;veryfast&quot;,<br>        &quot;-tune&quot;,<br>        &quot;fastdecode&quot;,<br>        &quot;-sc_threshold&quot;,<br>        &quot;0&quot;,<br>        &quot;-g&quot;,<br>        &quot;48&quot;,<br>        &quot;-keyint_min&quot;,<br>        &quot;48&quot;,<br>        &quot;-movflags&quot;,<br>        &quot;+faststart&quot;,<br>      ];<br><br>      // Add arguments for each quality<br>      videoQualities.forEach((quality) =&gt; {<br>        ffmpegArgs.push(<br>          &quot;-vf&quot;,<br>          `scale=-2:${quality.height}`,<br>          &quot;-c:v&quot;,<br>          &quot;libx264&quot;,<br>          &quot;-profile:v&quot;,<br>          &quot;main&quot;,<br>          &quot;-crf&quot;,<br>          &quot;23&quot;,<br>          &quot;-maxrate&quot;,<br>          quality.maxrate,<br>          &quot;-bufsize&quot;,<br>          quality.bufsize,<br>          &quot;-c:a&quot;,<br>          &quot;aac&quot;,<br>          &quot;-ar&quot;,<br>          &quot;48000&quot;,<br>          &quot;-b:a&quot;,<br>          &quot;128k&quot;,<br>          &quot;-ac&quot;,<br>          &quot;2&quot;,<br>          &quot;-hls_time&quot;,<br>          &quot;10&quot;,<br>          &quot;-hls_playlist_type&quot;,<br>          &quot;vod&quot;,<br>          &quot;-hls_segment_filename&quot;,<br>          path.join(outputDir, `${quality.name}_%03d.ts`),<br>          &quot;-hls_flags&quot;,<br>          &quot;independent_segments&quot;,<br>          path.join(outputDir, `${quality.name}.m3u8`)<br>        );<br>      });<br><br>      const ffmpegProcess = spawn(&quot;ffmpeg&quot;, ffmpegArgs);<br><br>      let errorOutput = &quot;&quot;;<br><br>      ffmpegProcess.stderr.on(&quot;data&quot;, (data) =&gt; {<br>        errorOutput += data.toString();<br>        console.log(`FFmpeg progress: ${data}`);<br>      });<br><br>      ffmpegProcess.on(&quot;close&quot;, (code) =&gt; {<br>        try {<br>          if (code !== 0) {<br>            throw new Error(<br>              `FFmpeg process exited with code ${code}\nError output: ${errorOutput}`<br>            );<br>          }<br><br>          // Read all generated files<br>          const files = fs.readdirSync(outputDir);<br>          for (const file of files) {<br>            if (file.endsWith(&quot;.ts&quot;) || file.endsWith(&quot;.m3u8&quot;)) {<br>              segments[file] = fs.readFileSync(path.join(outputDir, file));<br>            }<br>          }<br>          resolve(segments);<br>        } catch (error) {<br>          reject(error);<br>        } finally {<br>          // Clean up input file<br>          if (fs.existsSync(inputPath)) {<br>            fs.unlinkSync(inputPath);<br>          }<br>        }<br>      });<br><br>      ffmpegProcess.on(&quot;error&quot;, (error) =&gt; {<br>        reject(new Error(`FFmpeg process error: ${error.message}`));<br>      });<br>    } catch (error) {<br>      reject(error);<br>    }<br>  });<br>}</pre><h3><strong>Upload to AWS S3</strong></h3><pre>async function uploadToS3(<br>  segments: Record&lt;string, Buffer&gt;,<br>  hlsKey: string<br>): Promise&lt;void&gt; {<br>  const uploadPromises = Object.entries(segments).map(([filename, data]) =&gt; {<br>    const upload = new Upload({<br>      client: s3,<br>      params: {<br>        Bucket: BUCKET_NAME,<br>        Key: `${hlsKey}/${filename}`,<br>        Body: data,<br>        ContentType: filename.endsWith(&quot;.m3u8&quot;)<br>          ? &quot;application/x-mpegURL&quot;<br>          : &quot;video/MP2T&quot;,<br>      },<br>      tags: [{ Key: &quot;videoId&quot;, Value: hlsKey.split(&quot;/&quot;)[1] }],<br>      queueSize: 4,<br>      partSize: 1024 * 1024 * 5,<br>    });<br><br>    upload.on(&quot;httpUploadProgress&quot;, (progress) =&gt; {<br>      console.log(<br>        `Progress for ${filename}: ${(<br>          ((progress.loaded || 0) / (progress.total || 1)) *<br>          100<br>        ).toFixed(2)}%`<br>      );<br>    });<br><br>    return upload.done();<br>  });<br><br>  await Promise.all(uploadPromises);<br>}</pre><h3>Security Features</h3><h4>Input Validation</h4><p>We implement strict input validation to prevent security issues:</p><pre>function validateFile(file: Express.Multer.File): void {<br>  const allowedTypes = [&quot;video/mp4&quot;, &quot;video/quicktime&quot;, &quot;video/x-msvideo&quot;];<br>  if (!allowedTypes.includes(file.mimetype)) {<br>    throw new Error(&quot;Invalid file type. Only MP4, AVI, and MOV are allowed&quot;);<br>  }<br>  const fileSizeMB = file.buffer.length / (1024 * 1024);<br>  if (fileSizeMB &gt; MAX_VIDEO_SIZE_MB) {<br>    throw new Error(`File too large. Maximum size is ${MAX_VIDEO_SIZE_MB}MB`);<br>  }<br>}</pre><p>Image to showcasing how video processing work and being uploaded to AWS S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*wnhUQt-Mq9K0ASTIq0WrNw.png" /></figure><h3><strong>Full Version of the code:</strong></h3><pre>import { Upload } from &quot;@aws-sdk/lib-storage&quot;;<br>import { s3, BUCKET_NAME } from &quot;../config&quot;;<br>import type { Request, Response } from &quot;express&quot;;<br>import { spawn } from &quot;child_process&quot;;<br>import * as fs from &quot;fs&quot;;<br>import * as path from &quot;path&quot;;<br>import * as crypto from &quot;crypto&quot;;<br><br>const TEMP_DIR = path.join(process.cwd(), &quot;temp&quot;);<br>const MAX_VIDEO_SIZE_MB = 1024;<br><br>if (!fs.existsSync(TEMP_DIR)) {<br>  fs.mkdirSync(TEMP_DIR, { recursive: true });<br>}<br><br>const videoQualities = [<br>  {<br>    name: &quot;360p&quot;,<br>    height: 360,<br>    bitrate: &quot;800k&quot;,<br>    maxrate: &quot;856k&quot;,<br>    bufsize: &quot;1200k&quot;,<br>  },<br>  {<br>    name: &quot;720p&quot;,<br>    height: 720,<br>    bitrate: &quot;2500k&quot;,<br>    maxrate: &quot;2675k&quot;,<br>    bufsize: &quot;3750k&quot;,<br>  },<br>  {<br>    name: &quot;1080p&quot;,<br>    height: 1080,<br>    bitrate: &quot;5000k&quot;,<br>    maxrate: &quot;5350k&quot;,<br>    bufsize: &quot;7500k&quot;,<br>  },<br>];<br><br>async function checkFFmpeg(): Promise&lt;void&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const ffmpeg = spawn(&quot;ffmpeg&quot;, [&quot;-version&quot;]);<br><br>    ffmpeg.on(&quot;error&quot;, (error) =&gt; {<br>      if (error.message.includes(&quot;ENOENT&quot;)) {<br>        reject(<br>          new Error(&quot;FFmpeg is not installed or not found in system PATH&quot;)<br>        );<br>      } else {<br>        reject(error);<br>      }<br>    });<br><br>    ffmpeg.on(&quot;close&quot;, (code) =&gt; {<br>      if (code === 0) {<br>        resolve();<br>      } else {<br>        reject(new Error(`FFmpeg check failed with code ${code}`));<br>      }<br>    });<br>  });<br>}<br><br>function validateFile(file: Express.Multer.File): void {<br>  const allowedTypes = [&quot;video/mp4&quot;, &quot;video/quicktime&quot;, &quot;video/x-msvideo&quot;];<br>  if (!allowedTypes.includes(file.mimetype)) {<br>    throw new Error(&quot;Invalid file type. Only MP4, AVI, and MOV are allowed&quot;);<br>  }<br><br>  const fileSizeMB = file.buffer.length / (1024 * 1024);<br>  if (fileSizeMB &gt; MAX_VIDEO_SIZE_MB) {<br>    throw new Error(`File too large. Maximum size is ${MAX_VIDEO_SIZE_MB}MB`);<br>  }<br>}<br><br>// Main function to convert video to HLS segments<br>async function convertToHLSSegments(<br>  videoBuffer: Buffer,<br>  outputDir: string<br>): Promise&lt;Record&lt;string, Buffer&gt;&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const segments: Record&lt;string, Buffer&gt; = {};<br>    const inputPath = path.join(outputDir, `input_${Date.now()}.mp4`);<br><br>    try {<br>      fs.writeFileSync(inputPath, videoBuffer);<br><br>      // Generate master playlist content<br>      const masterPlaylistContent =<br>        &quot;#EXTM3U\n#EXT-X-VERSION:3\n&quot; +<br>        videoQualities<br>          .map(<br>            (quality) =&gt;<br>              `#EXT-X-STREAM-INF:BANDWIDTH=${<br>                parseInt(quality.bitrate) * 1000<br>              },RESOLUTION=${quality.height}p\n${quality.name}.m3u8`<br>          )<br>          .join(&quot;\n&quot;);<br><br>      // Write master playlist<br>      fs.writeFileSync(<br>        path.join(outputDir, &quot;master.m3u8&quot;),<br>        masterPlaylistContent<br>      );<br><br>      const ffmpegArgs = [<br>        &quot;-i&quot;,<br>        inputPath,<br>        &quot;-preset&quot;,<br>        &quot;veryfast&quot;,<br>        &quot;-tune&quot;,<br>        &quot;fastdecode&quot;,<br>        &quot;-sc_threshold&quot;,<br>        &quot;0&quot;,<br>        &quot;-g&quot;,<br>        &quot;48&quot;,<br>        &quot;-keyint_min&quot;,<br>        &quot;48&quot;,<br>        &quot;-movflags&quot;,<br>        &quot;+faststart&quot;,<br>      ];<br><br>      // Add arguments for each quality<br>      videoQualities.forEach((quality) =&gt; {<br>        ffmpegArgs.push(<br>          &quot;-vf&quot;,<br>          `scale=-2:${quality.height}`,<br>          &quot;-c:v&quot;,<br>          &quot;libx264&quot;,<br>          &quot;-profile:v&quot;,<br>          &quot;main&quot;,<br>          &quot;-crf&quot;,<br>          &quot;23&quot;,<br>          &quot;-maxrate&quot;,<br>          quality.maxrate,<br>          &quot;-bufsize&quot;,<br>          quality.bufsize,<br>          &quot;-c:a&quot;,<br>          &quot;aac&quot;,<br>          &quot;-ar&quot;,<br>          &quot;48000&quot;,<br>          &quot;-b:a&quot;,<br>          &quot;128k&quot;,<br>          &quot;-ac&quot;,<br>          &quot;2&quot;,<br>          &quot;-hls_time&quot;,<br>          &quot;10&quot;,<br>          &quot;-hls_playlist_type&quot;,<br>          &quot;vod&quot;,<br>          &quot;-hls_segment_filename&quot;,<br>          path.join(outputDir, `${quality.name}_%03d.ts`),<br>          &quot;-hls_flags&quot;,<br>          &quot;independent_segments&quot;,<br>          path.join(outputDir, `${quality.name}.m3u8`)<br>        );<br>      });<br><br>      const ffmpegProcess = spawn(&quot;ffmpeg&quot;, ffmpegArgs);<br><br>      let errorOutput = &quot;&quot;;<br><br>      ffmpegProcess.stderr.on(&quot;data&quot;, (data) =&gt; {<br>        errorOutput += data.toString();<br>        console.log(`FFmpeg progress: ${data}`);<br>      });<br><br>      ffmpegProcess.on(&quot;close&quot;, (code) =&gt; {<br>        try {<br>          if (code !== 0) {<br>            throw new Error(<br>              `FFmpeg process exited with code ${code}\nError output: ${errorOutput}`<br>            );<br>          }<br><br>          // Read all generated files<br>          const files = fs.readdirSync(outputDir);<br>          for (const file of files) {<br>            if (file.endsWith(&quot;.ts&quot;) || file.endsWith(&quot;.m3u8&quot;)) {<br>              segments[file] = fs.readFileSync(path.join(outputDir, file));<br>            }<br>          }<br>          resolve(segments);<br>        } catch (error) {<br>          reject(error);<br>        } finally {<br>          // Clean up input file<br>          if (fs.existsSync(inputPath)) {<br>            fs.unlinkSync(inputPath);<br>          }<br>        }<br>      });<br><br>      ffmpegProcess.on(&quot;error&quot;, (error) =&gt; {<br>        reject(new Error(`FFmpeg process error: ${error.message}`));<br>      });<br>    } catch (error) {<br>      reject(error);<br>    }<br>  });<br>}<br><br>// Helper function to upload segments to S3<br>async function uploadToS3(<br>  segments: Record&lt;string, Buffer&gt;,<br>  hlsKey: string<br>): Promise&lt;void&gt; {<br>  const uploadPromises = Object.entries(segments).map(([filename, data]) =&gt; {<br>    const upload = new Upload({<br>      client: s3,<br>      params: {<br>        Bucket: BUCKET_NAME,<br>        Key: `${hlsKey}/${filename}`,<br>        Body: data,<br>        ContentType: filename.endsWith(&quot;.m3u8&quot;)<br>          ? &quot;application/x-mpegURL&quot;<br>          : &quot;video/MP2T&quot;,<br>      },<br>      tags: [{ Key: &quot;videoId&quot;, Value: hlsKey.split(&quot;/&quot;)[1] }],<br>      queueSize: 4,<br>      partSize: 1024 * 1024 * 5,<br>    });<br><br>    upload.on(&quot;httpUploadProgress&quot;, (progress) =&gt; {<br>      console.log(<br>        `Progress for ${filename}: ${(<br>          ((progress.loaded || 0) / (progress.total || 1)) *<br>          100<br>        ).toFixed(2)}%`<br>      );<br>    });<br><br>    return upload.done();<br>  });<br><br>  await Promise.all(uploadPromises);<br>}<br><br>// Main controller function<br>export const uploadVideoController = async (req: Request, res: Response) =&gt; {<br>  const tempDir = path.join(TEMP_DIR, `hls_${Date.now()}`);<br>  fs.mkdirSync(tempDir, { recursive: true });<br><br>  try {<br>    // Check for FFmpeg installation<br>    await checkFFmpeg();<br><br>    const file = req.file;<br>    if (!file) {<br>      throw new Error(&quot;No file uploaded&quot;);<br>    }<br><br>    validateFile(file);<br><br>    // Generate unique ID and key for the video<br>    const videoId = crypto.randomBytes(16).toString(&quot;hex&quot;);<br>    const hlsKey = `hls/${videoId}`;<br><br>    // Convert video to HLS segments<br>    const segments = await convertToHLSSegments(file.buffer, tempDir);<br><br>    // Upload segments to S3<br>    console.log(&quot;📤 Uploading HLS segments to S3...&quot;);<br>    await uploadToS3(segments, hlsKey);<br><br>    const hlsUrl = `https://${BUCKET_NAME}.s3.${process.env.AWS_REGION}.amazonaws.com/${hlsKey}/master.m3u8`;<br><br>    return res.status(200).json({<br>      success: true,<br>      message: &quot;Video processed successfully&quot;,<br>      data: { hlsUrl, videoId },<br>    });<br>  } catch (error) {<br>    console.error(&quot;❌ Video processing error:&quot;, error);<br>    const errorMessage =<br>      error instanceof Error ? error.message : &quot;Failed to process video&quot;;<br>    return res.status(errorMessage.includes(&quot;Invalid file&quot;) ? 400 : 500).json({<br>      success: false,<br>      message: errorMessage,<br>    });<br>  } finally {<br>    // Clean up temporary directory<br>    if (fs.existsSync(tempDir)) {<br>      fs.rmSync(tempDir, { recursive: true, force: true });<br>    }<br>  }<br>};<br><br>export default { uploadVideoController };</pre><h3>Best Practices and Recommendations</h3><p><strong>1.Error Handling</strong></p><ul><li>Implement comprehensive error handling</li><li>Use appropriate HTTP status codes</li><li>Provide meaningful error messages</li></ul><ol><li><strong>Security</strong></li></ol><ul><li>Implement authentication for upload endpoints</li><li>Use signed URLs for S3 access</li><li>Validate file types and sizes</li></ul><ol><li><strong>Performance</strong></li></ol><ul><li>Use chunked uploads for large files</li><li>Implement retry mechanisms</li><li>Consider using a CDN</li></ul><ol><li><strong>Monitoring</strong></li></ol><ul><li>Track processing times</li><li>Monitor S3 usage</li><li>Set up alerts for failures</li></ul><h3>Conclusion</h3><p>This implementation provides a robust foundation for a production-ready video streaming platform. Key benefits include:</p><ul><li>Adaptive quality streaming</li><li>Secure content delivery</li><li>Scalable architecture</li><li>Production-ready error handling</li><li>Progress tracking</li><li>Cloud storage integration</li></ul><p>Additionally, this is a simple way for video processing, converting to HLS. However, processing may be slow. To improve performance, we can use a Redis queue with a master-worker pattern in Express.js, along with various FFmpeg arguments like threads, hardware acceleration (hwaccel), and more.</p><p>For next steps, consider implementing:</p><ul><li>User authentication</li><li>Content management system</li><li>Analytics tracking</li><li>Custom player interface</li><li>DRM integration</li></ul><p>The complete source code is available in the implementation sections above. Happy streaming! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92fb02db62e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stream Like a Pro, Secure Like a Fortress:The Simplest Guide to HLS Multi-Quality Encoding]]></title>
            <link>https://medium.com/@paudelronish/stream-like-a-pro-secure-like-a-fortress-the-ultimate-guide-to-hls-multi-quality-encoding-45a0bba26416?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a0bba26416</guid>
            <category><![CDATA[vi̇deo]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[video-streaming-service]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 10:07:51 GMT</pubDate>
            <atom:updated>2025-02-19T08:32:44.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stream Like a Pro, Secure Like a Fortress: The Simplest Guide to HLS Multi-Quality Encoding</h3><h3>Introduction</h3><p>Yo guide ma, tapaai haru lai ma Express.js ra AWS S3 sanga production-ready video streaming platform kasari banaune vanera bujhaune chu, jasma multi-quality encoding ra security features haru pani cha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*EIS__-rMQduWxKCKZUKMkg.png" /></figure><h3>What is HLS and Why It Matters</h3><p>HTTP Live Streaming (HLS) is a protocol developed by Apple that has become the industry standard for video streaming. Unlike progressive download (where viewers download the entire file), HLS works by breaking videos into small segments (.ts files) that are delivered via HTTP. A manifest file (.m3u8) tells the player which segments to request based on network conditions.</p><p>The key advantages of HLS include:</p><p>Adaptive bitrate streaming: Viewers automatically get the highest quality their connection can handle</p><p>Broad compatibility: Works across devices without plugins</p><p>Improved security: Segmentation makes unauthorized copying more difficult</p><p>Efficient delivery: Only sends what viewers need, when they need it</p><h3>Setting Up Your Express Server</h3><p>Sabai bhanda pahila, Express server setup garne, jasle video uploads ra processing handle grxa:</p><pre>// server.ts<br>import express from &#39;express&#39;;<br>import multer from &#39;multer&#39;;<br>import { uploadVideoController } from &#39;./controllers/videoController&#39;;<br><br>const app = express();<br>const upload = multer({<br>  storage: multer.memoryStorage(),<br>  limits: {<br>    fileSize: 1024 * 1024 * 1024, // 1GB limit<br>  },<br>});<br><br>// Video upload endpoint<br>app.post(&#39;/api/videos/upload&#39;,<br>  upload.single(&#39;video&#39;),<br>  uploadVideoController<br>);<br><br>// Error handling middleware<br>app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) =&gt; {<br>  console.error(&#39;🔥 Server error:&#39;, err);<br>  res.status(500).json({<br>    success: false,<br>    message: &#39;Internal server error&#39;,<br>    error: process.env.NODE_ENV === &#39;development&#39; ? err.message : undefined<br>  });<br>});<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`🚀 Server running on port ${PORT}`);<br>});</pre><h3>The Magic of Multi-Quality Encoding</h3><p><strong>Configuration Setup</strong></p><p>AWS configuration setup garnu bhanda pahila hamle, config file ma sabai required values haru rakhne:</p><pre>// config/index.ts<br>import { S3Client } from &quot;@aws-sdk/client-s3&quot;;<br><br>export const BUCKET_NAME = process.env.AWS_BUCKET_NAME;<br>export const s3 = new S3Client({<br>  region: process.env.AWS_REGION,<br>  credentials: {<br>    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,<br>    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,<br>  },<br>});</pre><p><strong>Quality Profiles</strong></p><p>Yaha, hami euta video like diff quality ma encode garchau jastai ki 360p, 720p ani 1080p ma:</p><pre>const videoQualities = [<br>  {<br>    name: &quot;360p&quot;,<br>    height: 360,<br>    bitrate: &quot;800k&quot;,<br>    maxrate: &quot;856k&quot;,<br>    bufsize: &quot;1200k&quot;,<br>  },<br>  {<br>    name: &quot;720p&quot;, <br>    height: 720,<br>    bitrate: &quot;2500k&quot;,<br>    maxrate: &quot;2675k&quot;,<br>    bufsize: &quot;3750k&quot;,<br>  },<br>  {<br>    name: &quot;1080p&quot;,<br>    height: 1080,<br>    bitrate: &quot;5000k&quot;,<br>    maxrate: &quot;5350k&quot;,<br>    bufsize: &quot;7500k&quot;,<br>  },<br>];</pre><p>Esari hamro original video chai diff quality haru ma encode vayi aauxa</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*nPs6cPvwVmeouoal1Cu3ZQ.png" /></figure><h3>Advanced Video Processing Pipeline</h3><p><strong>FFmpeg Integration</strong></p><p>Yo code le FFmpeg naam ko video processing software system ma cha ki chaina vani check garxa:</p><pre>async function checkFFmpeg(): Promise&lt;void&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const ffmpeg = spawn(&quot;ffmpeg&quot;, [&quot;-version&quot;]);<br>    ffmpeg.on(&quot;error&quot;, (error) =&gt; {<br>      if (error.message.includes(&quot;ENOENT&quot;)) {<br>        reject(new Error(&quot;FFmpeg is not installed or not found in system PATH&quot;));<br>      } else {<br>        reject(error);<br>      }<br>    });<br>    ffmpeg.on(&quot;close&quot;, (code) =&gt; {<br>      if (code === 0) {<br>        resolve();<br>      } else {<br>        reject(new Error(`FFmpeg check failed with code ${code}`));<br>      }<br>    });<br>  });<br>}</pre><p><strong>Segment Generation</strong></p><p>HLS segment generation ko main function cha convertToHLSSegments, jun video buffer lai segments ma convert garxa. Yaha master playlist content pani generate hunxa. master playlist bhitra hamro diff quality level haru video ko hunxa tei master playlist use gari hami quality level access garna sakchau.</p><pre>async function convertToHLSSegments(<br>  videoBuffer: Buffer,<br>  outputDir: string<br>): Promise&lt;Record&lt;string, Buffer&gt;&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const segments: Record&lt;string, Buffer&gt; = {};<br>    const inputPath = path.join(outputDir, `input_${Date.now()}.mp4`);<br><br>    try {<br>      fs.writeFileSync(inputPath, videoBuffer);<br><br>      const masterPlaylistContent =<br>        &quot;#EXTM3U\n#EXT-X-VERSION:3\n&quot; +<br>        videoQualities<br>          .map(<br>            (quality) =&gt;<br>              `#EXT-X-STREAM-INF:BANDWIDTH=${<br>                parseInt(quality.bitrate) * 1000<br>              },RESOLUTION=${quality.height}p\n${quality.name}.m3u8`<br>          )<br>          .join(&quot;\n&quot;);<br><br>      fs.writeFileSync(<br>        path.join(outputDir, &quot;master.m3u8&quot;),<br>        masterPlaylistContent<br>      );<br><br>      const ffmpegArgs = [<br>        &quot;-i&quot;,<br>        inputPath,<br>        &quot;-preset&quot;,<br>        &quot;veryfast&quot;,<br>        &quot;-tune&quot;,<br>        &quot;fastdecode&quot;,<br>        &quot;-sc_threshold&quot;,<br>        &quot;0&quot;,<br>        &quot;-g&quot;,<br>        &quot;48&quot;,<br>        &quot;-keyint_min&quot;,<br>        &quot;48&quot;,<br>        &quot;-movflags&quot;,<br>        &quot;+faststart&quot;,<br>      ];<br><br>      videoQualities.forEach((quality) =&gt; {<br>        ffmpegArgs.push(<br>          &quot;-vf&quot;,<br>          `scale=-2:${quality.height}`,<br>          &quot;-c:v&quot;,<br>          &quot;libx264&quot;,<br>          &quot;-profile:v&quot;,<br>          &quot;main&quot;,<br>          &quot;-crf&quot;,<br>          &quot;23&quot;,<br>          &quot;-maxrate&quot;,<br>          quality.maxrate,<br>          &quot;-bufsize&quot;,<br>          quality.bufsize,<br>          &quot;-c:a&quot;,<br>          &quot;aac&quot;,<br>          &quot;-ar&quot;,<br>          &quot;48000&quot;,<br>          &quot;-b:a&quot;,<br>          &quot;128k&quot;,<br>          &quot;-ac&quot;,<br>          &quot;2&quot;,<br>          &quot;-hls_time&quot;,<br>          &quot;10&quot;,<br>          &quot;-hls_playlist_type&quot;,<br>          &quot;vod&quot;,<br>          &quot;-hls_segment_filename&quot;,<br>          path.join(outputDir, `${quality.name}_%03d.ts`),<br>          &quot;-hls_flags&quot;,<br>          &quot;independent_segments&quot;,<br>          path.join(outputDir, `${quality.name}.m3u8`)<br>        );<br>      });<br><br>      const ffmpegProcess = spawn(&quot;ffmpeg&quot;, ffmpegArgs);<br><br>      let errorOutput = &quot;&quot;;<br><br>      ffmpegProcess.stderr.on(&quot;data&quot;, (data) =&gt; {<br>        errorOutput += data.toString();<br>        console.log(`FFmpeg progress: ${data}`);<br>      });<br><br>      ffmpegProcess.on(&quot;close&quot;, (code) =&gt; {<br>        try {<br>          if (code !== 0) {<br>            throw new Error(<br>              `FFmpeg process exited with code ${code}\nError output: ${errorOutput}`<br>            );<br>          }<br><br>          const files = fs.readdirSync(outputDir);<br>          for (const file of files) {<br>            if (file.endsWith(&quot;.ts&quot;) || file.endsWith(&quot;.m3u8&quot;)) {<br>              segments[file] = fs.readFileSync(path.join(outputDir, file));<br>            }<br>          }<br>          resolve(segments);<br>        } catch (error) {<br>          reject(error);<br>        } finally {<br>          if (fs.existsSync(inputPath)) {<br>            fs.unlinkSync(inputPath);<br>          }<br>        }<br>      });<br><br>      ffmpegProcess.on(&quot;error&quot;, (error) =&gt; {<br>        reject(new Error(`FFmpeg process error: ${error.message}`));<br>      });<br>    } catch (error) {<br>      reject(error);<br>    }<br>  });<br>}</pre><h3>Upload to AWS S3</h3><p>Video segments lai S3 ma upload garne function uploadToS3:</p><pre>async function uploadToS3(<br>  segments: Record&lt;string, Buffer&gt;,<br>  hlsKey: string<br>): Promise&lt;void&gt; {<br>  const uploadPromises = Object.entries(segments).map(([filename, data]) =&gt; {<br>    const upload = new Upload({<br>      client: s3,<br>      params: {<br>        Bucket: BUCKET_NAME,<br>        Key: `${hlsKey}/${filename}`,<br>        Body: data,<br>        ContentType: filename.endsWith(&quot;.m3u8&quot;)<br>          ? &quot;application/x-mpegURL&quot;<br>          : &quot;video/MP2T&quot;,<br>      },<br>      tags: [{ Key: &quot;videoId&quot;, Value: hlsKey.split(&quot;/&quot;)[1] }],<br>      queueSize: 4,<br>      partSize: 1024 * 1024 * 5,<br>    });<br><br>    upload.on(&quot;httpUploadProgress&quot;, (progress) =&gt; {<br>      console.log(<br>        `Progress for ${filename}: ${(<br>          ((progress.loaded || 0) / (progress.total || 1)) *<br>          100<br>        ).toFixed(2)}%`<br>      );<br>    });<br><br>    return upload.done();<br>  });<br><br>  await Promise.all(uploadPromises);<br>}</pre><p>esari hamro video process vayi aws s3 ma upload hunxa</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*wnhUQt-Mq9K0ASTIq0WrNw.png" /></figure><h3>Security Features</h3><p>File validation garna ko lagi use gariney function:</p><pre>function validateFile(file: Express.Multer.File): void {<br>  const allowedTypes = [&quot;video/mp4&quot;, &quot;video/quicktime&quot;, &quot;video/x-msvideo&quot;];<br>  if (!allowedTypes.includes(file.mimetype)) {<br>    throw new Error(&quot;Invalid file type. Only MP4, AVI, and MOV are allowed&quot;);<br>  }<br>  const fileSizeMB = file.buffer.length / (1024 * 1024);<br>  if (fileSizeMB &gt; MAX_VIDEO_SIZE_MB) {<br>    throw new Error(`File too large. Maximum size is ${MAX_VIDEO_SIZE_MB}MB`);<br>  }<br>}</pre><h3><strong>Full Version of the Code:</strong></h3><p>/controller/videoUploader.ts</p><pre>import { Upload } from &quot;@aws-sdk/lib-storage&quot;;<br>import { s3, BUCKET_NAME } from &quot;../config&quot;;<br>import type { Request, Response } from &quot;express&quot;;<br>import { spawn } from &quot;child_process&quot;;<br>import * as fs from &quot;fs&quot;;<br>import * as path from &quot;path&quot;;<br>import * as crypto from &quot;crypto&quot;;<br><br>const TEMP_DIR = path.join(process.cwd(), &quot;temp&quot;);<br>const MAX_VIDEO_SIZE_MB = 1024;<br><br>if (!fs.existsSync(TEMP_DIR)) {<br>  fs.mkdirSync(TEMP_DIR, { recursive: true });<br>}<br><br>const videoQualities = [<br>  {<br>    name: &quot;360p&quot;,<br>    height: 360,<br>    bitrate: &quot;800k&quot;,<br>    maxrate: &quot;856k&quot;,<br>    bufsize: &quot;1200k&quot;,<br>  },<br>  {<br>    name: &quot;720p&quot;,<br>    height: 720,<br>    bitrate: &quot;2500k&quot;,<br>    maxrate: &quot;2675k&quot;,<br>    bufsize: &quot;3750k&quot;,<br>  },<br>  {<br>    name: &quot;1080p&quot;,<br>    height: 1080,<br>    bitrate: &quot;5000k&quot;,<br>    maxrate: &quot;5350k&quot;,<br>    bufsize: &quot;7500k&quot;,<br>  },<br>];<br><br>async function checkFFmpeg(): Promise&lt;void&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const ffmpeg = spawn(&quot;ffmpeg&quot;, [&quot;-version&quot;]);<br><br>    ffmpeg.on(&quot;error&quot;, (error) =&gt; {<br>      if (error.message.includes(&quot;ENOENT&quot;)) {<br>        reject(<br>          new Error(&quot;FFmpeg is not installed or not found in system PATH&quot;)<br>        );<br>      } else {<br>        reject(error);<br>      }<br>    });<br><br>    ffmpeg.on(&quot;close&quot;, (code) =&gt; {<br>      if (code === 0) {<br>        resolve();<br>      } else {<br>        reject(new Error(`FFmpeg check failed with code ${code}`));<br>      }<br>    });<br>  });<br>}<br><br>function validateFile(file: Express.Multer.File): void {<br>  const allowedTypes = [&quot;video/mp4&quot;, &quot;video/quicktime&quot;, &quot;video/x-msvideo&quot;];<br>  if (!allowedTypes.includes(file.mimetype)) {<br>    throw new Error(&quot;Invalid file type. Only MP4, AVI, and MOV are allowed&quot;);<br>  }<br><br>  const fileSizeMB = file.buffer.length / (1024 * 1024);<br>  if (fileSizeMB &gt; MAX_VIDEO_SIZE_MB) {<br>    throw new Error(`File too large. Maximum size is ${MAX_VIDEO_SIZE_MB}MB`);<br>  }<br>}<br><br>// Main function to convert video to HLS segments<br>async function convertToHLSSegments(<br>  videoBuffer: Buffer,<br>  outputDir: string<br>): Promise&lt;Record&lt;string, Buffer&gt;&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const segments: Record&lt;string, Buffer&gt; = {};<br>    const inputPath = path.join(outputDir, `input_${Date.now()}.mp4`);<br><br>    try {<br>      fs.writeFileSync(inputPath, videoBuffer);<br><br>      // Generate master playlist content<br>      const masterPlaylistContent =<br>        &quot;#EXTM3U\n#EXT-X-VERSION:3\n&quot; +<br>        videoQualities<br>          .map(<br>            (quality) =&gt;<br>              `#EXT-X-STREAM-INF:BANDWIDTH=${<br>                parseInt(quality.bitrate) * 1000<br>              },RESOLUTION=${quality.height}p\n${quality.name}.m3u8`<br>          )<br>          .join(&quot;\n&quot;);<br><br>      // Write master playlist<br>      fs.writeFileSync(<br>        path.join(outputDir, &quot;master.m3u8&quot;),<br>        masterPlaylistContent<br>      );<br><br>      const ffmpegArgs = [<br>        &quot;-i&quot;,<br>        inputPath,<br>        &quot;-preset&quot;,<br>        &quot;veryfast&quot;,<br>        &quot;-tune&quot;,<br>        &quot;fastdecode&quot;,<br>        &quot;-sc_threshold&quot;,<br>        &quot;0&quot;,<br>        &quot;-g&quot;,<br>        &quot;48&quot;,<br>        &quot;-keyint_min&quot;,<br>        &quot;48&quot;,<br>        &quot;-movflags&quot;,<br>        &quot;+faststart&quot;,<br>      ];<br><br>      // Add arguments for each quality<br>      videoQualities.forEach((quality) =&gt; {<br>        ffmpegArgs.push(<br>          &quot;-vf&quot;,<br>          `scale=-2:${quality.height}`,<br>          &quot;-c:v&quot;,<br>          &quot;libx264&quot;,<br>          &quot;-profile:v&quot;,<br>          &quot;main&quot;,<br>          &quot;-crf&quot;,<br>          &quot;23&quot;,<br>          &quot;-maxrate&quot;,<br>          quality.maxrate,<br>          &quot;-bufsize&quot;,<br>          quality.bufsize,<br>          &quot;-c:a&quot;,<br>          &quot;aac&quot;,<br>          &quot;-ar&quot;,<br>          &quot;48000&quot;,<br>          &quot;-b:a&quot;,<br>          &quot;128k&quot;,<br>          &quot;-ac&quot;,<br>          &quot;2&quot;,<br>          &quot;-hls_time&quot;,<br>          &quot;10&quot;,<br>          &quot;-hls_playlist_type&quot;,<br>          &quot;vod&quot;,<br>          &quot;-hls_segment_filename&quot;,<br>          path.join(outputDir, `${quality.name}_%03d.ts`),<br>          &quot;-hls_flags&quot;,<br>          &quot;independent_segments&quot;,<br>          path.join(outputDir, `${quality.name}.m3u8`)<br>        );<br>      });<br><br>      const ffmpegProcess = spawn(&quot;ffmpeg&quot;, ffmpegArgs);<br><br>      let errorOutput = &quot;&quot;;<br><br>      ffmpegProcess.stderr.on(&quot;data&quot;, (data) =&gt; {<br>        errorOutput += data.toString();<br>        console.log(`FFmpeg progress: ${data}`);<br>      });<br><br>      ffmpegProcess.on(&quot;close&quot;, (code) =&gt; {<br>        try {<br>          if (code !== 0) {<br>            throw new Error(<br>              `FFmpeg process exited with code ${code}\nError output: ${errorOutput}`<br>            );<br>          }<br><br>          // Read all generated files<br>          const files = fs.readdirSync(outputDir);<br>          for (const file of files) {<br>            if (file.endsWith(&quot;.ts&quot;) || file.endsWith(&quot;.m3u8&quot;)) {<br>              segments[file] = fs.readFileSync(path.join(outputDir, file));<br>            }<br>          }<br>          resolve(segments);<br>        } catch (error) {<br>          reject(error);<br>        } finally {<br>          // Clean up input file<br>          if (fs.existsSync(inputPath)) {<br>            fs.unlinkSync(inputPath);<br>          }<br>        }<br>      });<br><br>      ffmpegProcess.on(&quot;error&quot;, (error) =&gt; {<br>        reject(new Error(`FFmpeg process error: ${error.message}`));<br>      });<br>    } catch (error) {<br>      reject(error);<br>    }<br>  });<br>}<br><br>// Helper function to upload segments to S3<br>async function uploadToS3(<br>  segments: Record&lt;string, Buffer&gt;,<br>  hlsKey: string<br>): Promise&lt;void&gt; {<br>  const uploadPromises = Object.entries(segments).map(([filename, data]) =&gt; {<br>    const upload = new Upload({<br>      client: s3,<br>      params: {<br>        Bucket: BUCKET_NAME,<br>        Key: `${hlsKey}/${filename}`,<br>        Body: data,<br>        ContentType: filename.endsWith(&quot;.m3u8&quot;)<br>          ? &quot;application/x-mpegURL&quot;<br>          : &quot;video/MP2T&quot;,<br>      },<br>      tags: [{ Key: &quot;videoId&quot;, Value: hlsKey.split(&quot;/&quot;)[1] }],<br>      queueSize: 4,<br>      partSize: 1024 * 1024 * 5,<br>    });<br><br>    upload.on(&quot;httpUploadProgress&quot;, (progress) =&gt; {<br>      console.log(<br>        `Progress for ${filename}: ${(<br>          ((progress.loaded || 0) / (progress.total || 1)) *<br>          100<br>        ).toFixed(2)}%`<br>      );<br>    });<br><br>    return upload.done();<br>  });<br><br>  await Promise.all(uploadPromises);<br>}<br><br>// Main controller function<br>export const uploadVideoController = async (req: Request, res: Response) =&gt; {<br>  const tempDir = path.join(TEMP_DIR, `hls_${Date.now()}`);<br>  fs.mkdirSync(tempDir, { recursive: true });<br><br>  try {<br>    // Check for FFmpeg installation<br>    await checkFFmpeg();<br><br>    const file = req.file;<br>    if (!file) {<br>      throw new Error(&quot;No file uploaded&quot;);<br>    }<br><br>    validateFile(file);<br><br>    // Generate unique ID and key for the video<br>    const videoId = crypto.randomBytes(16).toString(&quot;hex&quot;);<br>    const hlsKey = `hls/${videoId}`;<br><br>    // Convert video to HLS segments<br>    const segments = await convertToHLSSegments(file.buffer, tempDir);<br><br>    // Upload segments to S3<br>    console.log(&quot;📤 Uploading HLS segments to S3...&quot;);<br>    await uploadToS3(segments, hlsKey);<br><br>    const hlsUrl = `https://${BUCKET_NAME}.s3.${process.env.AWS_REGION}.amazonaws.com/${hlsKey}/master.m3u8`;<br><br>    return res.status(200).json({<br>      success: true,<br>      message: &quot;Video processed successfully&quot;,<br>      data: { hlsUrl, videoId },<br>    });<br>  } catch (error) {<br>    console.error(&quot;❌ Video processing error:&quot;, error);<br>    const errorMessage =<br>      error instanceof Error ? error.message : &quot;Failed to process video&quot;;<br>    return res.status(errorMessage.includes(&quot;Invalid file&quot;) ? 400 : 500).json({<br>      success: false,<br>      message: errorMessage,<br>    });<br>  } finally {<br>    // Clean up temporary directory<br>    if (fs.existsSync(tempDir)) {<br>      fs.rmSync(tempDir, { recursive: true, force: true });<br>    }<br>  }<br>};<br><br>export default { uploadVideoController };</pre><h3>Conclusion</h3><p>Yo implementation le euta production-ready video streaming platform ko strong foundation provide garxa ra esko faida haru yo yo hun:</p><ul><li>Adaptive quality streaming</li><li>Secure content delivery</li><li>Scalable architecture</li><li>Production-ready error handling</li><li>Progress tracking</li><li>Cloud storage integration</li></ul><p>Aba, yo video processing solution ko speed thap improve garna lai chahi Redis queue sanga master-worker pattern implement garna sakinchha. Ani hardware acceleration (hwaccel) jasari FFmpeg ko advanced features use and thread haru jasto diff ffmpeg args haru use gari eslai ajha saral ra fast garauna sakinxaaaa.</p><p>Happy streaming! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a0bba26416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating eSewa and Khalti Payment Gateways in Next.js with API Routes]]></title>
            <link>https://medium.com/@paudelronish/integrating-esewa-and-khalti-payment-gateways-in-next-js-14-with-server-actions-f15729ffae3e?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/f15729ffae3e</guid>
            <category><![CDATA[esewa-integration]]></category>
            <category><![CDATA[esewa]]></category>
            <category><![CDATA[khalti-digital-wallet]]></category>
            <category><![CDATA[khalti-integration]]></category>
            <category><![CDATA[payment-integration]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 04:02:07 GMT</pubDate>
            <atom:updated>2026-01-07T04:10:11.014Z</atom:updated>
            <content:encoded><![CDATA[<p>Payment gateways are vital for modern applications, allowing seamless transactions for users. In this comprehensive guide, we’ll walk through how to integrate two popular Nepali payment gateways, <strong>eSewa</strong> and <strong>Khalti</strong>, into a Next.js application using API Routes with <strong>proper payment verification</strong> and security measures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ac_FsvA2cw_9cdAcdJ8GRw.png" /></figure><h3>Why API Routes for Payment Processing?</h3><p>Next.js API Routes provide a powerful way to handle server-side logic securely. By processing payment initiation and verification on the server:</p><ul><li><strong>Sensitive information like secret keys remains protected</strong></li><li>You can implement complex logic without exposing it to the client</li><li>Easily manage environment-specific configurations</li><li>Provide a clean separation between client-side and server-side concerns</li><li><strong>Verify payments server-side to prevent fraud</strong></li></ul><h3>Setting Up Payment Initiation</h3><p>We’ll start by creating an API route to handle payment initiation for both eSewa and Khalti.</p><h3>Payment Initiation API Route</h3><p>Here’s a breakdown of the API Route responsible for initiating payments:</p><pre>// app/api/checkout-session/route.ts<br>import { NextResponse } from &quot;next/server&quot;;<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br>import { generateEsewaSignature } from &quot;@/lib/generateEsewaSignature&quot;;<br>import { PaymentMethod, PaymentRequestData } from &quot;@/lib/types&quot;;<br><br>function validateEnvironmentVariables() {<br>  const requiredEnvVars = [<br>    &quot;NEXT_PUBLIC_BASE_URL&quot;,<br>    &quot;NEXT_PUBLIC_ESEWA_MERCHANT_CODE&quot;,<br>    &quot;NEXT_PUBLIC_ESEWA_SECRET_KEY&quot;,<br>    &quot;NEXT_PUBLIC_KHALTI_SECRET_KEY&quot;,<br>  ];<br>  for (const envVar of requiredEnvVars) {<br>    if (!process.env[envVar]) {<br>      throw new Error(`Missing environment variable: ${envVar}`);<br>    }<br>  }<br>}<br>export async function POST(req: Request) {<br>  console.log(&quot;Received POST request to /api/checkout-session&quot;);<br>  try {<br>    validateEnvironmentVariables();<br>    const paymentData: PaymentRequestData = await req.json();<br>    const { amount, productName, transactionId, method } = paymentData;<br>    if (!amount || !productName || !transactionId || !method) {<br>      console.error(&quot;Missing required fields:&quot;, paymentData);<br>      return NextResponse.json(<br>        { error: &quot;Missing required fields&quot; },<br>        { status: 400 }<br>      );<br>    }<br>    switch (method as PaymentMethod) {<br>      case &quot;esewa&quot;: {<br>        console.log(&quot;Initiating eSewa payment&quot;);<br>        const transactionUuid = `${Date.now()}-${uuidv4()}`;<br>        const esewaConfig = {<br>          amount: amount,<br>          tax_amount: &quot;0&quot;,<br>          total_amount: amount,<br>          transaction_uuid: transactionUuid,<br>          product_code: process.env.NEXT_PUBLIC_ESEWA_MERCHANT_CODE,<br>          product_service_charge: &quot;0&quot;,<br>          product_delivery_charge: &quot;0&quot;,<br>          success_url: `${process.env.NEXT_PUBLIC_BASE_URL}/success?method=esewa`,<br>          failure_url: `${process.env.NEXT_PUBLIC_BASE_URL}`,<br>          signed_field_names: &quot;total_amount,transaction_uuid,product_code&quot;,<br>        };<br>        const signatureString = `total_amount=${esewaConfig.total_amount},transaction_uuid=${esewaConfig.transaction_uuid},product_code=${esewaConfig.product_code}`;<br>        const signature = generateEsewaSignature(<br>          process.env.NEXT_PUBLIC_ESEWA_SECRET_KEY!,<br>          signatureString<br>        );<br>        console.log(&quot;eSewa config:&quot;, { ...esewaConfig, signature });<br>        return NextResponse.json({<br>          amount: amount,<br>          esewaConfig: {<br>            ...esewaConfig,<br>            signature,<br>            product_service_charge: Number(esewaConfig.product_service_charge),<br>            product_delivery_charge: Number(esewaConfig.product_delivery_charge),<br>            tax_amount: Number(esewaConfig.tax_amount),<br>            total_amount: Number(esewaConfig.total_amount),<br>          },<br>        });<br>      }<br>      case &quot;khalti&quot;: {<br>        console.log(&quot;Initiating Khalti payment&quot;);<br>        const khaltiConfig = {<br>          return_url: `${process.env.NEXT_PUBLIC_BASE_URL}/success?method=khalti`,<br>          website_url: process.env.NEXT_PUBLIC_BASE_URL!,<br>          amount: Math.round(parseFloat(amount) * 100),<br>          purchase_order_id: transactionId,<br>          purchase_order_name: productName,<br>          customer_info: {<br>            name: &quot;dai&quot;,<br>            email: &quot;dai@gmail.com&quot;,<br>            phone: &quot;9800000000&quot;,<br>          },<br>        };<br>        const response = await fetch(<br>          &quot;https://a.khalti.com/api/v2/epayment/initiate/&quot;,<br>          {<br>            method: &quot;POST&quot;,<br>            headers: {<br>              Authorization: `Key ${process.env.NEXT_PUBLIC_KHALTI_SECRET_KEY}`,<br>              &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            },<br>            body: JSON.stringify(khaltiConfig),<br>          }<br>        );<br>        if (!response.ok) {<br>          const errorData = await response.json();<br>          console.error(&quot;Khalti API Error:&quot;, errorData);<br>          throw new Error(<br>            `Khalti payment initiation failed: ${JSON.stringify(errorData)}`<br>          );<br>        }<br>        const khaltiResponse = await response.json();<br>        console.log(&quot;Khalti payment initiated:&quot;, khaltiResponse);<br>        return NextResponse.json({<br>          khaltiPaymentUrl: khaltiResponse.payment_url,<br>        });<br>      }<br>      default:<br>        console.error(&quot;Invalid payment method:&quot;, method);<br>        return NextResponse.json(<br>          { error: &quot;Invalid payment method&quot; },<br>          { status: 400 }<br>        );<br>    }<br>  } catch (err) {<br>    console.error(&quot;Payment API Error:&quot;, err);<br>    return NextResponse.json(<br>      {<br>        error: &quot;Error creating payment session&quot;,<br>        details: err instanceof Error ? err.message : &quot;Unknown error&quot;,<br>      },<br>      { status: 500 }<br>    );<br>  }<br>}</pre><h3>[updated] Payment Verification And Why It’s Critical</h3><h3>Why Verification is Necessary</h3><p>Payment verification is <strong>absolutely critical</strong> for several security reasons:</p><ol><li><strong>Prevent Fraud</strong>: Without server-side verification, malicious users could manipulate URL parameters to fake successful payments</li><li><strong>Ensure Payment Completion</strong>: Verify that the payment actually went through with the payment gateway</li><li><strong>Prevent Transaction Reuse</strong>: Ensure that the same transaction ID (eSewa’s transaction_uuid or Khalti&#39;s pidx) cannot be used multiple times to unlock content</li><li><strong>Amount Validation</strong>: Confirm that the amount paid matches the expected amount</li><li><strong>Data Integrity</strong>: Ensure the transaction data hasn’t been tampered with</li></ol><h3>Security Vulnerabilities Without Verification</h3><p>Without proper verification, attackers could:</p><ul><li><strong>Bypass Payment</strong>: Set URL parameter status=Completed without paying</li><li><strong>Reuse Transaction IDs</strong>: Use someone else’s successful transaction_uuid or pidx to get free access</li><li><strong>Tamper Amounts</strong>: Pay NPR 100 but claim they paid NPR 10,000</li><li><strong>Replay Attacks</strong>: Reuse old successful payment confirmations</li></ul><h3>Payment Verification API Route</h3><p>Here’s the GET handler for the same API route that verifies payments:</p><pre>// app/api/checkout-session/route.ts <br><br>//(GET handler)<br>export async function GET(req: Request) {<br>  const { searchParams } = new URL(req.url);<br> const sessionId = searchParams.get(&quot;sessionId&quot;);<br>  const paymentId = searchParams.get(&quot;paymentId&quot;);<br>  const method = searchParams.get(&quot;method&quot;) as PaymentMethod;<br>  const pidx = searchParams.get(&quot;pidx&quot;);<br>  const transactionId = searchParams.get(&quot;transaction_id&quot;);<br>  const data = searchParams.get(&quot;data&quot;);<br><br>if (!method) {<br>    return NextResponse.json(<br>      { status: &quot;error&quot;, message: &quot;Missing payment method&quot; },<br>      { status: 400 }<br>    );<br>  }<br>try {<br>    // eSewa Payment Verification<br>    if (method === PaymentMethod.ESEWA &amp;&amp; paymentId &amp;&amp; data) {<br>      let decoded;<br>      try {<br>        decoded = JSON.parse(Buffer.from(data, &quot;base64&quot;).toString(&quot;utf-8&quot;));<br>      } catch (err) {<br>        console.error(&quot;Failed to decode eSewa data:&quot;, err);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Invalid eSewa payload&quot; },<br>          { status: 400 }<br>        );<br>      }<br>      if (decoded.status !== &quot;COMPLETE&quot;) {<br>        return NextResponse.json({ status: &quot;pending&quot; });<br>      }<br>      // SECURITY: Verify transaction with eSewa server<br>      console.log(&quot;Verifying eSewa transaction with server...&quot;);<br>      // SECURITY: Check if payment record exists<br>      const existingPayment = await prisma.payment.findUnique({<br>        where: { id: paymentId },<br>        select: {<br>          userId: true,<br>          paymentStatus: true,<br>          amount: true,<br>          esewaTransactionUuid: true,<br>        },<br>      });<br>      if (!existingPayment) {<br>        console.error(&quot;Payment record not found&quot;);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment not found&quot; },<br>          { status: 404 }<br>        );<br>      }<br>      // SECURITY: Prevent payment reuse<br>      if (existingPayment.paymentStatus === PaymentStatus.COMPLETED) {<br>        console.error(&quot;Payment already processed&quot;, { paymentId });<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment has already been processed&quot; },<br>          { status: 400 }<br>        );<br>      }<br>      const esewaVerifyUrl = process.env.ESEWA_VERIFY_URL;<br>      if (!esewaVerifyUrl) {<br>        console.error(&quot;ESEWA_VERIFY_URL not configured&quot;);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;eSewa verification not configured&quot; },<br>          { status: 500 }<br>        );<br>      }<br>      try {<br>        // SECURITY: Call eSewa API to verify transaction<br>        const verifyUrl = `${esewaVerifyUrl}?product_code=${encodeURIComponent(<br>          process.env.ESEWA_MERCHANT_CODE!<br>        )}&amp;total_amount=${encodeURIComponent(<br>          decoded.total_amount<br>        )}&amp;transaction_uuid=${encodeURIComponent(decoded.transaction_uuid)}`;<br>        console.log(&quot;eSewa verification URL:&quot;, verifyUrl);<br>        const verifyResponse = await fetch(verifyUrl, {<br>          method: &quot;GET&quot;,<br>        });<br>        if (!verifyResponse.ok) {<br>          console.error(&quot;eSewa verification failed:&quot;, verifyResponse.status);<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Payment verification failed with eSewa&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>        const verificationResult = await verifyResponse.json();<br>        // SECURITY: Verify transaction UUID matches<br>        if (<br>          verificationResult.status !== &quot;COMPLETE&quot; ||<br>          verificationResult.transaction_uuid !== decoded.transaction_uuid<br>        ) {<br>          console.error(&quot;eSewa verification mismatch:&quot;, verificationResult);<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Payment verification failed - invalid transaction&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>        // SECURITY: Verify amount matches<br>        const verifiedAmount = Number(verificationResult.total_amount);<br>        if (verifiedAmount !== existingPayment.amount) {<br>          console.error(&quot;Amount mismatch:&quot;, {<br>            expected: existingPayment.amount,<br>            received: verifiedAmount,<br>          });<br>          return NextResponse.json(<br>            { status: &quot;error&quot;, message: &quot;Payment amount mismatch&quot; },<br>            { status: 400 }<br>          );<br>        }<br>        console.log(&quot;eSewa transaction verified successfully&quot;);<br>        // SECURITY: Check if transaction UUID was already used (fraud prevention)<br>        const existingPaymentWithTxn = await prisma.payment.findFirst({<br>          where: {<br>            esewaTransactionUuid: decoded.transaction_uuid,<br>            id: { not: paymentId },<br>          },<br>        });<br>        if (existingPaymentWithTxn) {<br>          console.error(<br>            &quot;FRAUD ALERT: eSewa transaction UUID already used:&quot;,<br>            {<br>              transaction_uuid: decoded.transaction_uuid,<br>              originalPayment: existingPaymentWithTxn.id,<br>              attemptedPayment: paymentId,<br>            }<br>          );<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Transaction already used for another payment&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>      } catch (verifyError) {<br>        console.error(&quot;eSewa verification error:&quot;, verifyError);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment verification failed&quot; },<br>          { status: 500 }<br>        );<br>      }<br>      // SECURITY: Use atomic update to prevent race condition<br>      const updateResult = await prisma.payment.updateMany({<br>        where: {<br>          id: paymentId,<br>          paymentStatus: { not: PaymentStatus.COMPLETED },<br>          esewaTransactionUuid: null,<br>        },<br>        data: {<br>          paymentStatus: PaymentStatus.COMPLETED,<br>          esewaTransactionUuid: decoded.transaction_uuid,<br>          esewaRefId: decoded.ref_id || null,<br>        },<br>      });<br>      if (updateResult.count === 0) {<br>        console.log(&quot;eSewa payment already processed by another request&quot;);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment has already been processed&quot; },<br>          { status: 400 }<br>        );<br>      }<br>      console.log(&quot;eSewa payment verified and updated&quot;);<br>      return NextResponse.json({<br>        status: &quot;success&quot;,<br>        message: &quot;Payment verified successfully&quot;,<br>      });<br>    }<br>    // Khalti Payment Verification<br>    if (method === PaymentMethod.KHALTI) {<br>      console.log(&quot;Processing KHALTI payment...&quot;);<br>      const khaltiTxn = pidx || transactionId;<br>      const khaltiPaymentId =<br>        paymentId || searchParams.get(&quot;purchase_order_id&quot;);<br>      if (!khaltiPaymentId || !khaltiTxn) {<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Missing payment details&quot; },<br>          { status: 400 }<br>        );<br>      }<br>      // SECURITY: Check if payment exists<br>      const existingPayment = await prisma.payment.findUnique({<br>        where: { id: khaltiPaymentId },<br>        select: {<br>          paymentStatus: true,<br>          amount: true,<br>          khaltiPidx: true,<br>        },<br>      });<br>      if (!existingPayment) {<br>        console.error(&quot;Payment record not found&quot;);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment not found&quot; },<br>          { status: 404 }<br>        );<br>      }<br>      // SECURITY: Prevent payment reuse<br>      if (existingPayment.paymentStatus === PaymentStatus.COMPLETED) {<br>        console.error(&quot;Payment already processed&quot;, {<br>          paymentId: khaltiPaymentId,<br>        });<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment has already been processed&quot; },<br>          { status: 400 }<br>        );<br>      }<br>      try {<br>        const khaltiVerifyUrl = process.env.KHALTI_VERIFY_URL;<br>        if (!khaltiVerifyUrl) {<br>          console.error(&quot;KHALTI_VERIFY_URL not configured&quot;);<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Khalti verification not configured&quot;,<br>            },<br>            { status: 500 }<br>          );<br>        }<br>        // SECURITY: Call Khalti API to verify payment<br>        const res = await fetch(khaltiVerifyUrl, {<br>          method: &quot;POST&quot;,<br>          headers: {<br>            Authorization: `Key ${process.env.KHALTI_SECRET_KEY}`,<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          },<br>          body: JSON.stringify({ pidx: khaltiTxn }),<br>        });<br>        if (!res.ok) {<br>          console.error(&quot;Khalti verification API failed:&quot;, res.status);<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Payment verification failed with Khalti&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>        const json = await res.json();<br>        console.log(&quot;Khalti verification response:&quot;, json);<br>        // SECURITY: Verify the pidx belongs to this payment<br>        if (json.purchase_order_id &amp;&amp; json.purchase_order_id !== khaltiPaymentId) {<br>          console.error(&quot;Payment ID mismatch:&quot;, {<br>            expected: khaltiPaymentId,<br>            received: json.purchase_order_id,<br>          });<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Payment verification failed - ID mismatch&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>        // SECURITY: Verify amount matches (Khalti returns amount in paisa)<br>        if (json.total_amount) {<br>          const verifiedAmount = json.total_amount / 100;<br>          if (Math.abs(verifiedAmount - existingPayment.amount) &gt; 0.01) {<br>            console.error(&quot;Amount mismatch:&quot;, {<br>              expected: existingPayment.amount,<br>              received: verifiedAmount,<br>            });<br>            return NextResponse.json(<br>              { status: &quot;error&quot;, message: &quot;Payment amount mismatch&quot; },<br>              { status: 400 }<br>            );<br>          }<br>        }<br>        // SECURITY: Check payment status<br>        if (json.status !== &quot;Completed&quot; &amp;&amp; json.state?.name !== &quot;Completed&quot;) {<br>          console.warn(&quot;Khalti payment not completed:&quot;, json.status || json.state?.name);<br>          return NextResponse.json(<br>            { status: &quot;error&quot;, message: &quot;Payment not completed&quot; },<br>            { status: 400 }<br>          );<br>        }<br>        console.log(&quot;Khalti payment verified successfully&quot;);<br>        // SECURITY: Check if pidx was already used (fraud prevention)<br>        const existingPaymentWithPidx = await prisma.payment.findFirst({<br>          where: {<br>            khaltiPidx: khaltiTxn,<br>            id: { not: khaltiPaymentId },<br>          },<br>        });<br>        if (existingPaymentWithPidx) {<br>          console.error(&quot;FRAUD ALERT: Khalti pidx already used:&quot;, {<br>            pidx: khaltiTxn,<br>            originalPayment: existingPaymentWithPidx.id,<br>            attemptedPayment: khaltiPaymentId,<br>          });<br>          return NextResponse.json(<br>            {<br>              status: &quot;error&quot;,<br>              message: &quot;Transaction already used for another payment&quot;,<br>            },<br>            { status: 400 }<br>          );<br>        }<br>        // Update payment record<br>        const updatedPayment = await prisma.payment.update({<br>          where: { id: khaltiPaymentId },<br>          data: {<br>            paymentStatus: PaymentStatus.COMPLETED,<br>            khaltiPidx: khaltiTxn,<br>          },<br>        });<br>        console.log(&quot;Khalti payment verified and updated&quot;);<br>        return NextResponse.json({<br>          status: &quot;success&quot;,<br>          message: &quot;Payment verified successfully&quot;,<br>        });<br>      } catch (err) {<br>        console.error(&quot;Khalti verification error:&quot;, err);<br>        return NextResponse.json(<br>          { status: &quot;error&quot;, message: &quot;Payment verification failed&quot; },<br>          { status: 500 }<br>        );<br>      }<br>    }<br>    return NextResponse.json(<br>      { status: &quot;error&quot;, message: &quot;Invalid payment method&quot; },<br>      { status: 400 }<br>    );<br>  } catch (error) {<br>    console.error(&quot;Payment verification error:&quot;, error);<br>    return NextResponse.json(<br>      {<br>        status: &quot;error&quot;,<br>        message: &quot;Payment verification failed&quot;,<br>        details: error instanceof Error ? error.message : &quot;Unknown error&quot;,<br>      },<br>      { status: 500 }<br>    );<br>  }<br>}</pre><h3>Critical Security Measures Implemented</h3><h3>1. Server-Side Verification</h3><ul><li><strong>Never trust client data</strong>: Always verify with the payment gateway’s API</li><li><strong>eSewa</strong>: Call verification endpoint with transaction_uuid</li><li><strong>Khalti</strong>: Call lookup endpoint with pidx</li></ul><h3>2. Transaction ID Reuse Prevention</h3><p><strong>For eSewa:</strong></p><pre>// Store transaction_uuid in database to prevent reuse<br>const existingPaymentWithTxn = await prisma.payment.findFirst({<br>  where: {<br>    esewaTransactionUuid: decoded.transaction_uuid,<br>    id: { not: paymentId },<br>  },<br>});<br>if (existingPaymentWithTxn) {<br>  // FRAUD ALERT: Someone is trying to reuse a transaction UUID<br>  return error;<br>}</pre><p><strong>For Khalti:</strong></p><pre>// Store pidx in database to prevent reuse<br>const existingPaymentWithPidx = await prisma.payment.findFirst({<br>  where: {<br>    khaltiPidx: khaltiTxn,<br>    id: { not: khaltiPaymentId },<br>  },<br>});<br>if (existingPaymentWithPidx) {<br>  // FRAUD ALERT: Someone is trying to reuse a pidx<br>  return error;<br>}</pre><h3>3. Amount Validation</h3><pre>// Verify the amount paid matches expected amount<br>const verifiedAmount = Number(verificationResult.total_amount);<br>if (verifiedAmount !== existingPayment.amount) {<br>  return error; // Amount tampering detected<br>}</pre><h3>4. Atomic Updates (Race Condition Prevention)</h3><pre>// Use updateMany with conditions to prevent double-processing<br>const updateResult = await prisma.payment.updateMany({<br>  where: {<br>    id: paymentId,<br>    paymentStatus: { not: PaymentStatus.COMPLETED },<br>    esewaTransactionUuid: null,<br>  },<br>  data: {<br>    paymentStatus: PaymentStatus.COMPLETED,<br>    esewaTransactionUuid: decoded.transaction_uuid,<br>  },<br>});<br>if (updateResult.count === 0) {<br>  // Another request already processed this<br>  return error;<br>}</pre><h3>5. Database Schema Updates</h3><p>Add these fields to your Prisma schema:</p><pre>model Payment {<br>  <br>  // eSewa transaction tracking (prevents reuse)<br>  esewaTransactionUuid  String?       @unique<br>  esewaRefId            String?<br>  <br>  // Khalti transaction tracking (prevents reuse)<br>  khaltiPidx            String?       @unique<br>  <br>  // ... other fields<br>}</pre><h3>eSewa Hashing and Secret Key</h3><p>When integrating eSewa into your Next.js application, it’s crucial to understand the hashing process and the use of the secret key.</p><h3>eSewa Hashing</h3><p>eSewa uses <strong>HMAC-SHA256</strong> hashing to verify the integrity of the payment request. The hash is created using:</p><ol><li>Concatenate required fields: total_amount,transaction_uuid,product_code</li><li>Use your eSewa secret key to create an HMAC-SHA256 hash</li><li>Send the hash along with your payment request</li></ol><p>Here’s the signature generation function:</p><pre>// lib/generateEsewaSignature.ts<br>import CryptoJS from &quot;crypto-js&quot;;<br><br>export function generateEsewaSignature(<br>  secretKey: string,<br>  message: string<br>): string {<br>  const hash = CryptoJS.HmacSHA256(message, secretKey);<br>  return CryptoJS.enc.Base64.stringify(hash);<br>}</pre><h3>EPAYTEST and Secret Key</h3><p>For testing purposes, eSewa provides:</p><ul><li><strong>Merchant Code</strong>: EPAYTEST</li><li><strong>Secret Key</strong>: 8gBm/:&amp;EnhH.1/q</li></ul><p><strong>Environment Variables:</strong></p><pre>NEXT_PUBLIC_ESEWA_MERCHANT_CODE=EPAYTEST<br>NEXT_PUBLIC_ESEWA_SECRET_KEY=8gBm/:&amp;EnhH.1/q<br>ESEWA_VERIFY_URL=https://rc-epay.esewa.com.np/api/epay/transaction/status/</pre><h3>Important Notes</h3><ul><li><strong>Never expose your secret key on the client-side</strong></li><li><strong>Test URL</strong>: <a href="https://rc-epay.esewa.com.np/api/epay/main/v2/form">https://rc-epay.esewa.com.np/api/epay/main/v2/form</a></li><li><strong>Production URL</strong>: <a href="https://epay.esewa.com.np/api/epay/main/v2/form">https://epay.esewa.com.np/api/epay/main/v2/form</a></li><li><strong>Verify URL (Test)</strong>: <a href="https://rc-epay.esewa.com.np/api/epay/transaction/status/">https://rc-epay.esewa.com.np/api/epay/transaction/status/</a></li><li><strong>Verify URL (Production)</strong>: <a href="https://epay.esewa.com.np/api/epay/transaction/status/">https://epay.esewa.com.np/api/epay/transaction/status/</a></li></ul><h3>eSewa Test Credentials</h3><ul><li><strong>eSewa ID</strong>: 9806800001/2/3/4/5</li><li><strong>Password</strong>: Nepal@123</li><li><strong>MPIN</strong>: 1122</li><li><strong>Token</strong>: 123456</li></ul><h3>Payment Components</h3><h3>eSewa Payment Component</h3><pre>//app/esewa-payment/page.tsx<br>&quot;use client&quot;;</pre><pre>import { useState, useEffect } from &quot;react&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from &quot;@/components/ui/card&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import { Label } from &quot;@/components/ui/label&quot;;<br>import { useToast } from &quot;@/hooks/use-toast&quot;;</pre><pre>export default function EsewaPayment() {<br>  const [amount, setAmount] = useState&lt;string&gt;(&quot;&quot;);<br>  const [productName, setProductName] = useState&lt;string&gt;(&quot;&quot;);<br>  const [transactionId, setTransactionId] = useState&lt;string&gt;(&quot;&quot;);<br>  const [isLoading, setIsLoading] = useState&lt;boolean&gt;(false);<br>  const { toast } = useToast();</pre><pre>  const handlePayment = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br>    setIsLoading(true);</pre><pre>    try {<br>      const response = await fetch(&quot;/api/checkout-session&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify({<br>          method: &quot;esewa&quot;,<br>          amount,<br>          productName,<br>          transactionId,<br>        }),<br>      });</pre><pre>      if (!response.ok) {<br>        throw new Error(`Payment initiation failed: ${response.statusText}`);<br>      }</pre><pre>      const paymentData = await response.json();<br>      <br>      toast({<br>        title: &quot;Payment Initiated&quot;,<br>        description: &quot;Redirecting to eSewa payment gateway...&quot;,<br>      });</pre><pre>      // Create form and submit to eSewa<br>      const form = document.createElement(&quot;form&quot;);<br>      form.method = &quot;POST&quot;;<br>      form.action = &quot;https://rc-epay.esewa.com.np/api/epay/main/v2/form&quot;;</pre><pre>      const esewaPayload = {<br>        amount: paymentData.amount,<br>        tax_amount: paymentData.esewaConfig.tax_amount,<br>        total_amount: paymentData.esewaConfig.total_amount,<br>        transaction_uuid: paymentData.esewaConfig.transaction_uuid,<br>        product_code: paymentData.esewaConfig.product_code,<br>        product_service_charge: paymentData.esewaConfig.product_service_charge,<br>        product_delivery_charge: paymentData.esewaConfig.product_delivery_charge,<br>        success_url: paymentData.esewaConfig.success_url,<br>        failure_url: paymentData.esewaConfig.failure_url,<br>        signed_field_names: paymentData.esewaConfig.signed_field_names,<br>        signature: paymentData.esewaConfig.signature,<br>      };</pre><pre>      Object.entries(esewaPayload).forEach(([key, value]) =&gt; {<br>        const input = document.createElement(&quot;input&quot;);<br>        input.type = &quot;hidden&quot;;<br>        input.name = key;<br>        input.value = String(value);<br>        form.appendChild(input);<br>      });</pre><pre>      document.body.appendChild(form);<br>      form.submit();<br>      document.body.removeChild(form);<br>    } catch (error) {<br>      console.error(&quot;Payment error:&quot;, error);<br>      toast({<br>        variant: &quot;destructive&quot;,<br>        title: &quot;Payment Error&quot;,<br>        description: &quot;Payment initiation failed. Please try again.&quot;,<br>      });<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };</pre><pre>  return (<br>    &lt;div className=&quot;flex justify-center items-center min-h-screen bg-gray-100&quot;&gt;<br>      &lt;Card className=&quot;w-full max-w-md mx-4&quot;&gt;<br>        &lt;CardHeader&gt;<br>          &lt;CardTitle&gt;eSewa Payment&lt;/CardTitle&gt;<br>          &lt;CardDescription&gt;Enter payment details for eSewa&lt;/CardDescription&gt;<br>        &lt;/CardHeader&gt;<br>        &lt;form onSubmit={handlePayment}&gt;<br>          &lt;CardContent className=&quot;space-y-4&quot;&gt;<br>            &lt;div className=&quot;space-y-2&quot;&gt;<br>              &lt;Label htmlFor=&quot;amount&quot;&gt;Amount (NPR)&lt;/Label&gt;<br>              &lt;Input<br>                id=&quot;amount&quot;<br>                type=&quot;number&quot;<br>                value={amount}<br>                onChange={(e) =&gt; setAmount(e.target.value)}<br>                required<br>                min=&quot;1&quot;<br>                step=&quot;0.01&quot;<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;space-y-2&quot;&gt;<br>              &lt;Label htmlFor=&quot;productName&quot;&gt;Product Name&lt;/Label&gt;<br>              &lt;Input<br>                id=&quot;productName&quot;<br>                value={productName}<br>                onChange={(e) =&gt; setProductName(e.target.value)}<br>                required<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;space-y-2&quot;&gt;<br>              &lt;Label htmlFor=&quot;transactionId&quot;&gt;Transaction ID&lt;/Label&gt;<br>              &lt;Input<br>                id=&quot;transactionId&quot;<br>                value={transactionId}<br>                onChange={(e) =&gt; setTransactionId(e.target.value)}<br>                required<br>              /&gt;<br>            &lt;/div&gt;<br>          &lt;/CardContent&gt;<br>          &lt;CardFooter&gt;<br>            &lt;Button type=&quot;submit&quot; className=&quot;w-full&quot; disabled={isLoading}&gt;<br>              {isLoading ? &quot;Processing...&quot; : &quot;Pay with eSewa&quot;}<br>            &lt;/Button&gt;<br>          &lt;/CardFooter&gt;<br>        &lt;/form&gt;<br>      &lt;/Card&gt;<br>    &lt;/div&gt;<br>  );<br></pre><h3>Khalti Payment Component</h3><pre>//app/khalti-payment/page.tsx<br>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from &quot;@/components/ui/card&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import { Label } from &quot;@/components/ui/label&quot;;<br>import Script from &quot;next/script&quot;;</pre><pre>export default function KhaltiPayment() {<br>  const [amount, setAmount] = useState(&quot;&quot;);<br>  const [productName, setProductName] = useState(&quot;&quot;);<br>  const [transactionId, setTransactionId] = useState(&quot;&quot;);<br>  const [isLoading, setIsLoading] = useState(false);</pre><pre>  const handlePayment = async (e: React.FormEvent) =&gt; {<br>    e.preventDefault();<br>    setIsLoading(true);</pre><pre>    try {<br>      const response = await fetch(&quot;/api/checkout-session&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify({<br>          method: &quot;khalti&quot;,<br>          amount,<br>          productName,<br>          transactionId,<br>        }),<br>      });</pre><pre>      if (!response.ok) {<br>        throw new Error(&quot;Payment initiation failed&quot;);<br>      }</pre><pre>      const data = await response.json();</pre><pre>      if (!data.khaltiPaymentUrl) {<br>        throw new Error(&quot;Khalti payment URL not received&quot;);<br>      }<br>      <br>      window.location.href = data.khaltiPaymentUrl;<br>    } catch (error) {<br>      console.error(&quot;Payment error:&quot;, error);<br>      alert(&quot;Payment initiation failed. Please try again.&quot;);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;Script<br>        src=&quot;https://khalti.s3.ap-south-1.amazonaws.com/KPG/dist/2020.12.22.0.0.0/khalti-checkout.iffe.js&quot;<br>        strategy=&quot;lazyOnload&quot;<br>      /&gt;<br>      &lt;div className=&quot;flex justify-center items-center min-h-screen bg-gray-100&quot;&gt;<br>        &lt;Card className=&quot;w-full max-w-md mx-4&quot;&gt;<br>          &lt;CardHeader&gt;<br>            &lt;CardTitle&gt;Khalti Payment&lt;/CardTitle&gt;<br>            &lt;CardDescription&gt;Enter payment details for Khalti&lt;/CardDescription&gt;<br>          &lt;/CardHeader&gt;<br>          &lt;form onSubmit={handlePayment}&gt;<br>            &lt;CardContent className=&quot;space-y-4&quot;&gt;<br>              &lt;div className=&quot;space-y-2&quot;&gt;<br>                &lt;Label htmlFor=&quot;amount&quot;&gt;Amount (NPR)&lt;/Label&gt;<br>                &lt;Input<br>                  id=&quot;amount&quot;<br>                  type=&quot;number&quot;<br>                  value={amount}<br>                  onChange={(e) =&gt; setAmount(e.target.value)}<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;space-y-2&quot;&gt;<br>                &lt;Label htmlFor=&quot;productName&quot;&gt;Product Name&lt;/Label&gt;<br>                &lt;Input<br>                  id=&quot;productName&quot;<br>                  value={productName}<br>                  onChange={(e) =&gt; setProductName(e.target.value)}<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;space-y-2&quot;&gt;<br>                &lt;Label htmlFor=&quot;transactionId&quot;&gt;Transaction ID&lt;/Label&gt;<br>                &lt;Input<br>                  id=&quot;transactionId&quot;<br>                  value={transactionId}<br>                  onChange={(e) =&gt; setTransactionId(e.target.value)}<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br>            &lt;/CardContent&gt;<br>            &lt;CardFooter&gt;<br>              &lt;Button type=&quot;submit&quot; className=&quot;w-full&quot; disabled={isLoading}&gt;<br>                {isLoading ? &quot;Processing...&quot; : &quot;Pay with Khalti&quot;}<br>              &lt;/Button&gt;<br>            &lt;/CardFooter&gt;<br>          &lt;/form&gt;<br>        &lt;/Card&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Important Notes</h3><ul><li><strong>Never expose your secret key on the client-side</strong></li><li><strong>Test URL</strong>: <a href="https://dev.khalti.com/api/v2/epayment/initiate/">https://dev.khalti.com/api/v2/epayment/initiate/</a></li><li><strong>Production URL</strong>: <a href="https://khalti.com/api/v2/epayment/initiate/">https://khalti.com/api/v2/epayment/initiate/</a></li><li><strong>Verify URL (Test)</strong>: <a href="https://dev.khalti.com/api/v2/epayment/lookup/">https://dev.khalti.com/api/v2/epayment/lookup/</a></li><li><strong>Verify URL (Production)</strong>: <a href="https://khalti.com/api/v2/epayment/lookup/">https://khalti.com/api/v2/epayment/lookup/</a></li></ul><h3>API Keys</h3><p><strong>1.Khalti Public Key (</strong>KHALTI_PUBLIC_KEY<strong>)</strong></p><ul><li>Safe to use on the <strong>client-side</strong></li><li>Used to initialize Khalti payment UI</li></ul><p><strong>2.Khalti Secret Key (</strong>KHALTI_SECRET_KEY<strong>)</strong></p><ul><li><strong>Server-side only</strong></li><li>Required for payment initiation and verification</li></ul><p>Both keys are provided in the <strong>Khalti Merchant Dashboard</strong> for:</p><ul><li><strong>Sandbox</strong> (testing)</li><li><strong>Production</strong> (live payments)</li></ul><h3>Khalti Test Credentials</h3><ul><li><strong>Test Khalti ID</strong>: 9800000000, 9800000001, 9800000002, 9800000003, 9800000004, 9800000005</li><li><strong>Test MPIN</strong>: 1111</li><li><strong>Test OTP</strong>: 987654</li></ul><h3>Key Takeaways</h3><ol><li><strong>Always verify payments server-side</strong> — Never trust client data</li><li><strong>Prevent transaction ID reuse</strong> — Store and check transaction_uuid (eSewa) and pidx (Khalti)</li><li><strong>Validate amounts</strong> — Ensure paid amount matches expected amount</li><li><strong>Use atomic updates</strong> — Prevent race conditions with database constraints</li><li><strong>Implement proper error handling</strong> — Log fraud attempts for security monitoring</li><li><strong>Never expose secret keys</strong> — Keep all sensitive data server-side</li><li><strong>Test thoroughly</strong> — Use sandbox environments before going to production</li></ol><h3>Live Demo &amp; Source Code</h3><ul><li><strong>Live Demo</strong>: <a href="https://payment-gateway-mu-gold.vercel.app/">https://payment-gateway-mu-gold.vercel.app/</a></li><li><strong>Source Code</strong>: <a href="https://github.com/ronishpaudel/Payment-Gateway">https://github.com/ronishpaudel/Payment-Gateway</a></li></ul><p>With these security measures in place, you can confidently integrate eSewa and Khalti into your Next.js applications while protecting against fraud, transaction reuse, and other security vulnerabilities.</p><p>#WebDevelopment #NextJS #JavaScript #TypeScript #FrontendDevelopment #FullStackDeveloper #PaymentGatewayIntegration #PaymentSecurity #FraudPrevention</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f15729ffae3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Built a Dynamic Form with Simplified UI and Flexible Input Handling ?]]></title>
            <link>https://medium.com/@paudelronish/how-to-built-a-dynamic-form-with-simplified-ui-and-flexible-input-handling-9b90ef76b2e3?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b90ef76b2e3</guid>
            <category><![CDATA[dynamic-form-handling]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 15:11:00 GMT</pubDate>
            <atom:updated>2024-11-12T15:11:00.802Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Built a Dynamic Form with Simplified UI and Flexible Input Handling ?</h3><h3>Introduction</h3><p>Creating flexible, dynamic forms is an essential part of many applications, from contact lists to surveys and registration forms. Recently, I developed a <strong>lean React form component</strong> that allows users to add and remove multiple input fields dynamically. In this article, I’ll walk you through the key elements of building this kind of component and the optimizations that make it efficient.</p><p>To test form submissions, I used the <strong>JSONPlaceholder API</strong>, which provides a simple way to test and simulate interactions with a backend. This helps ensure that the form is fully functional, without needing an actual backend server.</p><h3>Dynamic Form Component Features</h3><p>The dynamic form component in this project is highly flexible, with these main features:</p><ul><li><strong>Dynamic Field Addition and Removal</strong>: Users can add or remove multiple sets of input fields, making it ideal for forms that require user flexibility.</li><li><strong>Enhanced User Experience with Framer Motion</strong>: To make the form interactive, I used Framer Motion for smooth animations. This adds an extra layer of polish and keeps users engaged.</li><li><strong>Simplified UI and User-Friendly</strong>: With intuitive form handling and validation, users have a streamlined experience that feels responsive and easy to use.</li></ul><h3>Tackling Performance with useCallback</h3><p>In complex form setups, repetitive re-renders can be a <strong>performance bottleneck</strong>. For example, without optimizations, adding or updating a field may trigger unnecessary re-renders, causing lag in the UI. To handle this, I utilized useCallback, which helps by <strong>memoizing functions</strong> like addField and handleChange. This prevents them from being redefined on every render, allowing for a smoother, more efficient form experience.</p><h3>Handling Multiple Inputs with useForm</h3><p>When it comes to managing multiple inputs and validations, <strong>React Hook Form’s </strong><strong>useForm hook</strong> is particularly suited for this kind of dynamic form. It provides:</p><ul><li><strong>Efficient State Management</strong>: useForm keeps form state centralized and optimized for performance.</li><li><strong>Validation Support</strong>: With useForm, we can easily define validation rules for each field, ensuring user input is accurate.</li><li><strong>Error Handling</strong>: Any issues with the input are highlighted in real-time, helping guide users through the form-filling process.</li></ul><h3>Try it Live!</h3><p>You can check out the live version and explore the code on GitHub:</p><p>🔗 Live Demo: <a href="https://cloneable-contact-form007.vercel.app/">Cloneable Form (cloneable-contact-form007.vercel.app)</a></p><p>🔗 GitHub Repository: <a href="https://github.com/ronishpaudel/clonable-contact-form">ronishpaudel/clonable-contact-form (github.com)</a></p><p><a href="https://www.linkedin.com/feed/hashtag/?keywords=react&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#React</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=javascript&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#JavaScript</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=webdevelopment&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#WebDevelopment</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=frontend&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#Frontend</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=programming&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#Programming</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=formhandling&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#FormHandling</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=optimization&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#Optimization</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=fullstackdevelopment&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7262116148794597376">#FullStackDevelopment</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFP-Igr6q7otWYNlEXTkcQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b90ef76b2e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to Next.js and Express Video Streaming using HSTS (with code example)]]></title>
            <link>https://medium.com/@paudelronish/how-to-build-a-full-stack-video-streaming-platform-with-node-js-9a7f14655af6?source=rss-ef4b39e1fb87------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7f14655af6</guid>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Paudelronish]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 15:49:01 GMT</pubDate>
            <atom:updated>2025-02-07T20:06:10.707Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Guide to Next.js and Express Video Streaming using HSTS (with code example) 🚀</h3><h3>Introduction</h3><p>Ever thought about creating your own video streaming platform, but not sure where to start? Imagine having full control over how videos are processed, streamed, and presented — every detail shaped by you. That’s the journey I embarked on, using <strong>Node.js</strong> and <strong>FFmpeg </strong>to handle the heavy lifting on the backend and <strong>Next.js</strong> to craft a sleek, modern frontend. In this blog, I’ll guide you through the entire process, sharing not just the setup but also the real-world challenges I faced and how I overcame them. Whether you’re an aspiring developer or just curious about the magic behind streaming platforms, this deep dive is packed with insights that could ignite your next big idea. Buckle up — you’re in for an exciting ride!</p><h3>Technologies Used</h3><p><strong>1. Node.js &amp; Express:</strong></p><ul><li><strong>Purpose:</strong> Handles video uploads, conversion to HLS format, and serves video files.</li><li><strong>Key Features:</strong> Fast, scalable, and non-blocking I/O.</li></ul><p><strong>2. FFmpeg:</strong></p><ul><li><strong>Purpose:</strong> Converts video files into HLS (HTTP Live Streaming) format.</li><li><strong>Key Features:</strong> Open-source tool for handling multimedia data. It can transcode, convert, and stream audio and video.</li><li><strong>HLS &amp; M3U8:</strong></li><li><strong>HLS</strong>: A protocol for streaming video over the internet. It breaks the video into small segments and delivers them as a playlist.</li><li><strong>M3U8</strong>: A playlist file format used by HLS to organize video segments and metadata.</li></ul><p><strong>3. Multer:</strong></p><ul><li><strong>Purpose:</strong> Middleware for handling multipart/form-data, used for uploading files.</li><li><strong>Key Features:</strong> Handles file uploads with ease, including setting file size limits and naming files uniquely.</li></ul><p><strong>4. Next.js:</strong></p><ul><li><strong>Purpose:</strong> Provides a modern frontend framework with server-side rendering, static site generation, and API routes.</li><li><strong>Key Features:</strong> Efficient routing, built-in CSS support, and easy API integration.</li></ul><h3>Backend Setup</h3><p><strong>1. Express Server Setup:</strong></p><ul><li><strong>Endpoints:</strong> Handle video uploads, convert videos to HLS format using FFmpeg, and serve video files.</li><li><strong>Code Highlights:</strong></li><li>Upload videos using <strong>Multer</strong>.</li><li>Convert videos to HLS format with <strong>FFmpeg</strong>.</li><li>Serve .m3u8 playlists and .ts segments.</li></ul><p><strong>- Server</strong>.<strong>ts:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*6uqHZAfQOr6ZycVurEB30w@2x.jpeg" /></figure><p><strong>2. FFmpeg Command for HLS Conversion:</strong></p><pre>ffmpeg -i &quot;${videoPath}&quot; -codec:v libx264 -codec:a aac -hls_time 10 -hls_playlist_type vod -hls_segment_filename &quot;${outputPath}/segment%03d.ts&quot; -start_number 0 &quot;${hlsPath}&quot;</pre><h3>Frontend Integration</h3><p><strong>1. Video Player Component:</strong></p><ul><li><strong>Using Hls.js:</strong> A JavaScript library to enable HLS playback in browsers that support it.</li><li><strong>Implementation:</strong> Load HLS source and attach it to a video element for smooth playback.</li></ul><p><strong>- hlsPlayer.tsx:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*wVDSaBchj_PZOGsAGwhfRw@2x.jpeg" /></figure><p><strong>- Page.tsx:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*2INYTo5hlvZ1lZhnCs1J4w@2x.jpeg" /></figure><p><strong>2. Error Handling:</strong></p><p><strong>a. CORS Errors:</strong></p><ul><li><strong>Problem:</strong> Browser blocking requests to different origins.</li><li><strong>Solution:</strong> Configure CORS headers in the Express server and update next.config.js to include allowed origins.</li></ul><p><strong>b. Content Security Policy (CSP) Errors:</strong></p><ul><li><strong>Problem:</strong> Media resources being blocked due to CSP settings.</li><li><strong>Solution:</strong> Adjust CSP headers to allow media sources from your server.</li></ul><p><strong>3. Example Code for CSP Configuration:</strong></p><p><strong>next.config.js (without nonce):</strong></p><pre>const cspHeader = `<br>    default-src &#39;self&#39;;<br>    script-src &#39;self&#39; &#39;unsafe-eval&#39; &#39;unsafe-inline&#39;;<br>    style-src &#39;self&#39; &#39;unsafe-inline&#39;;<br>    img-src &#39;self&#39; blob: data:;<br>    font-src &#39;self&#39;;<br>    media-src &#39;self&#39; blob: ${process.env.LOCAL_FRONTEND_URL};<br>    connect-src &#39;self&#39; ${process.env.LOCAL_API_URL};<br>    object-src &#39;none&#39;;<br>    base-uri &#39;self&#39;;<br>    form-action &#39;self&#39;;<br>    frame-ancestors &#39;none&#39;;<br>    upgrade-insecure-requests;<br>`<br> <br>module.exports = {<br>  async headers() {<br>    return [<br>      {<br>        source: &#39;/(.*)&#39;,<br>        headers: [<br>          {<br>            key: &#39;Content-Security-Policy&#39;,<br>            value: cspHeader.replace(/\n/g, &#39;&#39;),<br>          },<br>        ],<br>      },<br>    ]<br>  },<br>}</pre><p><strong>middleware.ts (with nonce):</strong></p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;<br> <br>export function middleware(request: NextRequest) {<br>  const nonce = Buffer.from(crypto.randomUUID()).toString(&#39;base64&#39;)<br>  const cspHeader = `<br>    default-src &#39;self&#39;;<br>    script-src &#39;self&#39; &#39;nonce-${nonce}&#39; &#39;strict-dynamic&#39;;<br>    style-src &#39;self&#39; &#39;nonce-${nonce}&#39;;<br>    img-src &#39;self&#39; blob: data:;<br>    font-src &#39;self&#39;;<br>    object-src &#39;none&#39;;<br>    base-uri &#39;self&#39;;<br>    form-action &#39;self&#39;;<br>    frame-ancestors &#39;none&#39;;<br>    upgrade-insecure-requests;<br>`<br>  // Replace newline characters and spaces<br>  const contentSecurityPolicyHeaderValue = cspHeader<br>    .replace(/\s{2,}/g, &#39; &#39;)<br>    .trim()<br> <br>  const requestHeaders = new Headers(request.headers)<br>  requestHeaders.set(&#39;x-nonce&#39;, nonce)<br> <br>  requestHeaders.set(<br>    &#39;Content-Security-Policy&#39;,<br>    contentSecurityPolicyHeaderValue<br>  )<br> <br>  const response = NextResponse.next({<br>    request: {<br>      headers: requestHeaders,<br>    },<br>  })<br>  response.headers.set(<br>    &#39;Content-Security-Policy&#39;,<br>    contentSecurityPolicyHeaderValue<br>  )<br> <br>  return response<br>}</pre><h3>Challenges &amp; Solutions</h3><p>1. <strong>CORS Configuration:</strong></p><ul><li><strong>Issue:</strong> Browser blocking requests to the backend.</li><li><strong>Resolution:</strong> Updated CORS settings in Express to allow specific origins.</li></ul><p>2. <strong>CSP Errors:</strong></p><ul><li><strong>Issue:</strong> Blocking media resources due to restrictive CSP.</li><li><strong>Resolution:</strong> Adjusted CSP headers in next.config.js and used nonce in middleware.ts.</li></ul><p>3. <strong>Multer File Handling:</strong></p><ul><li><strong>Issue:</strong> Managing large file uploads and unique file naming.</li><li><strong>Resolution:</strong> Configured Multer for file size limits and used UUIDs for unique filenames.</li></ul><h3>Conclusion</h3><p>Building a video streaming platform involves a variety of technologies and overcoming several challenges. By leveraging <strong>Node.js</strong>, <strong>FFmpeg</strong>, <strong>Multer</strong>, and <strong>Next.js</strong>, I was able to create a robust and scalable solution. Despite encountering errors related to CORS, CSP, and file handling, I was able to resolve them and deliver a seamless streaming experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7f14655af6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>