<?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 Piyush Yadav on Medium]]></title>
        <description><![CDATA[Stories by Piyush Yadav on Medium]]></description>
        <link>https://medium.com/@yadavpiyush222?source=rss-30a6e42163cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vEhXZwHEnQIglXGJoxMY5w.jpeg</url>
            <title>Stories by Piyush Yadav on Medium</title>
            <link>https://medium.com/@yadavpiyush222?source=rss-30a6e42163cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:12:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yadavpiyush222/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[How to create a web file downloader that directly writes to the disk]]></title>
            <link>https://medium.com/@yadavpiyush222/how-to-create-a-web-file-downloader-that-directly-writes-to-the-disk-06ca015b8fd9?source=rss-30a6e42163cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/06ca015b8fd9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[disk-write]]></category>
            <category><![CDATA[file-downloader]]></category>
            <dc:creator><![CDATA[Piyush Yadav]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 05:52:22 GMT</pubDate>
            <atom:updated>2025-02-02T06:39:30.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cMUl8IpP4P9JUllzEt-yig.png" /></figure><p>Most of the downloads that we do through websites are reliant on browser memory, i.e. they first download the data to the browser memory and then prompt to save to disk. This is memory consuming and breaks for large files.</p><p>With the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/showSaveFilePicker"><strong>showSaveFilePicker</strong></a> method we can prompt the user to first select the location to download the file and then start the download directly to the disk. Using this we can download any large file we want.</p><p>But it has <strong>limited</strong> Availability as of now, it is only available in <strong>Chrome</strong> and <strong>Edge</strong> browser. This is why I have also included the other method.</p><p>The example below is very simple using HTML, CSS and JavaScript. Download one file at a time by typing the name of the file with extension and hitting the download button. you can check it out here <a href="https://piyushyadav1617.github.io/file-downloader/"><strong>File-downloader</strong></a> and try to download the file named <strong>video.mp4.</strong></p><p>The code for the same is available here <a href="https://github.com/piyushyadav1617/file-downloader"><strong>GitHub</strong></a></p><p>You can check the HTML and the CSS files in the repository, so I can highlight the key concepts used.</p><h4><strong>HTTP `HEAD` request to peek at what we are downloading:</strong></h4><pre>const response = await fetch(url, { method: &#39;HEAD&#39; });</pre><p>This gives us the file size and type without downloading. The URL should be a valid file location and the server should have CORS configured.</p><h4><strong>File Picker:</strong></h4><pre><br>const fileHandle = await showSaveFilePicker({<br> suggestedName: filename,<br> types: [{<br> description: &#39;File&#39;,<br> accept: { [contentType]: [`.${fileExtension}`] }<br> }],<br>});</pre><p>This API shows that familiar save dialog we all know. It returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle"><strong>FileSystemFileHandle</strong></a> — think of it as a ticket to write to that file later.</p><h4><strong>Start the download stream and get the </strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader"><strong>ReadableStreamDefaultReader</strong></a><strong> instance by calling the getReader method on the response body</strong></h4><pre>abortController = new AbortController();<br>const response = await fetch(url, { signal: abortController.signal });<br>if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);<br>const reader = response.body.getReader();<br>.<br>.<br>//inside the while loop, the value is the individual chunk and done is a boolean<br>const { done, value } = await reader.read();</pre><p>Here we created and passed the <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController"><strong>AbortController</strong></a> instance to the fetch, so that we can abort the current stream by clicking on the cancel button.</p><h4><strong>Streaming Data to Disk:</strong></h4><pre>const writer = await fileHandle.createWritable();<br>.<br>.<br>await writer.write(value); // Each chunk of data</pre><p>The writer is like a pipe straight to your disk. Each chunk flows through it as it downloads.</p><h4><strong>Pause/Resume:</strong></h4><pre>if (isPaused) {<br> await new Promise(resolve =&gt; resumeButton.onclick = resolve);<br>}</pre><p>When <strong>isPaused </strong>is true, it waits for the resume button click. The download freezes but doesn’t break the connection. This functionality can be changed later, I started changing but didn’t complete, so something you can try for yourself.</p><h4><strong>Cleanup</strong></h4><pre>if (writer) await writer.close();<br><br>document.body.removeChild(a);<br>URL.revokeObjectURL(url); </pre><p>Always clean up. Close writer, revoke URL and remove the anchor tag.</p><p>The code can be found here: <a href="https://github.com/piyushyadav1617/file-downloader"><strong>GitHub</strong></a> and the live link here: <a href="https://piyushyadav1617.github.io/file-downloader/"><strong>File-downloader</strong></a></p><h4>Conclusion</h4><p>The explanation could be vague for some that is why I have given the code link and MDN doc links for further clarification.</p><p>There could be some edge cases and better ways to do this, so we should explore and share them. Also this can be extended or used to build for React or other libraries for front end.</p><p>There are quite a few under appreciated concepts used here, which can be extremely helpful in some cases, so do read them.</p><p>Thanks <a href="https://www.youtube.com/@SteveGriffith-Prof3ssorSt3v3"><strong>Steve Griffith — Prof3ssorSt3v3</strong></a><strong> </strong>on YouTube for his playlist on Blobs, Files and Streams. I learned a lot from his channel.</p><p><em>Thanks for reading this blog! Don’t forget to leave a comment💬!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06ca015b8fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate Razorpay payment gateway in Next Js 14 app router]]></title>
            <link>https://medium.com/@yadavpiyush222/how-to-integrate-razorpay-payment-gateway-in-next-js-14-app-router-02653384659a?source=rss-30a6e42163cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/02653384659a</guid>
            <category><![CDATA[razorpay]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Piyush Yadav]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 18:21:23 GMT</pubDate>
            <atom:updated>2024-04-06T19:25:04.957Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Workflow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCS9EIQC7bMfE4XEyY-iWA.jpeg" /><figcaption>Razorpay gateway workflow. For more details: <a href="https://razorpay.com/docs/payments/payment-gateway/how-it-works/#how-it-works">How it works</a></figcaption></figure><p>As a developer we need to take care of steps 1, 2, 3 and 5.</p><p>steps before proceeding with the code:</p><ol><li>Signup and login to Razorpay.</li><li>Make sure you are in the testing mode as you are coding.</li><li>Create your key_id and key_secret and paste them as the environment variables in your project.</li></ol><p><strong>Create an order API on your server (STEP 2):</strong></p><ol><li>Install Razorpay with “npm install razorpay”</li><li>Create a route.ts file in app/api/order folder to write the API.</li><li>Paste this code in that file:</li></ol><pre>import Razorpay from &#39;razorpay&#39;;<br>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br><br>const razorpay = new Razorpay({<br> key_id: process.env.key_id!,<br> key_secret: process.env.key_secret,<br>});<br><br>export async function POST(request: NextRequest) {<br> const { amount, currency } = (await request.json()) as {<br>  amount: string;<br>  currency: string;<br> };<br><br> var options = {<br>  amount: amount,<br>  currency: currency,<br>  receipt: &#39;rcp1&#39;,<br> };<br> const order = await razorpay.orders.create(options);<br> console.log(order);<br> return NextResponse.json({ orderId: order.id }, { status: 200 });<br>}</pre><p>This API will be used to create an order on the server side and it will send the orderId to the client. This order id will be used in the checkout.</p><p><strong>Creating an order from the client (STEP 1):</strong></p><ol><li>On your payment route, import the Script tag from next/script either in the layout.tsx or in the page.tsx file and put it like given below. I am using it in the page directly.</li></ol><pre><br>import Script from &#39;next/script&#39;;<br><br>function Payment() {<br>  return (<br>  &lt;&gt;<br>   &lt;Script<br>    id=&quot;razorpay-checkout-js&quot;<br>    src=&quot;https://checkout.razorpay.com/v1/checkout.js&quot;<br>   /&gt;<br>  &lt;/&gt;<br> );<br>}<br><br>export default Payment;</pre><p>This will inject the JavaScript needed for Razorpay to show their checkout window.</p><p>2. Create the function to place an order. In your Payment page paste this code and also create an input and a state variable to let user enter the amount and feed it to the function.</p><pre>const createOrderId = async () =&gt; {<br>  try {<br>   const response = await fetch(&#39;/api/order&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>     &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    body: JSON.stringify({<br>     amount: parseFloat(amount)*100,<br>    })<br>   });<br><br>   if (!response.ok) {<br>    throw new Error(&#39;Network response was not ok&#39;);<br>   }<br><br>   const data = await response.json();<br>   return data.orderId;<br>  } catch (error) {<br>   console.error(&#39;There was a problem with your fetch operation:&#39;, error);<br>  }<br> };</pre><p><strong>Payment checkout (STEP 3):</strong></p><ol><li>For the client you will need to create a function for payment checkout. Paste this function in the payment page. The verify post endpoint is explained later.</li></ol><pre>const processPayment = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>  e.preventDefault();<br>  try {<br>   const orderId: string = await createOrderId();<br>   const options = {<br>    key: process.env.key_id,<br>    amount: parseFloat(amount) * 100,<br>    currency: currency,<br>    name: &#39;name&#39;,<br>    description: &#39;description&#39;,<br>    order_id: orderId,<br>    handler: async function (response: any) {<br>     const data = {<br>      orderCreationId: orderId,<br>      razorpayPaymentId: response.razorpay_payment_id,<br>      razorpayOrderId: response.razorpay_order_id,<br>      razorpaySignature: response.razorpay_signature,<br>     };<br><br>     const result = await fetch(&#39;/api/verify&#39;, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(data),<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>     });<br>     const res = await result.json();<br>     if (res.isOk) alert(&quot;payment succeed&quot;);<br>     else {<br>      alert(res.message);<br>     }<br>    },<br>    prefill: {<br>     name: name,<br>     email: email,<br>    },<br>    theme: {<br>     color: &#39;#3399cc&#39;,<br>    },<br>   };<br>   const paymentObject = new window.Razorpay(options);<br>   paymentObject.on(&#39;payment.failed&#39;, function (response: any) {<br>    alert(response.error.description);<br>   });<br>   paymentObject.open();<br>  } catch (error) {<br>   console.log(error);<br>  }<br> };</pre><p>This function should be called when a user submits the form after filling in the details. The details of different options you can you find here <a href="https://razorpay.com/docs/payments/server-integration/nodejs/payment-gateway/build-integration/">razorpay</a>.</p><p>2. For the verification of payment (STEP 5) you will have to create another API at the endpoint /api/verify. Create a file route.ts in app/api/verify and paste this code:</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br>import crypto from &#39;crypto&#39;;<br><br>const generatedSignature = (<br> razorpayOrderId: string,<br> razorpayPaymentId: string<br>) =&gt; {<br> const keySecret = process.env.key_secret;<br> if (!keySecret) {<br>  throw new Error(<br>   &#39;Razorpay key secret is not defined in environment variables.&#39;<br>  );<br> }<br> const sig = crypto<br>  .createHmac(&#39;sha256&#39;, keySecret)<br>  .update(razorpayOrderId + &#39;|&#39; + razorpayPaymentId)<br>  .digest(&#39;hex&#39;);<br> return sig;<br>};<br><br><br>export async function POST(request: NextRequest) {<br> const { orderCreationId, razorpayPaymentId, razorpaySignature } =<br>  await request.json();<br><br> const signature = generatedSignature(orderCreationId, razorpayPaymentId);<br> if (signature !== razorpaySignature) {<br>  return NextResponse.json(<br>   { message: &#39;payment verification failed&#39;, isOk: false },<br>   { status: 400 }<br>  );<br> }<br> return NextResponse.json(<br>  { message: &#39;payment verified successfully&#39;, isOk: true },<br>  { status: 200 }<br> );<br>}</pre><p>This checks if the signature sent from Razorpay and the signature we generate using key_secret, order id and payment id are same or not.</p><p><strong>Finally your client payment page should look like this:</strong></p><pre>&#39;use client&#39;;<br>import { useState } from &#39;react&#39;;<br>import Script from &#39;next/script&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { Label } from &#39;@/components/ui/label&#39;;<br><br>function Payment() {<br> const [name, setName] = useState(&#39;&#39;);<br> const [email, setEmail] = useState(&#39;&#39;);<br> const [amount, setAmount] = useState(&#39;0&#39;);<br> const [currency, setCurrency] = useState(&#39;INR&#39;);<br> const [loading, setLoading] = useState(false);<br> const createOrderId = async () =&gt; {<br>  try {<br>   const response = await fetch(&#39;/api/order&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>     &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    body: JSON.stringify({<br>     amount: parseFloat(amount) * 100,<br>    }),<br>   });<br><br>   if (!response.ok) {<br>    throw new Error(&#39;Network response was not ok&#39;);<br>   }<br><br>   const data = await response.json();<br>   return data.orderId;<br>  } catch (error) {<br>   console.error(&#39;There was a problem with your fetch operation:&#39;, error);<br>  }<br> };<br>const processPayment = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>  e.preventDefault();<br>  try {<br>   const orderId: string = await createOrderId();<br>   const options = {<br>    key: process.env.key_id,<br>    amount: parseFloat(amount) * 100,<br>    currency: currency,<br>    name: &#39;name&#39;,<br>    description: &#39;description&#39;,<br>    order_id: orderId,<br>    handler: async function (response: any) {<br>     const data = {<br>      orderCreationId: orderId,<br>      razorpayPaymentId: response.razorpay_payment_id,<br>      razorpayOrderId: response.razorpay_order_id,<br>      razorpaySignature: response.razorpay_signature,<br>     };<br><br>     const result = await fetch(&#39;/api/verify&#39;, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(data),<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>     });<br>     const res = await result.json();<br>     if (res.isOk) alert(&quot;payment succeed&quot;);<br>     else {<br>      alert(res.message);<br>     }<br>    },<br>    prefill: {<br>     name: name,<br>     email: email,<br>    },<br>    theme: {<br>     color: &#39;#3399cc&#39;,<br>    },<br>   };<br>   const paymentObject = new window.Razorpay(options);<br>   paymentObject.on(&#39;payment.failed&#39;, function (response: any) {<br>    alert(response.error.description);<br>   });<br>   paymentObject.open();<br>  } catch (error) {<br>   console.log(error);<br>  }<br> };<br><br> <br> return (<br>  &lt;&gt;<br>   &lt;Script<br>    id=&quot;razorpay-checkout-js&quot;<br>    src=&quot;https://checkout.razorpay.com/v1/checkout.js&quot;<br>   /&gt;<br><br>   &lt;section className=&quot;min-h-[94vh] flex flex-col gap-6 h-14 mx-5 sm:mx-10 2xl:mx-auto 2xl:w-[1400px] items-center pt-36 &quot;&gt;<br>    &lt;form<br>     className=&quot;flex flex-col gap-6 w-full sm:w-80&quot;<br>     onSubmit={processPayment}<br>    &gt;<br>     &lt;div className=&quot;space-y-1&quot;&gt;<br>      &lt;Label&gt;Full name&lt;/Label&gt;<br>      &lt;Input<br>       type=&quot;text&quot;<br>       required<br>       value={name}<br>       onChange={(e) =&gt; setName(e.target.value)}<br>      /&gt;<br>     &lt;/div&gt;<br>     &lt;div className=&quot;space-y-1&quot;&gt;<br>      &lt;Label&gt;Email&lt;/Label&gt;<br>      &lt;Input<br>       type=&quot;email&quot;<br>       placeholder=&quot;user@gmail.com&quot;<br>       required<br>       value={email}<br>       onChange={(e) =&gt; setEmail(e.target.value)}<br>      /&gt;<br>     &lt;/div&gt;<br>     &lt;div className=&quot;space-y-1&quot;&gt;<br>      &lt;Label&gt;Amount&lt;/Label&gt;<br>      &lt;div className=&quot;flex gap-2&quot;&gt;<br>       &lt;Input<br>        type=&quot;number&quot;<br>        step=&quot;1&quot;<br>        min={5}<br>        required<br>        value={amount}<br>        onChange={(e) =&gt; setAmount(e.target.value)}<br>       /&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br><br>     &lt;Button type=&quot;submit&quot;&gt;Pay&lt;/Button&gt;<br>    &lt;/form&gt;<br>   &lt;/section&gt;<br>  &lt;/&gt;<br> );<br>}<br><br>export default Payment;</pre><h3>Here is how you might create a products page and add checkout flow:</h3><p>checkout this Github repository where I have created complete payment flow on a products page: <a href="https://github.com/piyushyadav1617/razorpay-next">github://razorpay-next</a></p><h3><strong>Conclusion</strong></h3><p>This is the example where a user will pay after putting in the payment details. Here Order and checkout is done in a single flow. This might not happen usually, for example on an e-commerce platform, the order is created as the page loads and checkout after user action.</p><p>Also ensure you have taken correct security measures before using it in production.</p><p><em>Thanks for reading this blog! Don’t forget to leave a comment💬!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02653384659a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>