<?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 Cedar Daniel on Medium]]></title>
        <description><![CDATA[Stories by Cedar Daniel on Medium]]></description>
        <link>https://medium.com/@cedard686?source=rss-5c3060c26185------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mIv9QFB4RdIgiBzhQMwM_g.jpeg</url>
            <title>Stories by Cedar Daniel on Medium</title>
            <link>https://medium.com/@cedard686?source=rss-5c3060c26185------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:54:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cedard686/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 Integrate Stripe Payment With Supabase Edge Functions Part 2: Recurring Payments…]]></title>
            <link>https://javascript.plainenglish.io/how-to-integrate-stripe-payment-with-supabase-edge-functions-part-2-recurring-payments-7b0d25d2753f?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b0d25d2753f</guid>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[subapase]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 18:54:54 GMT</pubDate>
            <atom:updated>2026-09-16T12:48:25.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Integrate Stripe Payment With Supabase Edge Functions Part 2: Recurring Payments (Subscriptions)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OemLbjwbFPUFasCXe2eGQ.png" /></figure><p>In Part 1, we handled <strong>One-Time</strong> payments using <strong>Stripe</strong> Checkout and Supabase Edge Functions, no dedicated backend server is required. Now it’s time to take things further. Recurring payments are a different beast. Unlike a one-time charge, subscriptions involve ongoing billing cycles, plan management, failed payment handling, and keeping your database in sync with Stripe’s state, all of which happen asynchronously through webhooks. In this part, we’ll wire all of that up using Supabase Edge Functions.</p><p>This article is a continuation of Part 1, which you can find <a href="https://medium.com/javascript-in-plain-english/how-to-integrate-stripe-payment-with-supabase-edge-functions-part-1-one-time-payments-7e266b27cbe0">here</a></p><ol><li><strong>Create A New Edge Function For Subscription</strong></li></ol><p>Within our <strong>Supabase </strong>project, we’ll generate a new edge function to initialize subscription checkout</p><pre>supabase functions new create-subscription-checkout-session</pre><p>2. <strong>Create Products On Stripe</strong></p><p>On your Stripe dashboard, navigate to <strong>Product</strong> <strong>catalogue &gt; Create Product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHvQruftD8ovSB6pV9RAQg.png" /></figure><p>Then fill in the product details in the form, and make sure the pricing is <strong>Recurring, </strong>then click <strong>Add product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBXcEQnzwF0IiOvKn9x5Hg.png" /></figure><p>I went ahead to do this for 2 other plans. At the end of it all, my product list looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQrc068fz8Hzr0dTleuEzw.png" /></figure><p>3. <strong>Update Boilerplate Function To Integrate Stripe</strong></p><p>Now we’ll update our boilerplate that came with the edge function to integrate <strong>Stripe Checkout </strong>for<strong> Subscription.</strong></p><pre>import &quot;@supabase/functions-js/edge-runtime.d.ts&quot;;<br>import { withSupabase } from &quot;@supabase/server&quot;;<br><br>import Stripe from &quot;https://esm.sh/stripe@14?target=denonext&quot;;<br><br>const stripe = new Stripe(Deno.env.get(&quot;STRIPE_SECRET_KEY&quot;) as string, {<br>  // This is needed to use the Fetch API rather than relying on the Node http<br>  // package.<br>  apiVersion: &quot;2023-10-16&quot;,<br>});<br><br>export default {<br>  fetch: withSupabase({ auth: [&quot;publishable&quot;, &quot;secret&quot;] }, async (req, ctx) =&gt; {<br>    const { email, firstName, lastName, planName, line_items } = await req<br>      .json();<br><br>    const success_url = `${<br>      Deno.env.get(&quot;STRIPE_SUCCESS_URL&quot;)<br>    }?session_id={CHECKOUT_SESSION_ID}`;<br><br>    const cancel_url = Deno.env.get(&quot;STRIPE_CANCEL_URL&quot;);<br><br>    const session = await stripe.checkout.sessions.create({<br>      line_items,<br>      mode: &quot;subscription&quot;,<br>      success_url,<br>      cancel_url,<br>      customer_email: email,<br>      metadata: { email, firstName, lastName, planName },<br>      subscription_data: {<br>        metadata: { email, firstName, lastName, planName },<br>      },<br>    });<br><br>    return Response.json({<br>      message:<br>        `Checkout session created successfully for ${firstName} (${email}).`,<br>      url: session.url,<br>    });<br>  }),<br>};</pre><p>4. <strong>Test Implementation Locally</strong></p><p>In our Stripe dashboard, we’ll click on the products we created and then click on the price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_nBkVWXYExI6x1ebJBkSA.png" /></figure><p>Then copy over the price ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L58A40BP0wc0cCdguVjQhg.png" /></figure><p>After retrieving the price IDs, we’ll head over to <strong>Postman </strong>and call the edge function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9QeyZsI6mnun8SiEnh8qg.png" /></figure><p>Then we go ahead and click the <strong>url</strong> returned in the response and proceed to payment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZhS_5ZLCxR_H8ZJ9rR_fA.png" /></figure><p>On successful payment, we get redirected to our success page whose URL we set in the <strong>.env </strong>as <strong>STRIPE_SUCCESS_URL </strong>at the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*bBzTQzjNJKfB3y_byY9xmQ.jpeg" /></figure><p>5. <strong>Handling Webhook Events</strong></p><p>The next step is to handle webhook events. In our project, go ahead and create a new function for that, like so.</p><pre>supabase functions new stripe-subscription-webhook</pre><p>Next, we update the function to this</p><pre>// Import via named specifier resolved by this function&#39;s deno.json import map<br>import Stripe from &quot;stripe&quot;;<br><br>const stripe = new Stripe(Deno.env.get(&quot;STRIPE_SECRET_KEY&quot;) as string, {<br>  // This is needed to use the Fetch API rather than relying on the Node http<br>  // package.<br>  apiVersion: &quot;2023-10-16&quot;,<br>});<br>// This is needed in order to use the Web Crypto API in Deno.<br>const cryptoProvider = Stripe.createSubtleCryptoProvider();<br><br>Deno.serve(async (request) =&gt; {<br>  const signature = request.headers.get(&quot;Stripe-Signature&quot;);<br><br>  // First step is to verify the event. The .text() method must be used as the<br>  // verification relies on the raw request body rather than the parsed JSON.<br>  const body = await request.text();<br>  let receivedEvent: Stripe.Event;<br>  try {<br>    receivedEvent = await stripe.webhooks.constructEventAsync(<br>      body,<br>      signature!,<br>      Deno.env.get(&quot;STRIPE_WEBHOOK_SIGNING_SECRET&quot;)!,<br>      undefined,<br>      cryptoProvider,<br>    );<br>  } catch (err: unknown) {<br>    const msg = err instanceof Error ? err.message : String(err);<br>    return new Response(msg, { status: 400 });<br>  }<br>  console.log(`🔔 Event received: ${receivedEvent.id}`);<br><br>  // If it&#39;s a successful charge, send a confirmation email via Resend<br><br>  const events = [<br>    &quot;customer.subscription.created&quot;,<br>    &quot;customer.subscription.updated&quot;,<br>  ];<br><br>  if (events.includes(receivedEvent.type)) {<br>    const subscription = receivedEvent.data.object as Stripe.Subscription;<br><br>    const email = subscription.metadata?.email ||<br>      null;<br><br>    if (!email) {<br>      console.warn(<br>        &quot;No email found on subscription, skipping confirmation email&quot;,<br>        subscription.id,<br>      );<br>    }<br><br>    if (email) {<br>      const plan = subscription.items.data[0];<br>      const price = plan.price;<br>      const amountCents = price.unit_amount || 0;<br>      const currency = (price.currency || &quot;usd&quot;).toUpperCase();<br>      const amount = (Number(amountCents) / 100).toFixed(2);<br><br>      const firstName = subscription.metadata?.firstName || null;<br>      const planName = subscription.metadata?.planName || &quot;your plan&quot;;<br><br>      const subject = `Your subscription to ${planName} is confirmed!`;<br><br>      const text =<br>        `Hi ${firstName},\n\nThis email confirms your subscription to ${planName} for ${currency} ${amount}.\n\nSubscription ID: ${subscription.id}\n\nThank you for subscribing!`;<br><br>      const RESEND_API_KEY = Deno.env.get(&quot;RESEND_API_KEY&quot;);<br><br>      const RESEND_FROM = Deno.env.get(&quot;RESEND_EMAIL_FROM&quot;);<br><br>      if (!RESEND_API_KEY) {<br>        console.warn(<br>          &quot;RESEND_API_KEY not configured, skipping email notification&quot;,<br>        );<br>        return new Response(<br>          JSON.stringify({ ok: true, message: &quot;Email sending skipped&quot; }),<br>          { status: 200 },<br>        );<br>      }<br><br>      const resp = await fetch(&quot;https://api.resend.com/emails&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          Authorization: `Bearer ${RESEND_API_KEY}`,<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify({<br>          from: RESEND_FROM,<br>          to: email,<br>          subject,<br>          text,<br>        }),<br>      });<br><br>      if (!resp.ok) {<br>        const errBody = await resp.text().catch(() =&gt; &quot;&quot;);<br>        console.error(&quot;Resend send error&quot;, resp.status, errBody);<br>      } else {<br>        console.log(`✅ Confirmation email sent to ${email}`);<br>      }<br>    }<br>  }<br><br>  return new Response(JSON.stringify({ ok: true }), { status: 200 });<br>});</pre><p>6. <strong>Create Webhook On Stripe</strong></p><p>Next, we use <strong>ngrok </strong>to tunnel the our webhook endpoint, so it can be accessed from stripe.</p><pre>ngrok http 54321 </pre><p>Now we head over to stripe and create a new webhook and pass the <strong>url</strong> gotten back from <strong>ngrok</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAK1bFDp0pAah0Tq5jZD5w.png" /></figure><p>Then we’ll go ahead to set it to listen to events <strong>customer.subscription.created, customer.subscription.updated</strong> like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4AreGVyOxjK43FJQK4ghA.png" /></figure><p>Next, we copy over the webhook sign in secret and save in our <strong>.env </strong>with the variable name <strong>STRIPE_WEBHOOK_SIGNING_SECRET</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WZFahAnhSdSD_JSsqvseg.png" /></figure><p>Now, we’ll retry the entire payment flow and we should end up with this email</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXzZZiS-NRdQDmQyo6veuw.png" /></figure><p>Here’s a conclusion that wraps up the tutorial while naturally leading into future improvements:</p><h3>Conclusion</h3><p>Recurring payments introduce a new level of complexity compared to one-time payments, but with <strong>Stripe Checkout</strong>, <strong>Supabase Edge Functions</strong>, and <strong>webhooks</strong>, you can build a reliable subscription system without maintaining a traditional backend server.</p><p>In this article, we’ve created a subscription checkout session, configured recurring products in Stripe, handled asynchronous webhook events, verified webhook signatures for security, and sent confirmation emails when subscriptions are created or updated. By relying on Stripe as the source of truth and using webhooks to react to subscription events, your application can stay in sync with every stage of the subscription lifecycle.</p><p>This implementation provides a solid foundation, but there’s still plenty you can build on. In a production application, you may also want to handle events such as failed payments, <strong>subscription cancellations</strong>, renewals, <strong>plan upgrades</strong> and <strong>downgrades</strong>, and update your <strong>database</strong> to reflect the user’s current subscription status. You can also build a customer billing portal to allow users to manage their subscriptions without leaving your application.</p><p>With these building blocks in place, you now have everything you need to integrate recurring payments into your Supabase-powered applications using a serverless architecture. From here, you can focus on delivering value to your users while Stripe takes care of the complexities of recurring billing.</p><p><strong>Github Repo:- </strong><a href="https://github.com/Cedar1000/stripe-supabase-edge-function">https://github.com/Cedar1000/stripe-supabase-edge-function</a></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b0d25d2753f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-integrate-stripe-payment-with-supabase-edge-functions-part-2-recurring-payments-7b0d25d2753f">How To Integrate Stripe Payment With Supabase Edge Functions Part 2: Recurring Payments…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Integrate Stripe Payment With Supabase Edge Functions Part 1: One-Time Payments]]></title>
            <link>https://javascript.plainenglish.io/how-to-integrate-stripe-payment-with-supabase-edge-functions-part-1-one-time-payments-7e266b27cbe0?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e266b27cbe0</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 19:59:58 GMT</pubDate>
            <atom:updated>2026-10-07T13:27:14.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tecEEZR94MHWw8lwDbevQ.png" /></figure><p>Setting up payments shouldn’t require spinning up a whole backend. Yet most developers end up doing exactly that: a dedicated server, extra deployments, more infrastructure to maintain, just to handle a <strong>Stripe</strong> checkout. In this article, I’ll be showing step-by-step how to set up <strong>Stripe</strong> payments using <strong>Supabase</strong> <strong>Edge Functions.</strong></p><ol><li><strong>Install The Supabase CLI</strong></li></ol><p>The link provided will guide you on how to install the Supabase CLI on your machine, depending on your OS (macOS, Windows, Linux, etc.).</p><p>After successful installation, go ahead and run</p><pre>supabase --version</pre><p>If the installation is successful, you should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWG3GbzQrjmc02FczUnDcQ.png" /></figure><p>2.<strong> Install Deno</strong></p><p>Use this link to install Deno on your machine <a href="https://docs.deno.com/runtime/getting_started/installation/"><strong>here</strong></a><strong>.</strong></p><p>Once that is done, verify successful installation by running</p><pre>deno --version</pre><p>You should see something that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*4vlvbLNDGaDWEEmTmbiK0A.png" /></figure><p>3. <strong>Create New Supabase Project</strong></p><p>Initialize a new Supabase project in your current directory.</p><pre>mkdir stripe-supabase-project<br>cd stripe-supabase-project<br>supabase init</pre><p>4. <strong>Create Your First Function</strong></p><p>Within your project, generate a new Edge Function with a basic template</p><pre>supabase functions new create-checkout-session</pre><p>5. <strong>Test Boilerplate Code Locally</strong></p><p>Next, we’re going to simplify the boilerplate code in the edge function to this</p><pre>import &quot;@supabase/functions-js/edge-runtime.d.ts&quot;;<br>import { withSupabase } from &quot;@supabase/server&quot;;<br><br>export default {<br>  fetch: withSupabase({ auth: [&quot;publishable&quot;, &quot;secret&quot;] }, async (req, ctx) =&gt; {<br>    const { name } = await req.json();<br><br>    return Response.json({<br>      message:<br>        `Hello ${name}! this is a checkout session created with Supabase Functions!`,<br>    });<br>  }),<br>};</pre><p>Then we’ll run the function locally</p><pre>supabase start<br>supabase functions serve create-checkout-session</pre><p><strong>NOTE:- </strong>Supabase Edge Functions require Docker to run locally on your machine, so make sure you have <strong>Docker</strong> running.</p><p>Open a new terminal and test your function with curl. You can find your local Publishable key by running supabase start, or you can find the complete curl command already in functions/create-checkout-session/index.ts.</p><pre>curl -i --location --request POST &#39;http://127.0.0.1:54321/functions/v1/create-checkout-session&#39; \<br>    --header &#39;apiKey: &lt;SUPABASE_PUBLISHABLE_KEY&gt;&#39; \<br>    --data &#39;{&quot;name&quot;:&quot;John&quot;}&#39;</pre><p>If we copy the curl and paste it into Postman, we should have this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gz5g7WPvS7jAugxxTWglgw.png" /></figure><p>6. <strong>Retrieve Stripe Credentials</strong></p><p>Log in to your Stripe account dashboard, head over to <strong>Developers </strong>&gt;<strong> API Keys. </strong>For the purpose of this article, we’ll be using the standard keys, but in a production environment, the best practice is to go ahead and create a <strong>restricted key </strong>like so<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFVHxjfhiuV2VpLmB-ka5g.png" /></figure><p>But in this case, we’ll go with <strong>standard keys</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fK3fDsUozYganGcJ3SmerA.png" /></figure><p>We’ll go ahead and create a .env file placed at supabase/functions/.envThen, copy over the <strong>secret key </strong>and save it under the variable name <strong>STRIPE_SECRET_KEY. </strong>We’ll also proceed to create .env variables <strong>STRIPE_SUCCESS_URL </strong>and <strong>STRIPE_CANCEL_URL, </strong>so it’ll then look like this</p><pre>STRIPE_SECRET_KEY=your-secret-key<br>STRIPE_SUCCESS_URL=http://localhost:5173/success<br>STRIPE_CANCEL_URL=http://localhost:5173/cancel</pre><p>7. <strong>Create Products On Stripe</strong></p><p>On your Stripe dashboard, navigate to <strong>Product</strong> <strong>catalogue</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*JnCuuaWFZ3LAsBFtZhf34g.png" /></figure><p>Then go ahead and create a product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*T1LtIOQIZUcyjXz-9Z9nIw.png" /></figure><p>Then fill in the product details in the form, and make sure the pricing is O<strong>ne-off, </strong>then click <strong>Add product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTYduwNtV_r5tG_xPgRtyQ.png" /></figure><p>I went ahead to do this for 2 other products. At the end of it all, my product list looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEqTSX_mOPtk9Qs6Q6pfDg.png" /></figure><p>8. <strong>Update Boilerplate Function To Integrate Stripe</strong></p><p>Now we’ll update our boilerplate function to integrate <strong>Stripe Checkout.</strong></p><pre>import &quot;@supabase/functions-js/edge-runtime.d.ts&quot;;<br>import { withSupabase } from &quot;@supabase/server&quot;;<br><br>import Stripe from &quot;https://esm.sh/stripe@14?target=denonext&quot;;<br><br>const stripe = new Stripe(Deno.env.get(&quot;STRIPE_SECRET_KEY&quot;) as string, {<br>  // This is needed to use the Fetch API rather than relying on the Node http<br>  // package.<br>  apiVersion: &quot;2023-10-16&quot;,<br>});<br><br>export default {<br>  fetch: withSupabase({ auth: [&quot;publishable&quot;, &quot;secret&quot;] }, async (req, ctx) =&gt; {<br>    const { email, firstName, lastName, address, line_items } = await req<br>      .json();<br><br>    const success_url = `${<br>      Deno.env.get(&quot;STRIPE_SUCCESS_URL&quot;)<br>    }?session_id={CHECKOUT_SESSION_ID}`;<br><br>    const cancel_url = Deno.env.get(&quot;STRIPE_CANCEL_URL&quot;);<br><br>    const session = await stripe.checkout.sessions.create({<br>      line_items,<br>      mode: &quot;payment&quot;,<br>      success_url,<br>      cancel_url,<br>      customer_email: email,<br>      metadata: { email, firstName, lastName, address },<br>    });<br><br>    return Response.json({<br>      message:<br>        `Checkout session created successfully for ${firstName} (${email}).`,<br>      url: session.url,<br>    });<br>  }),<br>};</pre><p>9. <strong>Test Implementation Locally</strong></p><p>In our Stripe dashboard, we’ll click on the products we created and then click on the price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGJhc9CaVTBtL0UdRMmsag.png" /></figure><p>Then copy over the price ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMQz3PAHO8IBwx-QPvUYsA.png" /></figure><p>We’ll do that to retrieve the price IDs of the other products and head over to <strong>Postman </strong>and call the edge function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsIU6WqrEk6eJe4Q7BNhRg.png" /></figure><p>Then we go ahead and click the <strong>url</strong> returned in the response and proceed to payment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bq78zJuAVJro-kqhgtmglw.png" /></figure><p>On successful payment, we get redirected to our success page whose URL we set in the <strong>.env </strong>as <strong>STRIPE_SUCCESS_URL </strong>at the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FO2qkjA36CM7wDh14C7p2g.png" /></figure><p>10. <strong>Handling Webhook Events</strong></p><p>The next step is to handle webhook events. In our project, go ahead and create a new function for that, like so.</p><pre>supabase functions new stripe-webhook</pre><p>Then we’ll modify the boilerplate code to this</p><pre>// Import via bare specifier thanks to the import_map.json file.<br>import Stripe from &quot;https://esm.sh/stripe@14?target=denonext&quot;;<br><br>const stripe = new Stripe(Deno.env.get(&quot;STRIPE_API_KEY&quot;) as string, {<br>  // This is needed to use the Fetch API rather than relying on the Node http<br>  // package.<br>  apiVersion: &quot;2023-10-16&quot;,<br>});<br>// This is needed in order to use the Web Crypto API in Deno.<br>const cryptoProvider = Stripe.createSubtleCryptoProvider();<br><br>console.log(&quot;Hello from Stripe Webhook!&quot;);<br><br>Deno.serve(async (request) =&gt; {<br>  const signature = request.headers.get(&quot;Stripe-Signature&quot;);<br><br>  // First step is to verify the event. The .text() method must be used as the<br>  // verification relies on the raw request body rather than the parsed JSON.<br>  const body = await request.text();<br>  let receivedEvent;<br>  try {<br>    receivedEvent = await stripe.webhooks.constructEventAsync(<br>      body,<br>      signature!,<br>      Deno.env.get(&quot;STRIPE_WEBHOOK_SIGNING_SECRET&quot;)!,<br>      undefined,<br>      cryptoProvider,<br>    );<br>  } catch (err) {<br>    return new Response(err.message, { status: 400 });<br>  }<br>  console.log(`🔔 Event received: ${receivedEvent.id}`);<br>  return new Response(JSON.stringify({ ok: true }), { status: 200 });<br>});</pre><p>12. <strong>Create a Webhook In Stripe</strong></p><p>In the Stripe dashboard, head over to <strong>Developers &gt; Webhooks, </strong>then click on the <strong>Add Destination </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWrSRpD9PEw3c4wYLJhjWQ.png" /></figure><p>Then we’ll set it to listen to the events <strong>charge.failed </strong>and <strong>charge.succeeded </strong>like so</p><p>Then, we choose the webhook endpoint option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLktUq0Cw-QTwB7AP1YOTg.png" /></figure><p>The edge function runs on <a href="http://127.0.0.1:54321/">http://127.0.0.1:54321</a>. We’ll use <strong>ngrok </strong>to tunnel that port like so</p><pre>ngrok http 54321</pre><p>Then copy the link obtained from the output and paste it in the form below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2EZ2AFzIt1S7KgkeQFTPw.png" /></figure><p>Then we’ll obtain the Webhook Signing Secret and store it in our <strong>.env </strong>as <strong>STRIPE_WEBHOOK_SIGNING_SECRET.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoXo3QBgnRU6OEOqNNK1fA.png" /></figure><p>12. <strong>Modify Edge Function To Include Email Sending Functionality</strong></p><p>We’ll add email sending functionality with <a href="https://notify.cx/"><strong>Notify</strong></a> to our webhook, we’ll update our <strong>.env </strong>to include</p><pre>NOTIFY_API_KEY=your-notify-api-key<br>NOTIFY_EMAIL_FROM=your-notify-email-from</pre><p>Then we’ll update the edge function like so:</p><pre>// Import via named specifier resolved by this function&#39;s deno.json import map<br>import Stripe from &quot;stripe&quot;;<br><br>const stripe = new Stripe(Deno.env.get(&quot;STRIPE_SECRET_KEY&quot;) as string, {<br>  // This is needed to use the Fetch API rather than relying on the Node http<br>  // package.<br>  apiVersion: &quot;2023-10-16&quot;,<br>});<br>// This is needed in order to use the Web Crypto API in Deno.<br>const cryptoProvider = Stripe.createSubtleCryptoProvider();<br><br>console.log(&quot;Hello from Stripe Webhook!&quot;);<br><br>// Narrow type for the subset of charge fields we use here<br>type Charge = {<br>  id?: string;<br>  amount?: number;<br>  amount_captured?: number;<br>  currency?: string;<br>  receipt_email?: string;<br>  billing_details?: { email?: string; name?: string };<br>  metadata?: { [key: string]: string };<br>  payment_method_details?: { card?: { last4?: string } };<br>};<br><br>Deno.serve(async (request) =&gt; {<br>  const signature = request.headers.get(&quot;Stripe-Signature&quot;);<br><br>  // First step is to verify the event. The .text() method must be used as the<br>  // verification relies on the raw request body rather than the parsed JSON.<br>  const body = await request.text();<br>  let receivedEvent;<br>  try {<br>    receivedEvent = await stripe.webhooks.constructEventAsync(<br>      body,<br>      signature!,<br>      Deno.env.get(&quot;STRIPE_WEBHOOK_SIGNING_SECRET&quot;)!,<br>      undefined,<br>      cryptoProvider,<br>    );<br>  } catch (err: unknown) {<br>    const msg = err instanceof Error ? err.message : String(err);<br>    return new Response(msg, { status: 400 });<br>  }<br>  console.log(`🔔 Event received: ${receivedEvent.id}`);<br><br>  // If it&#39;s a successful charge, send a confirmation email via Notify<br><br>  if (receivedEvent.type === &quot;charge.succeeded&quot;) {<br>    const charge = receivedEvent.data.object as Charge;<br><br>    const email = charge?.metadata?.email ||<br>      null;<br><br>    if (!email) {<br>      console.warn(<br>        &quot;No email found on charge, skipping confirmation email&quot;,<br>        charge.id,<br>      );<br>    }<br><br>    if (email) {<br>      const amountCents = charge.amount || 0;<br>      const currency = (charge.currency || &quot;usd&quot;).toUpperCase();<br>      const amount = (Number(amountCents) / 100).toFixed(2);<br><br>      const firstName = charge.metadata?.firstName || null;<br><br>      const subject = `Payment received — ${currency} ${amount}`;<br><br>      const text =<br>        `Hi ${firstName},\n\nWe received your payment of ${currency} ${amount}.\n\nCharge ID: ${charge.id}\nLast4: ${<br>          charge.payment_method_details?.card?.last4 || &quot;N/A&quot;<br>        }\n\nThank you!`;<br><br>      const NOTIFY_API_KEY = Deno.env.get(&quot;NOTIFY_API_KEY&quot;);<br><br>      const NOTIFY_FROM = Deno.env.get(&quot;NOTIFY_EMAIL_FROM&quot;);<br><br>      if (!NOTIFY_API_KEY) {<br>        console.warn(&quot;NOTIFY_API_KEY not configured, skipping email&quot;);<br>        return new Response(JSON.stringify({ ok: true }), { status: 200 });<br>      }<br><br>      const resp = await fetch(&quot;https://notify.cx/api/email/send&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;x-api-key&quot;: NOTIFY_API_KEY,<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify({<br>          from: NOTIFY_FROM,<br>          to: email,<br>          subject,<br>          message: text,<br>        }),<br>      });<br><br>      if (!resp.ok) {<br>        const errBody = await resp.text().catch(() =&gt; &quot;&quot;);<br>        console.error(&quot;Notify send error&quot;, resp.status, errBody);<br>      } else {<br>        console.log(`✅ Confirmation email sent to ${email}`);<br>      }<br>    }<br>  }<br><br>  return new Response(JSON.stringify({ ok: true }), { status: 200 });<br>});</pre><p>After this, we run the command to serve the webhook edge function, this time with the <strong>— no-verify-jwt </strong>flag. The reason is that by default, Supabase Edge Functions require a valid JWT in the Authorization header. Stripe webhooks cannot provide this token, so Supabase rejects the request with a 401 error</p><pre>supabase functions --no-verify-jwt serve stripe-webhook</pre><p>When we test the flow again, we should end up with an email that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4I-a4DAQjNaQ4MNa-BSoA.png" /></figure><p>13. <strong>Deployment</strong></p><p>First, login to the CLI if you haven’t already, and authenticate with Supabase. This opens your browser to authenticate with Supabase; complete the login process in your browser.</p><pre>supabase login</pre><p>Next, go to your <strong>Supabase</strong> dashboard and create a new project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut7WI2MMlTzMdrj9G9VQXQ.png" /></figure><p>In your CLI, run</p><pre>supabase projects list</pre><p>Next, copy your project ID from the output, then connect your local project to your remote Supabase project. Replace YOUR_PROJECT_ID with the ID from the previous step.</p><pre>supabase link --project-ref [YOUR_PROJECT_ID]</pre><p>Set your <strong>.env </strong>variables</p><pre>supabase secrets set STRIPE_SECRET_KEY=sk_test_...<br>supabase secrets set STRIPE_WEBHOOK_SIGNING_SECRET=whsec_...<br>supabase secrets set NOTIFY_API_KEY=key_...<br>supabase secrets set NOTIFY_FROM=you@example.com</pre><p>Then we deploy the functions to <strong>Supabase</strong> like so:</p><pre>supabase functions deploy</pre><p>14. <strong>BONUS: </strong>Frontend Implementation</p><p>Let’s create a simple <strong>React.js</strong> application and call these edge functions from there</p><pre>npm create vite@latest stripe-frontend -- --template react-ts</pre><p>In our <strong>App.tsx,</strong> let’s create a dataset of products with their corresponding <strong>priceId</strong> from Stripe, and then hook it up into a UI like so</p><pre>import { useState } from &#39;react&#39;;<br>import headphonesImg from &#39;./assets/products/headphones.webp&#39;;<br>import jordansImg from &#39;./assets/products/jordans.webp&#39;;<br>import tshirtsImg from &#39;./assets/products/t-shirts.webp&#39;;<br>import &#39;./App.css&#39;;<br><br>type CartItem = {<br>  id: string;<br>  name: string;<br>  description: string;<br>  price: number;<br>  quantity: number;<br>  image: string;<br>  color: string;<br>  size: string;<br>  priceId?: string;<br>};<br><br>const initialCartItems: CartItem[] = [<br>  {<br>    id: &#39;headphones&#39;,<br>    name: &#39;Sleek Headphones&#39;,<br>    description: &#39;Noise-cancelling over-ear headphones with premium comfort.&#39;,<br>    price: 39,<br>    quantity: 1,<br>    image: headphonesImg,<br>    color: &#39;Matte Black&#39;,<br>    size: &#39;One Size&#39;,<br>    priceId: &#39;price_1TeDr4F4E7zCE0XZYF3Q6QLp&#39;,<br>  },<br>  {<br>    id: &#39;jordans&#39;,<br>    name: &#39;Classic Jordans&#39;,<br>    description: &#39;Signature basketball sneakers with bold streetwear style.&#39;,<br>    price: 99,<br>    quantity: 1,<br>    image: jordansImg,<br>    color: &#39;White / Red&#39;,<br>    size: &#39;US 10&#39;,<br>    priceId: &#39;price_1TeDo8F4E7zCE0XZ0gCqcWhr&#39;,<br>  },<br>  {<br>    id: &#39;tshirt&#39;,<br>    name: &#39;Graphic Tee&#39;,<br>    description: &#39;Soft cotton tee with a modern fit and vivid print.&#39;,<br>    price: 20,<br>    quantity: 2,<br>    image: tshirtsImg,<br>    color: &#39;Cream&#39;,<br>    size: &#39;Large&#39;,<br>    priceId: &#39;price_1TeDubF4E7zCE0XZLj6fRh9B&#39;,<br>  },<br>];<br><br>const formatPrice = (value: number) =&gt; `$${value.toFixed(2)}`;<br><br>function App() {<br>  const [items, setItems] = useState&lt;CartItem[]&gt;(initialCartItems);<br><br>  const updateQuantity = (id: string, delta: number) =&gt; {<br>    setItems((currentItems) =&gt;<br>      currentItems.map((item) =&gt;<br>        item.id === id<br>          ? { ...item, quantity: Math.max(1, item.quantity + delta) }<br>          : item,<br>      ),<br>    );<br>  };<br><br>  const removeItem = (id: string) =&gt; {<br>    setItems((currentItems) =&gt; currentItems.filter((item) =&gt; item.id !== id));<br>  };<br><br>  const subtotal = items.reduce(<br>    (sum, item) =&gt; sum + item.price * item.quantity,<br>    0,<br>  );<br><br>  const total = subtotal;<br><br>  return (<br>    &lt;div className=&quot;cart-page&quot;&gt;<br>      &lt;header className=&quot;cart-header&quot;&gt;<br>        &lt;div&gt;<br>          &lt;p className=&quot;eyebrow&quot;&gt;Shopping cart&lt;/p&gt;<br>          &lt;h1&gt;Your order is ready&lt;/h1&gt;<br>          &lt;p className=&quot;intro&quot;&gt;<br>            Review your items and complete checkout with confidence.<br>          &lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;cart-status&quot;&gt;<br>          &lt;span&gt;{items.length} items&lt;/span&gt;<br>          &lt;span&gt;Free shipping over $150&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;main className=&quot;cart-grid&quot;&gt;<br>        &lt;section className=&quot;cart-items&quot;&gt;<br>          &lt;div className=&quot;section-heading&quot;&gt;<br>            &lt;h2&gt;Cart items&lt;/h2&gt;<br>            &lt;p&gt;Tap through each product for details and pricing.&lt;/p&gt;<br>          &lt;/div&gt;<br><br>          &lt;ul&gt;<br>            {items.map((item) =&gt; (<br>              &lt;li key={item.id} className=&quot;cart-item&quot;&gt;<br>                &lt;img src={item.image} alt={item.name} /&gt;<br>                &lt;div className=&quot;item-body&quot;&gt;<br>                  &lt;div className=&quot;item-meta&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;p className=&quot;item-name&quot;&gt;{item.name}&lt;/p&gt;<br>                      &lt;p className=&quot;item-variant&quot;&gt;<br>                        {item.color} · {item.size}<br>                      &lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;p className=&quot;item-price&quot;&gt;{formatPrice(item.price)}&lt;/p&gt;<br>                  &lt;/div&gt;<br>                  &lt;div className=&quot;item-footer&quot;&gt;<br>                    &lt;div className=&quot;quantity-controls&quot;&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;quantity-button&quot;<br>                        onClick={() =&gt; updateQuantity(item.id, -1)}<br>                        disabled={item.quantity &lt;= 1}<br>                      &gt;<br>                        −<br>                      &lt;/button&gt;<br>                      &lt;span&gt;{item.quantity}&lt;/span&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;quantity-button&quot;<br>                        onClick={() =&gt; updateQuantity(item.id, 1)}<br>                      &gt;<br>                        +<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;item-actions&quot;&gt;<br>                      &lt;p className=&quot;item-total&quot;&gt;<br>                        {formatPrice(item.price * item.quantity)}<br>                      &lt;/p&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;button-link&quot;<br>                        onClick={() =&gt; removeItem(item.id)}<br>                      &gt;<br>                        Remove<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        &lt;/section&gt;<br><br>        &lt;aside className=&quot;cart-summary&quot;&gt;<br>          &lt;div className=&quot;summary-card&quot;&gt;<br>            &lt;p className=&quot;summary-title&quot;&gt;Order summary&lt;/p&gt;<br>            &lt;div className=&quot;summary-row&quot;&gt;<br>              &lt;span&gt;Subtotal&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(subtotal)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;summary-row&quot;&gt;<br>              &lt;span&gt;Shipping&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(shipping)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;summary-total&quot;&gt;<br>              &lt;span&gt;Total&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(total)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;button type=&quot;button&quot; className=&quot;checkout-button&quot;&gt;<br>              Checkout now<br>            &lt;/button&gt;<br>            &lt;p className=&quot;summary-note&quot;&gt;<br>              Secure payment, fast delivery, and easy returns.<br>            &lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/aside&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Add a little styling</p><pre>.cart-page {<br>  padding: 48px 32px;<br>  max-width: 1180px;<br>  margin: 0 auto;<br>  color: var(--text-h);<br>}<br><br>.cart-header {<br>  display: flex;<br>  justify-content: space-between;<br>  gap: 32px;<br>  align-items: flex-start;<br>  margin-bottom: 40px;<br><br>  @media (max-width: 900px) {<br>    flex-direction: column;<br>    gap: 20px;<br>  }<br>}<br><br>... and more</pre><p>Then we should have a UI that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7muU4ivO76byqdXhp9VNw.png" /></figure><p>Install the <strong>Supabase</strong> Client</p><pre>npm install @supabase/supabase-js</pre><p>In your <strong>Supabase</strong> project, head over to <strong>settings &gt; API Keys </strong>and retrieve and set them up like so</p><pre>// utils/supabase.ts<br><br>import { createClient } from &#39;@supabase/supabase-js&#39;;<br><br>const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;<br>const supabaseKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;<br><br>export const supabase = createClient(supabaseUrl, supabaseKey);</pre><p>Now we’ll modify the <strong>App.tsx</strong> to integrate this like so</p><pre>import { useState } from &#39;react&#39;;<br>import headphonesImg from &#39;./assets/products/headphones.webp&#39;;<br>import jordansImg from &#39;./assets/products/jordans.webp&#39;;<br>import tshirtsImg from &#39;./assets/products/t-shirts.webp&#39;;<br>import &#39;./App.css&#39;;<br><br>import { supabase } from &#39;./utils/supabase&#39;;<br><br>type CartItem = {<br>  id: string;<br>  name: string;<br>  description: string;<br>  price: number;<br>  quantity: number;<br>  image: string;<br>  color: string;<br>  size: string;<br>  priceId?: string;<br>};<br><br>type CheckoutForm = {<br>  firstName: string;<br>  lastName: string;<br>  email: string;<br>  address: string;<br>};<br><br>const initialCheckoutForm: CheckoutForm = {<br>  firstName: &#39;&#39;,<br>  lastName: &#39;&#39;,<br>  email: &#39;&#39;,<br>  address: &#39;&#39;,<br>};<br><br>const initialCartItems: CartItem[] = [<br>  {<br>    id: &#39;headphones&#39;,<br>    name: &#39;Sleek Headphones&#39;,<br>    description: &#39;Noise-cancelling over-ear headphones with premium comfort.&#39;,<br>    price: 39,<br>    quantity: 1,<br>    image: headphonesImg,<br>    color: &#39;Matte Black&#39;,<br>    size: &#39;One Size&#39;,<br>    priceId: &#39;price_1TeDr4F4E7zCE0XZYF3Q6QLp&#39;,<br>  },<br>  {<br>    id: &#39;jordans&#39;,<br>    name: &#39;Classic Jordans&#39;,<br>    description: &#39;Signature basketball sneakers with bold streetwear style.&#39;,<br>    price: 99,<br>    quantity: 1,<br>    image: jordansImg,<br>    color: &#39;White / Red&#39;,<br>    size: &#39;US 10&#39;,<br>    priceId: &#39;price_1TeDo8F4E7zCE0XZ0gCqcWhr&#39;,<br>  },<br>  {<br>    id: &#39;tshirt&#39;,<br>    name: &#39;Graphic Tee&#39;,<br>    description: &#39;Soft cotton tee with a modern fit and vivid print.&#39;,<br>    price: 20,<br>    quantity: 2,<br>    image: tshirtsImg,<br>    color: &#39;Cream&#39;,<br>    size: &#39;Large&#39;,<br>    priceId: &#39;price_1TeDubF4E7zCE0XZLj6fRh9B&#39;,<br>  },<br>];<br><br>const formatPrice = (value: number) =&gt; `$${value.toFixed(2)}`;<br><br>function App() {<br>  const [items, setItems] = useState&lt;CartItem[]&gt;(initialCartItems);<br>  const [checkoutOpen, setCheckoutOpen] = useState(false);<br>  const [formData, setFormData] = useState&lt;CheckoutForm&gt;(initialCheckoutForm);<br>  const [checkoutStatus, setCheckoutStatus] = useState&lt;{<br>    status: &#39;idle&#39; | &#39;loading&#39; | &#39;success&#39; | &#39;error&#39;;<br>    message: string | null;<br>  }&gt;({ status: &#39;idle&#39;, message: null });<br><br>  const updateQuantity = (id: string, delta: number) =&gt; {<br>    setItems((currentItems) =&gt;<br>      currentItems.map((item) =&gt;<br>        item.id === id<br>          ? { ...item, quantity: Math.max(1, item.quantity + delta) }<br>          : item,<br>      ),<br>    );<br>  };<br><br>  const removeItem = (id: string) =&gt; {<br>    setItems((currentItems) =&gt; currentItems.filter((item) =&gt; item.id !== id));<br>  };<br><br>  const handleInputChange = (field: keyof CheckoutForm, value: string) =&gt; {<br>    setFormData((current) =&gt; ({ ...current, [field]: value }));<br>  };<br><br>  const openCheckout = () =&gt; {<br>    setCheckoutStatus({ status: &#39;idle&#39;, message: null });<br>    setCheckoutOpen(true);<br>  };<br><br>  const closeCheckout = () =&gt; {<br>    setCheckoutOpen(false);<br>  };<br><br>  const handleCheckoutSubmit = async (event) =&gt; {<br>    event.preventDefault();<br><br>    if (items.length === 0) {<br>      setCheckoutStatus({ status: &#39;error&#39;, message: &#39;Your cart is empty.&#39; });<br>      return;<br>    }<br><br>    if (items.some((item) =&gt; !item.priceId)) {<br>      setCheckoutStatus({<br>        status: &#39;error&#39;,<br>        message: &#39;One or more products are missing a price ID.&#39;,<br>      });<br>      return;<br>    }<br><br>    setCheckoutStatus({<br>      status: &#39;loading&#39;,<br>      message: &#39;Creating checkout session...&#39;,<br>    });<br><br>    const payload = {<br>      firstName: formData.firstName,<br>      lastName: formData.lastName,<br>      email: formData.email,<br>      address: formData.address,<br>      line_items: items.map((item) =&gt; ({<br>        price: item.priceId!,<br>        quantity: item.quantity,<br>      })),<br>    };<br><br>    const { data, error } = await supabase.functions.invoke&lt;{ url?: string }&gt;(<br>      &#39;create-checkout-session&#39;,<br>      {<br>        body: payload,<br>      },<br>    );<br><br>    if (error) {<br>      setCheckoutStatus({ status: &#39;error&#39;, message: error.message });<br>      return;<br>    }<br><br>    setCheckoutStatus({<br>      status: &#39;success&#39;,<br>      message: data?.url<br>        ? &#39;Checkout session created. Redirecting...&#39;<br>        : &#39;Checkout session created.&#39;,<br>    });<br><br>    if (data?.url) {<br>      window.location.href = data.url;<br>    }<br>  };<br><br>  const subtotal = items.reduce(<br>    (sum, item) =&gt; sum + item.price * item.quantity,<br>    0,<br>  );<br>  <br>  const total = subtotal;<br><br>  return (<br>    &lt;div className=&quot;cart-page&quot;&gt;<br>      &lt;header className=&quot;cart-header&quot;&gt;<br>        &lt;div&gt;<br>          &lt;p className=&quot;eyebrow&quot;&gt;Shopping cart&lt;/p&gt;<br>          &lt;h1&gt;Your order is ready&lt;/h1&gt;<br>          &lt;p className=&quot;intro&quot;&gt;<br>            Review your items and complete checkout with confidence.<br>          &lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;cart-status&quot;&gt;<br>          &lt;span&gt;{items.length} items&lt;/span&gt;<br>          &lt;span&gt;Free shipping over $150&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;main className=&quot;cart-grid&quot;&gt;<br>        &lt;section className=&quot;cart-items&quot;&gt;<br>          &lt;div className=&quot;section-heading&quot;&gt;<br>            &lt;h2&gt;Cart items&lt;/h2&gt;<br>            &lt;p&gt;Tap through each product for details and pricing.&lt;/p&gt;<br>          &lt;/div&gt;<br><br>          &lt;ul&gt;<br>            {items.map((item) =&gt; (<br>              &lt;li key={item.id} className=&quot;cart-item&quot;&gt;<br>                &lt;img src={item.image} alt={item.name} /&gt;<br>                &lt;div className=&quot;item-body&quot;&gt;<br>                  &lt;div className=&quot;item-meta&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;p className=&quot;item-name&quot;&gt;{item.name}&lt;/p&gt;<br>                      &lt;p className=&quot;item-variant&quot;&gt;<br>                        {item.color} · {item.size}<br>                      &lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;p className=&quot;item-price&quot;&gt;{formatPrice(item.price)}&lt;/p&gt;<br>                  &lt;/div&gt;<br>                  &lt;div className=&quot;item-footer&quot;&gt;<br>                    &lt;div className=&quot;quantity-controls&quot;&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;quantity-button&quot;<br>                        onClick={() =&gt; updateQuantity(item.id, -1)}<br>                        disabled={item.quantity &lt;= 1}<br>                      &gt;<br>                        −<br>                      &lt;/button&gt;<br>                      &lt;span&gt;{item.quantity}&lt;/span&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;quantity-button&quot;<br>                        onClick={() =&gt; updateQuantity(item.id, 1)}<br>                      &gt;<br>                        +<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;item-actions&quot;&gt;<br>                      &lt;p className=&quot;item-total&quot;&gt;<br>                        {formatPrice(item.price * item.quantity)}<br>                      &lt;/p&gt;<br>                      &lt;button<br>                        type=&quot;button&quot;<br>                        className=&quot;button-link&quot;<br>                        onClick={() =&gt; removeItem(item.id)}<br>                      &gt;<br>                        Remove<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        &lt;/section&gt;<br><br>        &lt;aside className=&quot;cart-summary&quot;&gt;<br>          &lt;div className=&quot;summary-card&quot;&gt;<br>            &lt;p className=&quot;summary-title&quot;&gt;Order summary&lt;/p&gt;<br>            &lt;div className=&quot;summary-row&quot;&gt;<br>              &lt;span&gt;Subtotal&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(subtotal)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;summary-row&quot;&gt;<br>              &lt;span&gt;Shipping&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(shipping)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;summary-row&quot;&gt;<br>              &lt;span&gt;Taxes&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(tax)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;summary-total&quot;&gt;<br>              &lt;span&gt;Total&lt;/span&gt;<br>              &lt;span&gt;{formatPrice(total)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;button<br>              type=&quot;button&quot;<br>              className=&quot;checkout-button&quot;<br>              onClick={openCheckout}<br>            &gt;<br>              Checkout now<br>            &lt;/button&gt;<br>            &lt;p className=&quot;summary-note&quot;&gt;<br>              Secure payment, fast delivery, and easy returns.<br>            &lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/aside&gt;<br>      &lt;/main&gt;<br><br>      {checkoutOpen &amp;&amp; (<br>        &lt;div className=&quot;cart-modal-backdrop&quot; onClick={closeCheckout}&gt;<br>          &lt;div<br>            className=&quot;cart-modal&quot;<br>            onClick={(event) =&gt; event.stopPropagation()}<br>            style={{ padding: &#39;2.5rem&#39; }}<br>          &gt;<br>            &lt;div className=&quot;modal-header&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h2&gt;Complete checkout&lt;/h2&gt;<br>                &lt;p&gt;Enter shipping details to create your checkout session.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;button<br>                type=&quot;button&quot;<br>                className=&quot;modal-close-button&quot;<br>                onClick={closeCheckout}<br>                aria-label=&quot;Close checkout modal&quot;<br>              &gt;<br>                ×<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br><br>            &lt;form className=&quot;modal-form&quot; onSubmit={handleCheckoutSubmit}&gt;<br>              &lt;div className=&quot;modal-field&quot;&gt;<br>                &lt;label<br>                  htmlFor=&quot;firstName&quot;<br>                  style={{ display: &#39;block&#39;, textAlign: &#39;left&#39; }}<br>                &gt;<br>                  First name<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;firstName&quot;<br>                  value={formData.firstName}<br>                  onChange={(event) =&gt;<br>                    handleInputChange(&#39;firstName&#39;, event.target.value)<br>                  }<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;modal-field&quot;&gt;<br>                &lt;label<br>                  htmlFor=&quot;lastName&quot;<br>                  style={{ display: &#39;block&#39;, textAlign: &#39;left&#39; }}<br>                &gt;<br>                  Last name<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;lastName&quot;<br>                  value={formData.lastName}<br>                  onChange={(event) =&gt;<br>                    handleInputChange(&#39;lastName&#39;, event.target.value)<br>                  }<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;modal-field&quot;&gt;<br>                &lt;label<br>                  htmlFor=&quot;email&quot;<br>                  style={{ display: &#39;block&#39;, textAlign: &#39;left&#39; }}<br>                &gt;<br>                  Email<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;email&quot;<br>                  type=&quot;email&quot;<br>                  value={formData.email}<br>                  onChange={(event) =&gt;<br>                    handleInputChange(&#39;email&#39;, event.target.value)<br>                  }<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;modal-field&quot;&gt;<br>                &lt;label<br>                  htmlFor=&quot;address&quot;<br>                  style={{ display: &#39;block&#39;, textAlign: &#39;left&#39; }}<br>                &gt;<br>                  Shipping address<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;address&quot;<br>                  value={formData.address}<br>                  onChange={(event) =&gt;<br>                    handleInputChange(&#39;address&#39;, event.target.value)<br>                  }<br>                  required<br>                /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;modal-footer&quot;&gt;<br>                &lt;button<br>                  type=&quot;button&quot;<br>                  className=&quot;button-link&quot;<br>                  onClick={closeCheckout}<br>                &gt;<br>                  Cancel<br>                &lt;/button&gt;<br>                &lt;button<br>                  type=&quot;submit&quot;<br>                  className=&quot;checkout-button&quot;<br>                  disabled={checkoutStatus.status === &#39;loading&#39;}<br>                &gt;<br>                  {checkoutStatus.status === &#39;loading&#39;<br>                    ? &#39;Processing…&#39;<br>                    : &#39;Confirm payment&#39;}<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br><br>              {checkoutStatus.message &amp;&amp; (<br>                &lt;p className={`modal-status ${checkoutStatus.status}`}&gt;<br>                  {checkoutStatus.message}<br>                &lt;/p&gt;<br>              )}<br>            &lt;/form&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>15. <strong>Test The Entire Flow</strong></p><p><strong>STEP 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7muU4ivO76byqdXhp9VNw.png" /></figure><p><strong>STEP 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KfFTv-cN2J0MQvjrwBVVw.png" /></figure><p><strong>STEP 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SCwUS3gtuT0iJfz3Qohng.png" /></figure><p><strong>Conclusion</strong></p><p>And that’s it, a fully functional one-time payment flow powered by Stripe and Supabase Edge Functions, with no dedicated backend server in sight. You’ve seen how Edge Functions can handle the heavy lifting of payment processing right at the edge, keeping your architecture lean and your deployments simple. In <strong>Part 2</strong>, we’ll take this further by setting up recurring subscriptions and handling Stripe webhooks to keep your database in sync with payment events.</p><p><strong>Github Repositories</strong></p><p><strong>Frontend</strong>:- <a href="https://github.com/Cedar1000/stripe-supabase-frontend">https://github.com/Cedar1000/stripe-supabase-frontend</a></p><p><strong>Backend:- </strong><a href="https://github.com/Cedar1000/stripe-supabase-edge-function">https://github.com/Cedar1000/stripe-supabase-edge-function</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e266b27cbe0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-integrate-stripe-payment-with-supabase-edge-functions-part-1-one-time-payments-7e266b27cbe0">How To Integrate Stripe Payment With Supabase Edge Functions Part 1: One-Time Payments</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up NGINX as A Reverse Proxy for your Nest JS Microservices]]></title>
            <link>https://javascript.plainenglish.io/setting-up-nginx-as-a-reverse-proxy-for-your-nest-js-microservices-ea3aa53a0eba?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea3aa53a0eba</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 16:41:51 GMT</pubDate>
            <atom:updated>2025-10-17T00:59:39.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDPbjAMxa2n5YkZ6U7RI8g.jpeg" /></figure><p>When building applications with NestJS, it’s common to break features into microservices for better scalability, maintainability, and fault isolation. While this approach brings flexibility, it also introduces complexity in how clients communicate with multiple services. That’s where NGINX comes in.</p><p><strong>What is NGINX?</strong></p><p>NGINX is a high-performance web server and reverse proxy widely used to handle routing, load balancing, SSL termination, and request buffering. By placing NGINX in front of your NestJS microservices, you create a single entry point that can manage traffic efficiently, hide internal service structure from the outside world, and improve overall security and performance.</p><p>In this article, we’ll walk through the process of setting up NGINX as a reverse proxy for your NestJS microservices. We’ll cover why this setup is useful, how to configure NGINX to route traffic to different services, and best practices for production-ready deployments. Whether you’re running on Docker, Kubernetes, or a bare-metal server, the same principles apply.</p><ol><li><strong>Spin Up New Nest JS Application</strong></li></ol><p>We’ll do this by leveraging the Nest JS CLI</p><pre>nest new nestjs-nginx</pre><p><strong>2. Convert App to Monorepo</strong></p><p>We’ll do this by generating a new app within our current app</p><pre>nest generate app app-b</pre><p>Now, let’s rename the original app to app-a for clarity.</p><ol><li>Rename the folder apps/my-monorepo to apps/app-a.</li><li>Open the nest-cli.json file in the root directory. You will see an entry for &quot;my-monorepo&quot;. Change its name to &quot;app-a&quot;.</li></ol><p>Your nest-cli.json should now look something like this:</p><pre>{<br>  &quot;$schema&quot;: &quot;https://json.schemastore.org/nest-cli&quot;,<br>  &quot;collection&quot;: &quot;@nestjs/schematics&quot;,<br>  &quot;sourceRoot&quot;: &quot;apps/app-a/src&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;deleteOutDir&quot;: true,<br>    &quot;webpack&quot;: true,<br>    &quot;tsConfigPath&quot;: &quot;apps/app-a/tsconfig.app.json&quot;<br>  },<br>  &quot;monorepo&quot;: true,<br>  &quot;root&quot;: &quot;apps/app-a&quot;,<br>  &quot;projects&quot;: {<br>    &quot;app-a&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/app-a&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/app-a/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/app-a/tsconfig.app.json&quot;<br>      }<br>    },<br>    &quot;app-b&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/app-b&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/app-b/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/app-b/tsconfig.app.json&quot;<br>      }<br>    }<br>  }<br>}</pre><p>We’ll update the code in the <strong>app.service.ts</strong> of service <strong>A </strong>and <strong>B</strong> respectively to</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class AppService {<br>  getHello(): string {<br>    return &#39;Hello from service A!&#39;;<br>  }<br>}</pre><p>and</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class AppService {<br>  getHello(): string {<br>    return &#39;Hello from service B!&#39;;<br>  }<br>}</pre><p><strong>3. Dockerize Both Applications</strong></p><h3>Step 1: Create a .dockerignore File</h3><p>First, we’ll create a .dockerignore file in the root directory of our nestjs-nginx project. This prevents unnecessary files from being copied into our Docker images, which speeds up the build process.</p><pre># Dependency directories<br>node_modules/<br><br># Build artifacts<br>dist/<br><br># Git<br>.git<br>.gitignore<br><br># Docker<br>Dockerfile<br>docker-compose.yml<br><br># IDE/Editor specific<br>.idea<br>.vscode<br><br># Log files<br>*.log</pre><h3>Step 2: Create a Dockerfile for app-a</h3><p>Next, we’ll create a Dockerfile inside the apps/app-a/ directory.</p><p>apps/app-a/Dockerfile</p><pre># ---- Build Stage ----<br>FROM node:20-alpine AS builder<br><br>WORKDIR /usr/src/app<br><br># Copy root dependencies and config<br>COPY package*.json tsconfig*.json nest-cli.json ./<br><br># Copy specific app and shared libs<br>COPY apps/app-a ./apps/app-a<br>COPY libs ./libs<br><br># Install dependencies and build the app<br>RUN npm install<br>RUN npm run build app-a<br><br># ---- Production Stage ----<br>FROM node:20-alpine AS production<br><br>WORKDIR /usr/src/app<br><br># Copy only necessary files from builder<br>COPY --from=builder /usr/src/app/node_modules ./node_modules<br>COPY --from=builder /usr/src/app/dist/apps/app-a ./dist<br><br>EXPOSE 3000<br><br>CMD [&quot;node&quot;, &quot;dist/main.js&quot;]</pre><h3>Step 3: Create a Dockerfile for app-b</h3><p>Now, create a nearly identical Dockerfile inside the apps/app-b/ directory. The only changes are the lines for building app-b and copying its specific dist folder.</p><p>apps/app-b/Dockerfile</p><pre># ---- Build Stage ----<br>FROM node:20-alpine AS builder<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json tsconfig*.json nest-cli.json ./<br>COPY apps/app-b ./apps/app-b<br>COPY libs ./libs<br><br>RUN npm install<br>RUN npm run build app-b<br><br># ---- Production Stage ----<br>FROM node:20-alpine AS production<br><br>WORKDIR /usr/src/app<br><br>COPY --from=builder /usr/src/app/node_modules ./node_modules<br>COPY --from=builder /usr/src/app/dist/apps/app-b ./dist<br><br>EXPOSE 3001<br><br>CMD [&quot;node&quot;, &quot;dist/main.js&quot;]</pre><h3>Step 4: Create the docker-compose.yml File</h3><p>In the root of your nestjs-nginx project, create a docker-compose.yml file. This file will define and orchestrate your services.</p><p>docker-compose.yml</p><pre>services:<br>  app-a:<br>    build:<br>      context: .<br>      dockerfile: apps/app-a/Dockerfile<br>    ports:<br>      - &#39;3000:3000&#39;<br>    restart: always<br><br>  app-b:<br>    build:<br>      context: .<br>      dockerfile: apps/app-b/Dockerfile<br>    ports:<br>      - &#39;3001:3001&#39;<br>    restart: always</pre><h3>Step 5: Build and Run the Containers 🚀</h3><p>You’re all set! Open your terminal at the root of the project and run the following command:</p><pre>docker compose up --build -d</pre><p>We should be able to reach both apps at <strong>localhost:3000</strong> and <strong>localhost:3001 </strong>respectively as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*rfOsxx5jZW_64ueUOcif2g.png" /><figcaption>Service A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*dZ3cGTOIwp9zwImeKAONNw.png" /><figcaption>Service B</figcaption></figure><h3>Step 6: Set Up Nginx!</h3><p>In the root of our <strong>nestjs-nginx</strong> project, we create an <strong>nginx </strong>folder and inside we create a <strong>nginx.conf </strong>file and we set it up like so.</p><pre>events {}<br><br>http {<br>  # Define an &quot;upstream&quot; for each of your services.<br>  # Docker Compose lets you use the service name (&#39;app-a&#39;, &#39;app-b&#39;) as a hostname.<br>  upstream app_a_server {<br>    server app-a:3000;<br>  }<br><br>  upstream app_b_server {<br>    server app-b:3001;<br>  }<br><br>  server {<br>    listen 80;<br><br>    # Route requests starting with /api/a to app-a<br>    location /app-a/ {<br>      # The rewrite rule strips the /api/a prefix before forwarding<br>      # e.g., /api/a/users becomes /users<br>      rewrite /app-a/(.*) /$1 break;<br>      proxy_pass http://app_a_server;<br>      proxy_set_header Host $host;<br>      proxy_set_header X-Real-IP $remote_addr;<br>      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    }<br><br>    # Route requests starting with /api/b to app-b<br>    location /app-b/ {<br>      rewrite /app-b/(.*) /$1 break;<br>      proxy_pass http://app_b_server;<br>      proxy_set_header Host $host;<br>      proxy_set_header X-Real-IP $remote_addr;<br>      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    }<br>  }<br>}</pre><p>Then we update the <strong>docker-compose.yaml</strong> to spin up an nginx container and reference this file like so</p><pre>services:<br>  app-a:<br>    build:<br>      context: .<br>      dockerfile: apps/app-a/Dockerfile<br>    ports:<br>      - &#39;3000:3000&#39;<br>    restart: always<br><br>  app-b:<br>    build:<br>      context: .<br>      dockerfile: apps/app-b/Dockerfile<br>    ports:<br>      - &#39;3001:3001&#39;<br>    restart: always<br><br>  nginx:<br>    image: nginx:latest<br>    container_name: nginx<br>    volumes:<br>      - ./nginx/nginx.conf:/etc/nginx/nginx.conf<br>    ports:<br>      - &#39;80:80&#39;<br>    depends_on:<br>      - app-a<br>      - app-b</pre><h3>Step 7: Rebuild Images</h3><p>Now we rebuild the images and start up the containers like so</p><pre>docker compose down -v<br><br>docker compose up --build</pre><h3>Step 8: Test Nginx Integration</h3><p>We can proceed to reach the apps through <strong>Nginx </strong>again through <a href="http://localhost/app-a/"><strong>http://localhost/app-a</strong></a><strong> </strong>and <a href="http://localhost/app-b/"><strong>http://localhost/app-b</strong></a><strong> </strong>respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*gTLxEyRHRqfjfrvYXsH5MA.png" /><figcaption>Service A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*tD5ptE_OPWvuaDRAS6dvjw.png" /><figcaption>Service B</figcaption></figure><p><strong>Conclusion</strong></p><blockquote><em>In this article, we walked through how to use NGINX as a reverse proxy to route traffic between multiple NestJS services. You’ve learned how to structure your Docker containers, configure the </em><em>nginx.conf, and test that each service is reachable through clean, unified endpoints. With this setup in place, you can now add more services or introduce HTTPS with minimal changes, making your microservice architecture production-ready.</em></blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea3aa53a0eba" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/setting-up-nginx-as-a-reverse-proxy-for-your-nest-js-microservices-ea3aa53a0eba">Setting Up NGINX as A Reverse Proxy for your Nest JS Microservices</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Simple Blog App With NestJS Microservices, RabbitMQ, and Docker]]></title>
            <link>https://medium.com/@cedard686/building-a-simple-blog-app-with-nestjs-microservices-rabbitmq-and-docker-70e41abba03f?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e41abba03f</guid>
            <category><![CDATA[mircoservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 23:08:48 GMT</pubDate>
            <atom:updated>2025-10-04T06:55:58.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwDopVsxxPwi5l8NrWtHqQ.jpeg" /></figure><p>As applications scale and demand grows, building them in a monolithic way often becomes difficult to maintain. That’s where microservices architecture comes into play.</p><p>In this article, we’re going to be building a blog/articles app from scratch with NestJS using the microservices architecture. We’ll break the app into different microservices, using <strong>MongoDB</strong> as a database for each service, and we’ll utilize <strong>RabbitMQ</strong> for intercommunication between the microservices. All of this will be facilitated by <strong>Docker.</strong></p><p>For our app, we’ll have 3 major services, namely:-</p><ol><li>Auth Service.</li><li>Articles Service</li><li>Comment Service</li><li>Like Service</li></ol><ul><li><strong>Spin Up NestJS Application</strong></li></ul><p>First things first, spin up our Nest JS app like so</p><pre>nest new articles-app</pre><ul><li><strong>Install packages needed</strong></li></ul><pre>npm install @nestjs/microservices amqplib amqp-connection-manager @nestjs/mongoose mongoose @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt</pre><ul><li><strong>Convert The App Into A Monorepo</strong></li></ul><p>Now, we’re going to do this by creating our first microservice app by running the command below</p><pre>nest generate app auth</pre><p>This will automatically converts the app into a mono repo. We’ll proceed to create respective apps for our remaining microservices.</p><pre>nest generate app articles</pre><pre>nest generate app comments</pre><pre>nest generate app likes</pre><ul><li><strong>Set up Our Docker Containers</strong></li></ul><p>In the root of our project, we’ll create a <em>docker-compose.yaml. </em>We’re going to be spinning up containers for <strong>MongoDB </strong>and <strong>RabbitMQ. </strong>The contents of the file will look like this.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  mongodb:<br>    image: mongo:6<br>    container_name: nest_mongodb<br>    restart: unless-stopped<br>    ports:<br>      - 27017:27017<br>    volumes:<br>      - mongo_data:/data/db<br>    environment:<br>      MONGO_INITDB_DATABASE: auth_db<br><br>  rabbitmq:<br>    image: rabbitmq:3-management<br>    container_name: nest_rabbitmq<br>    restart: unless-stopped<br>    ports:<br>      - 5672:5672 # AMQP port<br>      - 15672:15672 # Management UI<br>    environment:<br>      RABBITMQ_DEFAULT_USER: guest<br>      RABBITMQ_DEFAULT_PASS: guest<br><br>volumes:<br>  mongo_data:</pre><p>Then we proceed to start the containers by running the following command in the root of the project. The <strong>-d</strong> flag is to run it in detached mode</p><pre>docker-compose up -d</pre><p>Verify the containers are running by running:</p><pre>docker ps</pre><p>You should see something that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anG2H72QXL3EZI7jS1dssg.png" /></figure><p>You can access the RabbitMQ management UI at <a href="http://localhost:15672/"><strong>http://localhost:15672</strong></a> with the credentials user/password specified in the docker-compose file.</p><p>In the root of our project, we’ll modify our nest-cli.json file to this</p><pre>{<br>  &quot;$schema&quot;: &quot;https://json.schemastore.org/nest-cli&quot;,<br>  &quot;collection&quot;: &quot;@nestjs/schematics&quot;,<br>  &quot;sourceRoot&quot;: &quot;apps/articles/src&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;deleteOutDir&quot;: true,<br>    &quot;webpack&quot;: true,<br>    &quot;tsConfigPath&quot;: &quot;apps/articles/tsconfig.app.json&quot;<br>  },<br>  &quot;monorepo&quot;: true,<br>  &quot;root&quot;: &quot;apps/articles&quot;,<br>  &quot;projects&quot;: {<br>    &quot;articles&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/articles&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/articles/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/articles/tsconfig.app.json&quot;<br>      }<br>    },<br>    &quot;auth&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/auth&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/auth/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/auth/tsconfig.app.json&quot;<br>      }<br>    },<br>    &quot;comments&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/comments&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/comments/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/comments/tsconfig.app.json&quot;<br>      }<br>    },<br>    &quot;common&quot;: {<br>      &quot;type&quot;: &quot;library&quot;,<br>      &quot;root&quot;: &quot;libs/common&quot;,<br>      &quot;entryFile&quot;: &quot;index&quot;,<br>      &quot;sourceRoot&quot;: &quot;libs/common/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;libs/common/tsconfig.lib.json&quot;<br>      }<br>    },<br>    &quot;likes&quot;: {<br>      &quot;type&quot;: &quot;application&quot;,<br>      &quot;root&quot;: &quot;apps/likes&quot;,<br>      &quot;entryFile&quot;: &quot;main&quot;,<br>      &quot;sourceRoot&quot;: &quot;apps/likes/src&quot;,<br>      &quot;compilerOptions&quot;: {<br>        &quot;tsConfigPath&quot;: &quot;apps/likes/tsconfig.app.json&quot;<br>      }<br>    }<br>  }<br>}</pre><p>In this file, we’ll specify each of our service apps and their entry points.</p><ul><li><strong>Setting Up the Databases</strong></li></ul><p>Once your MongoDB container is running, you need to create the individual databases for your microservices. The easiest way to do this is by accessing the MongoDB shell directly inside the container.</p><p><strong>1. Access the MongoDB Shell</strong></p><p>Open your terminal and run the following command to get an interactive shell inside your running MongoDB container. <strong>Note: Replace mongodb with your container’s name if it’s different.</strong></p><pre>docker exec -it mongodb mongosh</pre><p><strong>2. Create the Databases</strong></p><p>IIn MongoDB, a database isn’t physically created until you insert data into it. We’ll use the use command to switch to our new databases and add a single dummy document to create them.</p><p>Create <strong>users</strong> for the <strong>auth</strong> service</p><pre>use users<br>db.users.insertOne({ &quot;init&quot;: true })</pre><p>Create <strong>articles</strong> for the <strong>articles</strong> service</p><pre>use articles<br>db.users.insertOne({ &quot;init&quot;: true })</pre><p>Create <strong>comments</strong> for the <strong>comments</strong> service</p><pre>use comments<br>db.users.insertOne({ &quot;init&quot;: true })</pre><ul><li>Create <strong>likes</strong> for the <strong>likes</strong> service</li></ul><pre>use likes<br>db.users.insertOne({ &quot;init&quot;: true })</pre><p>After this, we can set up an <strong>.env</strong> that looks like this</p><pre>JWT_SECRET=supersecret<br>AUTH_DB=mongodb://localhost:27017/users<br>ARTICLES_DB=mongodb://localhost:27017/articles<br>LIKES_DB=mongodb://localhost:27017/likes<br>COMMENTS_DB=mongodb://localhost:27017/comments<br><br>RABBITMQ_URL=amqp://user:password@localhost:5672</pre><ul><li><strong>Set up Auth Service</strong></li></ul><p>We’ll run through setting up the auth service</p><p><strong>user.schema.ts</strong></p><pre>import { Prop, Schema, SchemaFactory } from &#39;@nestjs/mongoose&#39;;<br>import { Document } from &#39;mongoose&#39;;<br><br>export type UserDocument = User &amp; Document;<br><br>@Schema()<br>export class User {<br>  @Prop({ required: true })<br>  firstName: string;<br><br>  @Prop({ required: true })<br>  lastName: string;<br><br>  @Prop({ required: true })<br>  email: string;<br><br>  @Prop({ required: true, default: 0 })<br>  articleCount: number;<br><br>  @Prop({ required: true })<br>  password: string;<br>}<br><br>export const UserSchema = SchemaFactory.createForClass(User);</pre><p><strong>login.dto.ts</strong></p><pre>import { IsEmail, IsString } from &#39;class-validator&#39;;<br><br>export class LoginDto {<br>  @IsEmail()<br>  email: string;<br><br>  @IsString()<br>  password: string;<br>}</pre><p><strong>signup.dto.ts</strong></p><pre>import { IsEmail, IsNotEmpty, IsString, MinLength } from &#39;class-validator&#39;;<br><br>export class SignupDto {<br>  @IsNotEmpty()<br>  @IsString()<br>  firstName: string;<br><br>  @IsNotEmpty()<br>  @IsString()<br>  lastName: string;<br><br>  @IsNotEmpty()<br>  @IsEmail()<br>  email: string;<br><br>  @IsNotEmpty()<br>  @IsString()<br>  @MinLength(6)<br>  password: string;<br>}</pre><p><strong>auth.service.ts</strong></p><pre>import {<br>  Injectable,<br>  UnauthorizedException,<br>  ConflictException,<br>} from &#39;@nestjs/common&#39;;<br><br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { User, UserDocument } from &#39;./schemas/user.schema&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br>import { SignupDto } from &#39;./dtos/signup.dto&#39;;<br>import { LoginDto } from &#39;./dtos/login.dto&#39;;<br><br>@Injectable()<br>export class AuthService {<br>  constructor(<br>    @InjectModel(User.name) private userModel: Model&lt;UserDocument&gt;,<br>    private jwtService: JwtService,<br>  ) {}<br><br>  async signup(dto: SignupDto) {<br>    const existingUser = await this.userModel.findOne({ email: dto.email });<br><br>    if (existingUser) throw new ConflictException(&#39;Email already in use&#39;);<br><br>    const hash = await bcrypt.hash(dto.password, 10);<br><br>    dto.password = hash;<br><br>    const data = new this.userModel(dto);<br><br>    const user = await data.save();<br><br>    const { access_token } = this.signToken(user.id, user.email);<br><br>    return { status: &#39;success&#39;, access_token, user };<br>  }<br><br>  async login(dto: LoginDto) {<br>    const user = await this.userModel.findOne({ email: dto.email });<br><br>    if (!user) throw new UnauthorizedException(&#39;Invalid credentials&#39;);<br><br>    const isMatch = await bcrypt.compare(dto.password, user.password);<br><br>    if (!isMatch) throw new UnauthorizedException(&#39;Invalid credentials&#39;);<br><br>    const { access_token } = this.signToken(user.id, user.email);<br><br>    return { status: &#39;success&#39;, access_token, user };<br>  }<br><br>  async updateUserArticles(payload: { count: number; userId: string }) {<br>    const { userId, count } = payload;<br><br>    await this.userModel.findById(userId);<br><br>    const user = await this.userModel.findByIdAndUpdate(userId, {<br>      articleCount: count,<br>    });<br>  }<br><br>  async getUsersByIds(ids: string[]) {<br>    const promises = ids.map((id) =&gt; this.userModel.findById(id));<br><br>    return await Promise.all(promises);<br>  }<br><br>  private signToken(id: string, email: string) {<br>    const payload = { id, email };<br>    return {<br>      access_token: this.jwtService.sign(payload),<br>    };<br>  }<br>}</pre><p>In addition to the <strong>login </strong>and <strong>signup </strong>handlers, notice we added 2 additional handlers, namely <strong>updateUserArticle </strong>and <strong>getUsersByIds</strong> that will be called by the other microservices through <strong>RabbitMQ. </strong>We’ll see this as we progress.</p><p><strong>auth.controller.ts</strong></p><pre>import {<br>  Body,<br>  Post,<br>  UsePipes,<br>  HttpCode,<br>  Controller,<br>  ValidationPipe,<br>} from &#39;@nestjs/common&#39;;<br><br>import { MessagePattern, Payload } from &#39;@nestjs/microservices&#39;;<br><br>import { AuthService } from &#39;./auth.service&#39;;<br><br>import { LoginDto } from &#39;./dtos/login.dto&#39;;<br>import { SignupDto } from &#39;./dtos/signup.dto&#39;;<br><br>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {}<br><br>  @Post(&#39;signup&#39;)<br>  @UsePipes(ValidationPipe)<br>  signup(@Body() dto: SignupDto) {<br>    return this.authService.signup(dto);<br>  }<br><br>  @Post(&#39;login&#39;)<br>  @HttpCode(200)<br>  @UsePipes(ValidationPipe)<br>  login(@Body() dto: LoginDto) {<br>    return this.authService.login(dto);<br>  }<br><br>  @MessagePattern(&#39;article_created&#39;)<br>  handleArticleCreated(@Payload() data: any) {<br>    console.log(<br>      `[Auth-Service] Event &#39;article_created&#39; received for user: ${data}`,<br>    );<br><br>    this.authService.updateUserArticles(data);<br>  }<br><br>  @MessagePattern({ cmd: &#39;get_users_by_ids&#39; })<br>  getUsersById(@Payload() data: any) {<br>    console.log(<br>      `[Auth-Service] Event &#39;get_users_by_ids&#39; received for user: ${data}`,<br>    );<br><br>    return this.authService.getUsersByIds(data);<br>  }<br>}</pre><p><strong>Handling Both Web Traffic and Internal Events</strong></p><p>A key feature of this architecture is how a single service can handle two different kinds of communication. If you look at the AuthController, you’ll see a great example of a “hybrid” controller.</p><p><strong>HTTP Route Handlers (@Post)</strong></p><p>Methods like signup and login are decorated with @Post. These are standard API endpoints that listen for POST requests from the outside world (like a user’s browser or Postman).</p><p><strong>Message Event Handlers (@MessagePattern)</strong></p><p>Methods like <strong>handleArticleCreated</strong> and <strong>getUsersById</strong> are different. They are decorated with <strong>@MessagePattern</strong> and listen for messages on the <strong>RabbitMQ</strong> queue. They are not accessible via a URL. For example, when the articles-service emits an ‘article_created’ event, the handleArticleCreated method is triggered automatically to update the user’s data.</p><p>This hybrid approach allows you to keep related logic together in one place, whether it’s triggered by a direct user action or a background event from another microservice.</p><p><strong>How it Works</strong></p><p>The microservice sets up a RabbitMQ microservice transport. It listens on a specific queue (some_queue). The AppController in the microservice has a method decorated with @MessagePattern(‘some_event’). This means it will handle any message sent to the <strong>some_queue</strong> with the pattern ‘some_event’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*WFCSbuQabr3Tiidq_etg5A.jpeg" /></figure><p>In this example, when an article is created, we count the number of articles created by the currently logged-in user and dispatch an event to the auth service with this calculated</p><p>We proceed to set up <strong>jwt.strategy.ts</strong> like so</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PassportStrategy } from &#39;@nestjs/passport&#39;;<br>import { ExtractJwt, Strategy } from &#39;passport-jwt&#39;;<br><br>@Injectable()<br>export class JwtStrategy extends PassportStrategy(Strategy) {<br>  constructor() {<br>    super({<br>      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),<br>      secretOrKey: &#39;supersecret&#39;, // Use env var in real app<br>    });<br>  }<br><br>  validate(payload: any) {<br>    return payload; // payload contains: sub (userId), email<br>  }<br>}</pre><p><strong>auth.module.ts</strong></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { JwtModule } from &#39;@nestjs/jwt&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br><br>import { AuthService } from &#39;./auth.service&#39;;<br>import { AuthController } from &#39;./auth.controller&#39;;<br>import { User, UserSchema } from &#39;./schemas/user.schema&#39;;<br>import { JwtStrategy } from &#39;./jwt.strategy&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br><br>    MongooseModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: async (config: ConfigService) =&gt; ({<br>        uri: config.get&lt;string&gt;(&#39;AUTH_DB&#39;),<br>      }),<br>    }),<br><br>    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),<br><br>    JwtModule.registerAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: async (config: ConfigService) =&gt; ({<br>        secret: config.get&lt;string&gt;(&#39;JWT_SECRET&#39;),<br>        signOptions: { expiresIn: &#39;24h&#39; },<br>      }),<br>    }),<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, JwtStrategy],<br>})<br>export class AuthModule {}</pre><p><strong>main.ts</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AuthModule } from &#39;./auth.module&#39;;<br>import { MicroserviceOptions, Transport } from &#39;@nestjs/microservices&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AuthModule);<br><br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.RMQ,<br>    options: {<br>      urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>      queue: &#39;users_queue&#39;, // The queue this service will listen to<br>      queueOptions: { durable: false },<br>    },<br>  });<br><br>  await app.startAllMicroservices();<br><br>  await app.listen(3001);<br>}<br>bootstrap();</pre><p>This is the entry point to the service. Here, we configure the app as a hybrid app, i.e, we configure the application to handle both HTTP requests and microservice messages simultaneously.</p><ul><li><strong>Generate A Shared Library</strong></li></ul><p>We’ll create a dedicated library in our monorepo to hold all our common code, you know, stuff we reuse across our different services, e.g, <strong>decorators, guards, interceptors, etc. </strong>We’ll run through these really quickly.</p><pre>nest g library common</pre><p>This command will create a new libs/common directory for our shared code. We’ll proceed to create this common code now in the libs/common/src folder.</p><p><strong>decorators/public.decorator.ts</strong></p><pre>import { SetMetadata } from &#39;@nestjs/common&#39;;<br><br>export const IS_PUBLIC_KEY = &#39;isPublic&#39;;<br>export const Public = () =&gt; SetMetadata(IS_PUBLIC_KEY, true);</pre><p><strong>decorators/user.decorator.ts</strong></p><pre>import { createParamDecorator, ExecutionContext } from &#39;@nestjs/common&#39;;<br><br>export const CurrentUser = createParamDecorator(<br>  (data: unknown, ctx: ExecutionContext) =&gt; {<br>    const request = ctx.switchToHttp().getRequest();<br>    return request.user;<br>  },<br>);</pre><p>This is a custom parameter decorator to extract the user object from the request.</p><p>The JwtAuthGuard must be used for this decorator to work, as it’s responsible for validating the token and attaching the user to the request</p><p><strong>guards/jwt-auth.guard.ts</strong></p><pre>import {<br>  Injectable,<br>  CanActivate,<br>  ExecutionContext,<br>  UnauthorizedException,<br>} from &#39;@nestjs/common&#39;;<br>import { Reflector } from &#39;@nestjs/core&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br>import { IS_PUBLIC_KEY } from &#39;../decorators/public.decorator&#39;;<br><br>@Injectable()<br>export class JwtAuthGuard implements CanActivate {<br>  constructor(<br>    private jwtService: JwtService,<br>    private reflector: Reflector,<br>  ) {}<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    // Check if the route is marked as public<br>    const isPublic = this.reflector.getAllAndOverride&lt;boolean&gt;(IS_PUBLIC_KEY, [<br>      context.getHandler(),<br>      context.getClass(),<br>    ]);<br><br>    if (isPublic) return true;<br><br>    const request = context.switchToHttp().getRequest();<br>    const token = this.extractTokenFromHeader(request);<br><br>    if (!token) {<br>      throw new UnauthorizedException(&#39;No token provided&#39;);<br>    }<br><br>    try {<br>      // The secret should be loaded from ConfigService for security<br>      const payload = await this.jwtService.verifyAsync(token, {<br>        secret: process.env.JWT_SECRET, // Assumes JWT_SECRET is in your .env<br>      });<br><br>      // Assign the payload to the request object so we can access it in our route handlers<br>      request[&#39;user&#39;] = payload;<br>    } catch {<br>      throw new UnauthorizedException(&#39;Invalid or expired token&#39;);<br>    }<br>    return true;<br>  }<br><br>  private extractTokenFromHeader(request: any): string | undefined {<br>    const [type, token] = request.headers.authorization?.split(&#39; &#39;) ?? [];<br>    return type === &#39;Bearer&#39; ? token : undefined;<br>  }<br>}</pre><p>This is a guard to check for a token in the request headers, decode it, and then assign the decoded user to the request body.</p><p><strong>interceptors/attach-users.interceptor.ts</strong></p><pre>import {<br>  Injectable,<br>  NestInterceptor,<br>  ExecutionContext,<br>  CallHandler,<br>  Inject,<br>  Type,<br>} from &#39;@nestjs/common&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { switchMap } from &#39;rxjs/operators&#39;;<br>import { ClientProxy } from &#39;@nestjs/microservices&#39;;<br>import { firstValueFrom } from &#39;rxjs&#39;;<br>import { IUser } from &#39;../interfaces/user.interface&#39;; // Assuming IUser is in your common library<br><br>/**<br> * Defines the configuration options for the AttachAuthors interceptor.<br> */<br>export interface AttachAuthorsOptions {<br>  // The name of the field on the data object that holds the user&#39;s ID.<br>  // e.g., &#39;userId&#39;, &#39;authorId&#39;<br>  userIdField: string;<br><br>  // The name of the new field where the fetched user object will be attached.<br>  // e.g., &#39;author&#39;, &#39;user&#39;<br>  attachToField: string;<br><br>  // Optional: The path to the array of data within the response object.<br>  // e.g., &#39;data&#39; if the response is { status: &#39;success&#39;, data: [...] }<br>  dataPath?: string;<br>}<br><br>/**<br> * A factory function that creates a configurable interceptor.<br> * This interceptor fetches user data for a list of items and attaches it.<br> * @param options - The configuration for the interceptor.<br> */<br>export function AttachUsers(<br>  options: AttachAuthorsOptions,<br>): Type&lt;NestInterceptor&gt; {<br>  @Injectable()<br>  class AttachUsersInterceptor implements NestInterceptor {<br>    constructor(@Inject(&#39;USER_SERVICE&#39;) private userClient: ClientProxy) {}<br><br>    intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {<br>      return next.handle().pipe(<br>        switchMap(async (response: any) =&gt; {<br>          // 1. Determine the array of items to process based on the dataPath.<br>          const items = options.dataPath<br>            ? response[options.dataPath]<br>            : response;<br><br>          if (!Array.isArray(items) || items.length === 0) {<br>            return response; // Return original response if there&#39;s nothing to process.<br>          }<br><br>          // 2. Collect all unique, non-null user IDs from the items.<br>          const userIds = [<br>            ...new Set(<br>              items.map((item) =&gt; item[options.userIdField]).filter(Boolean),<br>            ),<br>          ];<br><br>          if (userIds.length === 0) {<br>            return response; // No user IDs to fetch.<br>          }<br><br>          // 3. Send a SINGLE batch request to the users-service.<br>          const authors: IUser[] = await firstValueFrom(<br>            this.userClient.send({ cmd: &#39;get_users_by_ids&#39; }, userIds),<br>          );<br><br>          // 4. Create a map of authors for efficient O(1) lookup.<br>          const authorMap = new Map(<br>            authors.map((author) =&gt; [author._id, author]),<br>          );<br><br>          // 5. Combine items with their corresponding authors.<br>          const enrichedItems = items.map((item) =&gt; {<br>            const itemObject = item._doc ? item._doc : item; // Handle Mongoose documents<br>            return {<br>              ...itemObject,<br>              [options.attachToField]:<br>                authorMap.get(item[options.userIdField]) || null,<br>            };<br>          });<br><br>          // 6. Reconstruct the response with the enriched data.<br>          if (options.dataPath) {<br>            response[options.dataPath] = enrichedItems;<br>            return response;<br>          } else {<br>            return enrichedItems;<br>          }<br>        }),<br>      );<br>    }<br>  }<br><br>  // Return the dynamically created interceptor class.<br>  return AttachUsersInterceptor;<br>}</pre><p>This is a reusable interceptor which fetches and attaches each user’s data to the corresponding resource, e.g, <strong>article, like, comment.</strong></p><p><strong>interfaces/user.interface.ts</strong></p><pre>export interface IUser {<br>  [x: string]: any;<br>  /**<br>   * The unique identifier for the user (string representation of _id).<br>   */<br>  id: string;<br><br>  /**<br>   * The user&#39;s first name.<br>   */<br>  firstName: string;<br><br>  /**<br>   * The user&#39;s last name.<br>   */<br>  lastName: string;<br><br>  /**<br>   * The user&#39;s email address.<br>   */<br>  email: string;<br><br>  /**<br>   * The number of articles the user has posted.<br>   */<br>  articleCount: number;<br><br>  /**<br>   * The user&#39;s hashed password. This is marked as optional as it should<br>   * never be included in objects sent back to the client.<br>   */<br>  password?: string;<br>}</pre><ul><li><strong>Set up Articles Service</strong></li></ul><p>We’ll run through setting up the articles service</p><p><strong>article.schema.ts</strong></p><pre>import { Prop, Schema, SchemaFactory } from &#39;@nestjs/mongoose&#39;;<br>import { Document } from &#39;mongoose&#39;;<br><br>export type ArticleDocument = Article &amp; Document;<br><br>@Schema()<br>export class Article {<br>  @Prop({ required: true })<br>  title: string;<br><br>  @Prop({ required: true })<br>  body: string;<br><br>  @Prop({ required: true })<br>  userId: string;<br><br>  @Prop({ required: true, default: 0 })<br>  commentCount: number;<br><br>  @Prop({ required: true, default: 0 })<br>  likeCount: number;<br>  _doc: any;<br>}<br><br>export const ArticleSchema = SchemaFactory.createForClass(Article);</pre><p><strong>article.dto.ts</strong></p><pre>import { IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class ArticleDto {<br>  @IsNotEmpty()<br>  @IsString()<br>  title: string;<br><br>  @IsNotEmpty()<br>  @IsString()<br>  body: string;<br><br>  userId: string;<br>}</pre><p><strong>articles.service.ts</strong></p><pre>import { Inject, Injectable } from &#39;@nestjs/common&#39;;<br><br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br><br>import { Model } from &#39;mongoose&#39;;<br><br>import { ArticleDto } from &#39;./dtos/article.dto&#39;;<br><br>import { Article, ArticleDocument } from &#39;./schemas/article.schema&#39;;<br><br>import { ClientProxy } from &#39;@nestjs/microservices&#39;;<br><br>import { IUser } from &#39;@app/common&#39;;<br><br>@Injectable()<br>export class ArticlesService {<br>  constructor(<br>    @InjectModel(Article.name) private articleModel: Model&lt;ArticleDocument&gt;,<br>    @Inject(&#39;USER_SERVICE&#39;) private userClient: ClientProxy,<br>  ) {}<br><br>  async findAll() {<br>    const articles = await this.articleModel.find();<br><br>    return { status: &#39;success&#39;, results: articles.length, data: articles };<br>  }<br><br>  async create(articleDto: ArticleDto, user: IUser) {<br>    articleDto.userId = user.id;<br><br>    const data = await this.articleModel.create(articleDto);<br><br>    const article = await data.save();<br><br>    this.countUserArticles(user.id);<br><br>    return { status: &#39;success&#39;, data: article };<br>  }<br><br>  async findOne(id: string) {<br>    return await this.articleModel.findById(id);<br>  }<br><br>  async updateArticleLikes(payload: { count: number; articleId: string }) {<br>    const { count, articleId } = payload;<br><br>    await this.articleModel.findByIdAndUpdate(<br>      articleId,<br>      { likeCount: count },<br>    );<br>  }<br><br>  async updateArticleComments(payload: { count: number; articleId: string }) {<br>    const { count, articleId } = payload;<br><br>    await this.articleModel.findByIdAndUpdate(<br>      articleId,<br>      { commentCount: count },<br>    );<br>  }<br><br>  private async countUserArticles(userId: string) {<br>    const count = await this.articleModel.countDocuments({ userId });<br><br>    this.userClient.emit(&#39;article_created&#39;, { count, userId });<br>  }<br>}</pre><p>Notice how we also have methods updateArticleLikes and updateArticleComments. These are also waiting for events from other microservices, as we’ll see as we progress.</p><p><strong>article.controller.ts</strong></p><pre>import {<br>  Get,<br>  Post,<br>  Body,<br>  UsePipes,<br>  Controller,<br>  ValidationPipe,<br>  UseInterceptors,<br>} from &#39;@nestjs/common&#39;;<br><br>import { MessagePattern, Payload } from &#39;@nestjs/microservices&#39;;<br><br>import { ArticlesService } from &#39;./articles.service&#39;;<br><br>import { ArticleDto } from &#39;./dtos/article.dto&#39;;<br><br>import { CurrentUser } from &#39;@app/common&#39;;<br><br>import { IUser } from &#39;@app/common&#39;;<br><br>import { AttachUsers } from &#39;@app/common/interceptors/attach-users.interceptor&#39;;<br><br>@Controller(&#39;articles&#39;)<br>export class ArticlesController {<br>  constructor(private readonly articlesService: ArticlesService) {}<br><br>  @Get()<br>  @UseInterceptors(<br>    AttachUsers({<br>      userIdField: &#39;userId&#39;,<br>      attachToField: &#39;author&#39;,<br>      dataPath: &#39;data&#39;,<br>    }),<br>  )<br>  async findAll() {<br>    return await this.articlesService.findAll();<br>  }<br><br>  @Post()<br>  @UsePipes(ValidationPipe)<br>  async create(@Body() articleDto: ArticleDto, @CurrentUser() user: IUser) {<br>    return this.articlesService.create(articleDto, user);<br>  }<br><br>  @MessagePattern(&#39;like_created&#39;)<br>  handleLikeCreated(@Payload() data: any) {<br>    console.log(<br>      `[Like-Service] Event &#39;like_created&#39; received for article: ${data}`,<br>    );<br><br>    this.articlesService.updateArticleLikes(data);<br>  }<br><br>  @MessagePattern(&#39;comment_created&#39;)<br>  handleCommentCreated(@Payload() data: any) {<br>    console.log(<br>      `[Comment-Service] Event &#39;comment_created&#39; received for article: ${data}`,<br>    );<br><br>    this.articlesService.updateArticleComments(data);<br>  }<br><br>  @MessagePattern({ cmd: &#39;validate_article&#39; })<br>  getUsersById(@Payload() data: any) {<br>    console.log(<br>      `[Like-Service] Event &#39;validate_article&#39; received for article: ${data}`,<br>    );<br><br>    return this.articlesService.findOne(data);<br>  }<br>}</pre><p><strong>article.module.ts</strong></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br><br>import { JwtModule } from &#39;@nestjs/jwt&#39;;<br>import { ArticlesController } from &#39;./articles.controller&#39;;<br>import { ArticlesService } from &#39;./articles.service&#39;;<br><br>import { APP_GUARD } from &#39;@nestjs/core&#39;;<br>import { JwtAuthGuard } from &#39;@app/common&#39;;<br><br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br><br>import { Article, ArticleSchema } from &#39;./schemas/article.schema&#39;;<br><br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br><br>    MongooseModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: async (config: ConfigService) =&gt; ({<br>        uri: config.get&lt;string&gt;(&#39;ARTICLES_DB&#39;),<br>      }),<br>    }),<br><br>    MongooseModule.forFeature([{ name: Article.name, schema: ArticleSchema }]),<br><br>    JwtModule.registerAsync({<br>      imports: [ConfigModule],<br>      // Use a factory to inject the ConfigService and get the JWT_SECRET<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        secret: configService.get&lt;string&gt;(&#39;JWT_SECRET&#39;),<br>        signOptions: { expiresIn: &#39;1h&#39; },<br>      }),<br>      inject: [ConfigService],<br>    }),<br><br>    ClientsModule.register([<br>      {<br>        name: &#39;USER_SERVICE&#39;,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>          queue: &#39;users_queue&#39;,<br>          queueOptions: { durable: false },<br>        },<br>      },<br>    ]),<br>  ],<br><br>  controllers: [ArticlesController],<br><br>  providers: [ArticlesService, { provide: APP_GUARD, useClass: JwtAuthGuard }],<br>})<br>export class ArticlesModule {}</pre><p><strong>main.ts</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { ArticlesModule } from &#39;./articles.module&#39;;<br>import { MicroserviceOptions, Transport } from &#39;@nestjs/microservices&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(ArticlesModule);<br><br>  app.connectMicroservice&lt;MicroserviceOptions&gt;({<br>    transport: Transport.RMQ,<br>    options: {<br>      urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>      queue: &#39;articles_queue&#39;, // The queue this service will listen to<br>      queueOptions: { durable: false },<br>    },<br>  });<br><br>  await app.startAllMicroservices();<br><br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p><strong>Set up Comment Service</strong></p><p><strong>comment.schema.ts</strong></p><pre>import { Prop, Schema, SchemaFactory } from &#39;@nestjs/mongoose&#39;;<br>import { Document } from &#39;mongoose&#39;;<br><br>export type CommentDocument = Comment &amp; Document;<br><br>@Schema({ timestamps: true })<br>export class Comment {<br>  @Prop({ required: true, index: true })<br>  userId: string;<br><br>  @Prop({ required: true, index: true })<br>  articleId: string;<br><br>  @Prop({ required: true })<br>  body: string;<br>}<br><br>export const CommentSchema = SchemaFactory.createForClass(Comment);</pre><p><strong>comment.dto.ts</strong></p><pre>import { IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class CommentDto {<br>  @IsNotEmpty()<br>  @IsString()<br>  articleId: string;<br><br>  @IsNotEmpty()<br>  @IsString()<br>  body: string;<br><br>  userId: string;<br>}</pre><p><strong>comment.service.ts</strong></p><pre>import { Injectable, Inject, UnauthorizedException } from &#39;@nestjs/common&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { ClientProxy } from &#39;@nestjs/microservices&#39;;<br>import { Comment, CommentDocument } from &#39;./schemas/comment.schema&#39;;<br><br>import { CommentDto } from &#39;./dtos/comment.dto&#39;;<br><br>@Injectable()<br>export class CommentsService {<br>  constructor(<br>    @InjectModel(Comment.name) private commentModel: Model&lt;CommentDocument&gt;,<br>    @Inject(&#39;ARTICLE_SERVICE&#39;) private articleClient: ClientProxy,<br>  ) {}<br><br>  async create(commentDto: CommentDto, userId: string) {<br>    const { articleId } = commentDto;<br><br>    commentDto.userId = userId;<br><br>    const comment = await new this.commentModel(commentDto).save();<br><br>    // Emit an event to notify the articles service to update its count<br>    this.articleClient.emit(&#39;comment_created&#39;, { articleId });<br><br>    this.countCommentLikes(articleId);<br><br>    return { status: &#39;success&#39;, data: comment };<br>  }<br><br>  async getAll() {<br>    const comments = await this.commentModel.find();<br><br>    return { status: &#39;success&#39;, data: comments };<br>  }<br><br>  async delete(commentId: string, userId: string) {<br>    const comment = await this.commentModel.findById(commentId);<br><br>    // Ensure only the user who created the comment can delete it<br>    if (comment?.userId !== userId) {<br>      throw new UnauthorizedException(<br>        &#39;You are not authorized to delete this comment.&#39;,<br>      );<br>    }<br><br>    await comment.deleteOne();<br><br>    // Emit an event to notify the articles service to update its count<br>    this.articleClient.emit(&#39;article_comment_count_updated&#39;, {<br>      articleId: comment.articleId,<br>    });<br><br>    return { status: &#39;success&#39;, message: &#39;Comment deleted&#39; };<br>  }<br><br>  private async countCommentLikes(articleId: string) {<br>    const count = await this.commentModel.countDocuments({ articleId });<br><br>    this.articleClient.emit(&#39;comment_created&#39;, { count, articleId });<br>  }<br>}</pre><p><strong>comments.controller.ts</strong></p><pre>import {<br>  Get,<br>  Post,<br>  Body,<br>  Param,<br>  Delete,<br>  UsePipes,<br>  UseGuards,<br>  Controller,<br>  ValidationPipe,<br>  UseInterceptors,<br>} from &#39;@nestjs/common&#39;;<br><br>import { CommentsService } from &#39;./comments.service&#39;;<br>import { JwtAuthGuard, IUser, CurrentUser } from &#39;@app/common&#39;;<br><br>import { CommentDto } from &#39;./dtos/comment.dto&#39;;<br><br>import { AttachUsers } from &#39;@app/common/interceptors/attach-users.interceptor&#39;;<br><br>@Controller(&#39;comments&#39;)<br>@UseGuards(JwtAuthGuard)<br>export class CommentsController {<br>  constructor(private readonly commentsService: CommentsService) {}<br><br>  @Get()<br>  @UseInterceptors(<br>    AttachUsers({<br>      userIdField: &#39;userId&#39;,<br>      attachToField: &#39;user&#39;,<br>      dataPath: &#39;data&#39;,<br>    }),<br>  )<br>  getAllComments() {<br>    return this.commentsService.getAll();<br>  }<br><br>  @Post()<br>  @UsePipes(ValidationPipe)<br>  createComment(@Body() commentDto: CommentDto, @CurrentUser() user: IUser) {<br>    return this.commentsService.create(commentDto, user.id);<br>  }<br><br>  @Delete(&#39;:commentId&#39;)<br>  deleteComment(<br>    @Param(&#39;commentId&#39;) commentId: string,<br>    @CurrentUser() user: IUser,<br>  ) {<br>    return this.commentsService.delete(commentId, user.id);<br>  }<br>}</pre><p><strong>comment.module.ts</strong></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { JwtModule } from &#39;@nestjs/jwt&#39;;<br><br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br>import { Comment, CommentSchema } from &#39;./schemas/comment.schema&#39;;<br>import { CommentsController } from &#39;./comments.controller&#39;;<br>import { CommentsService } from &#39;./comments.service&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br><br>    MongooseModule.forRootAsync({<br>      imports: [ConfigModule],<br>      useFactory: (configService: ConfigService) =&gt; ({<br>        uri: configService.get&lt;string&gt;(&#39;COMMENTS_DB&#39;),<br>      }),<br>      inject: [ConfigService],<br>    }),<br><br>    JwtModule.registerAsync({<br>      imports: [ConfigModule],<br>      // Use a factory to inject the ConfigService and get the JWT_SECRET<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        secret: configService.get&lt;string&gt;(&#39;JWT_SECRET&#39;),<br>        signOptions: { expiresIn: &#39;1h&#39; },<br>      }),<br>      inject: [ConfigService],<br>    }),<br><br>    MongooseModule.forFeature([{ name: Comment.name, schema: CommentSchema }]),<br>    // Register a client to emit events to the comment service<br><br>    ClientsModule.register([<br>      {<br>        name: &#39;USER_SERVICE&#39;,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>          queue: &#39;users_queue&#39;,<br>          queueOptions: { durable: false },<br>        },<br>      },<br>    ]),<br><br>    ClientsModule.register([<br>      {<br>        name: &#39;ARTICLE_SERVICE&#39;,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>          queue: &#39;comments_queue&#39;,<br>          queueOptions: {<br>            durable: false,<br>          },<br>        },<br>      },<br>    ]),<br>  ],<br>  controllers: [CommentsController],<br>  providers: [CommentsService],<br>})<br>export class CommentModule {}</pre><p><strong>main.ts</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { CommentModule } from &#39;./comments.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(CommentModule);<br>  await app.listen(3003);<br>}<br>bootstrap();</pre><p><strong>Set up Like Service</strong></p><p><strong>like.schema.ts</strong></p><pre>import { Prop, Schema, SchemaFactory } from &#39;@nestjs/mongoose&#39;;<br>import { Document } from &#39;mongoose&#39;;<br><br>export type LikeDocument = Like &amp; Document;<br><br>@Schema({ timestamps: true })<br>export class Like {<br>  @Prop({ required: true, index: true })<br>  userId: string;<br><br>  @Prop({ required: true, index: true })<br>  articleId: string;<br>}<br><br>export const LikeSchema = SchemaFactory.createForClass(Like);</pre><p><strong>like.dto.ts</strong></p><pre>import { IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class LikeDto {<br>  @IsNotEmpty()<br>  @IsString()<br>  articleId: string;<br><br>  userId: string;<br>}</pre><p><strong>like.service.ts</strong></p><pre>import { Inject, Injectable, NotFoundException } from &#39;@nestjs/common&#39;;<br><br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br><br>import { Model } from &#39;mongoose&#39;;<br><br>import { Like, LikeDocument } from &#39;./schemas/like.schema&#39;;<br><br>import { ClientProxy } from &#39;@nestjs/microservices&#39;;<br>import { firstValueFrom } from &#39;rxjs&#39;;<br><br>import { LikeDto } from &#39;./dtos/like.dto&#39;;<br>import { IUser } from &#39;@app/common&#39;;<br><br>@Injectable()<br>export class LikesService {<br>  constructor(<br>    @InjectModel(Like.name) private likeModel: Model&lt;LikeDocument&gt;,<br>    @Inject(&#39;ARTICLE_SERVICE&#39;) private articleClient: ClientProxy,<br>  ) {}<br><br>  async create(likeDto: LikeDto, user: IUser) {<br>    const articleExists = await firstValueFrom(<br>      this.articleClient.send({ cmd: &#39;validate_article&#39; }, likeDto.articleId),<br>    );<br><br>    if (!articleExists) {<br>      throw new NotFoundException(<br>        `Article with ID &quot;${likeDto.articleId}&quot; not found.`,<br>      );<br>    }<br><br>    likeDto.userId = user.id;<br><br>    const data = await this.likeModel.create(likeDto);<br><br>    const like = await data.save();<br><br>    this.countArticleLikes(likeDto.articleId);<br><br>    return { status: &#39;success&#39;, data: like };<br>  }<br><br>  async getAll(filter: any) {<br>    const likes = await this.likeModel.find(filter);<br><br>    return { status: &#39;success&#39;, data: likes };<br>  }<br><br>  private async countArticleLikes(articleId: string) {<br>    const count = await this.likeModel.countDocuments({ articleId });<br><br>    this.articleClient.emit(&#39;like_created&#39;, { count, articleId });<br>  }<br>}</pre><p><strong>like.controller.ts</strong></p><pre>import {<br>  Get,<br>  Body,<br>  Post,<br>  Query,<br>  UsePipes,<br>  UseGuards,<br>  Controller,<br>  ValidationPipe,<br>} from &#39;@nestjs/common&#39;;<br><br>import { LikesService } from &#39;./likes.service&#39;;<br><br>import { LikeDto } from &#39;./dtos/like.dto&#39;;<br><br>import { CurrentUser } from &#39;@app/common&#39;;<br><br>import { IUser } from &#39;@app/common&#39;;<br><br>import { UseInterceptors } from &#39;@nestjs/common&#39;;<br><br>import { AttachUsers } from &#39;@app/common/interceptors/attach-users.interceptor&#39;;<br><br>@Controller(&#39;likes&#39;)<br>export class LikesController {<br>  constructor(private readonly likesService: LikesService) {}<br><br>  @Get()<br>  @UseInterceptors(<br>    AttachUsers({<br>      userIdField: &#39;userId&#39;,<br>      attachToField: &#39;user&#39;,<br>      dataPath: &#39;data&#39;,<br>    }),<br>  )<br>  async findAll(@Query() query: any) {<br>    return this.likesService.getAll(query);<br>  }<br><br>  @Post()<br>  @UsePipes(ValidationPipe)<br>  async create(@Body() likeDto: LikeDto, @CurrentUser() user: IUser) {<br>    return this.likesService.create(likeDto, user);<br>  }<br>}</pre><p><strong>check-likes-middleware.ts</strong></p><pre>import { Injectable, NestMiddleware } from &#39;@nestjs/common&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { Request, Response, NextFunction } from &#39;express&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { Like, LikeDocument } from &#39;../schemas/like.schema&#39;;<br><br>@Injectable()<br>export class CheckLikeExistsMiddleware implements NestMiddleware {<br>  constructor(@InjectModel(Like.name) private likeModel: Model&lt;LikeDocument&gt;) {}<br><br>  async use(req: Request, res: Response, next: NextFunction) {<br>    const user = (req as any).user;<br>    const articleId = req.body.articleId;<br><br>    if (!user || !articleId) {<br>      // Pass through if user or articleId isn&#39;t available at this stage<br>      return next();<br>    }<br><br>    const existingLike = await this.likeModel.findOne({<br>      userId: user.id,<br>      articleId: articleId,<br>    });<br><br>    if (existingLike) {<br>      // If the like already exists, send a 200 OK response and end the request.<br>      return res.status(200).json({<br>        status: &#39;success&#39;,<br>        message: &#39;Article has already been liked by this user.&#39;,<br>      });<br>    }<br><br>    // If no like exists, proceed to the controller/service handler.<br>    next();<br>  }<br>}</pre><p><strong>like.module.ts</strong></p><pre>import {<br>  Module,<br>  NestModule,<br>  RequestMethod,<br>  MiddlewareConsumer,<br>} from &#39;@nestjs/common&#39;;<br><br>import { LikesController } from &#39;./likes.controller&#39;;<br>import { LikesService } from &#39;./likes.service&#39;;<br><br>import { JwtModule } from &#39;@nestjs/jwt&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br><br>import { APP_GUARD } from &#39;@nestjs/core&#39;;<br>import { JwtAuthGuard } from &#39;@app/common&#39;;<br><br>import { Like, LikeSchema } from &#39;./schemas/like.schema&#39;;<br><br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br><br>import { CheckLikeExistsMiddleware } from &#39;./middlewares/check-likes-middleware&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br><br>    MongooseModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: async (config: ConfigService) =&gt; ({<br>        uri: config.get&lt;string&gt;(&#39;LIKES_DB&#39;),<br>      }),<br>    }),<br><br>    MongooseModule.forFeature([{ name: Like.name, schema: LikeSchema }]),<br><br>    JwtModule.registerAsync({<br>      imports: [ConfigModule],<br>      // Use a factory to inject the ConfigService and get the JWT_SECRET<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        secret: configService.get&lt;string&gt;(&#39;JWT_SECRET&#39;),<br>        signOptions: { expiresIn: &#39;1h&#39; },<br>      }),<br>      inject: [ConfigService],<br>    }),<br><br>    ClientsModule.register([<br>      {<br>        name: &#39;ARTICLE_SERVICE&#39;,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>          queue: &#39;articles_queue&#39;,<br>          queueOptions: { durable: false },<br>        },<br>      },<br>      {<br>        name: &#39;USER_SERVICE&#39;,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [&#39;amqp://guest:guest@localhost:5672&#39;],<br>          queue: &#39;users_queue&#39;,<br>          queueOptions: { durable: false },<br>        },<br>      },<br>    ]),<br>  ],<br><br>  controllers: [LikesController],<br><br>  providers: [LikesService, { provide: APP_GUARD, useClass: JwtAuthGuard }],<br>})<br>export class LikeModule implements NestModule {<br>  configure(consumer: MiddlewareConsumer) {<br>    consumer<br>      .apply(CheckLikeExistsMiddleware)<br>      .forRoutes({ path: &#39;likes&#39;, method: RequestMethod.POST });<br>  }<br>}</pre><p><strong>main.ts</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { LikeModule } from &#39;./likes.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(LikeModule);<br>  await app.listen(3002);<br>}<br>bootstrap();</pre><p><strong>Time To Test!</strong></p><p><strong>Sign Up</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bX1Pr7rvONilkQurXEViiA.png" /></figure><p><strong>Login</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*6EyaGp6CzlLsTYm6vBlteQ.png" /></figure><p><strong>Create Article</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGu-BqrL_2ZpkRqGd-9X7g.png" /></figure><p><strong>Get All Articles</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYKm1UTsSVuotdJ1JwhKXQ.png" /></figure><p><strong>Like A Post</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSv1KVAyn07kKrVJcNFEdg.png" /></figure><p><strong>Get Likes On A Post</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AXOQq0ZDzmejgGTVxhaYg.png" /></figure><p><strong>Create Comment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvtYH3_CrAbAVbDsAW-u4A.png" /></figure><p><strong>Get Comments On A Post</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8PE4N0B6EEXWOx3RQQK1A.png" /></figure><p>After a series of continuous testing, we can get the particular post by ID, like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilZe_9FIcBsRrEhcxKo1Ug.png" /></figure><p>Here’s a link to the <strong>GitHub</strong> repo <a href="https://github.com/Cedar1000/nest-blog-articles">link</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e41abba03f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Elastic Search In Your Nest JS Application Using Docker]]></title>
            <link>https://medium.com/@cedard686/setting-up-elastic-search-in-your-nest-js-application-8aae7ad2e1f8?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aae7ad2e1f8</guid>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 21:43:17 GMT</pubDate>
            <atom:updated>2025-07-09T17:42:53.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*X-NU7lbqFLMxBqw6e5ijzQ.png" /></figure><p>Hey there, are you looking to build a high-speed and scalable full-text search functionality into your application? Then<strong> Elastic Search </strong>is the technology you! In this article, we’re going to be discussing what it is and how to set it up with a <strong>Nest.js</strong> application. So here are some terminologies.</p><p><strong>What is Elastic Search?</strong></p><p>Elasticsearch is a <strong>distributed, open-source search and analytics engine</strong> built on top of <strong>Apache Lucene</strong>. It is designed for fast, scalable full-text search and is commonly used for a wide range of use cases, including log and event data analysis, application search, monitoring, and real-time analytics.</p><p>In simpler terms, it’s a technology that helps you <strong>store, search, and analyze large volumes of data quickly and in near real-time</strong>.</p><p><strong>Index</strong>: A logical namespace for storing documents, similar to a database table.</p><p><strong>Document</strong>: The basic unit of data (JSON format) stored in an index.</p><p><strong>Field</strong>: A key-value pair inside a document.</p><p><strong>Shard</strong>: An index is split into shards for horizontal scaling. Each shard is a self-contained search engine.</p><p><strong>Replica</strong>: A copy of a shard, used for fault tolerance and parallel querying.</p><p><strong>Node</strong>: A single server that is part of an Elasticsearch cluster.</p><p><strong>Cluster</strong>: A group of nodes that together hold the entire data and provide indexing and search capabilities.</p><p><strong>Kibana</strong>: This is a Graphical User Interface to visualize the data stored in <strong>Elastic</strong></p><p><strong>STEP 1</strong></p><p>Let’s spin up a new Nest.js application</p><pre>nest new elastic-search-app</pre><p><strong>STEP 2</strong></p><p>We’re going to set up Elastic Search using Docker. We’ll be spinning up containers for both <strong>Elasticsearch</strong> and <strong>Kibana. </strong>In the root of our project, let’s create a <strong><em>docker-compose.yaml </em></strong>and paste this setup like so</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  elasticsearch:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:8.12.2<br>    container_name: elasticsearch<br>    environment:<br>      - discovery.type=single-node<br>      - xpack.security.enabled=false<br>      - xpack.monitoring.collection.enabled=true<br>    ports:<br>      - &quot;9200:9200&quot;<br>    networks:<br>      - elk<br><br>  kibana:<br>    image: docker.elastic.co/kibana/kibana:8.12.2<br>    container_name: kibana<br>    ports:<br>      - &quot;5601:5601&quot;<br>    environment:<br>      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200<br>      - xpack.security.enabled=false<br>    depends_on:<br>      - elasticsearch<br>    networks:<br>      - elk<br><br>networks:<br>  elk:<br>    driver: bridge</pre><p>Then run</p><pre>docker compose up -d</pre><p>If this is done successfully, when we run <strong>docker ps</strong> we should have containers for <strong>Elasticsearch</strong> and <strong>Kibana </strong>running on our local machine on ports <strong>9200 </strong>and<strong> 5601, </strong>respectively.</p><p><strong>STEP 3</strong></p><p>We’re going to create a simple <strong><em>products</em></strong> resource<strong><em> </em></strong>in Nest.js and set up a CRUD endpoint using Elastic Search as a database. We’ll start by creating a new resource.</p><pre>nest generate resource product</pre><p>We’re going to install the <strong>nestjs/elasticsearch</strong> package like so</p><pre>npm i --save @nestjs/elasticsearch @elastic/elasticsearch</pre><p><strong>STEP 4</strong></p><p>Configure <strong>Elasticsearch.</strong> In your <strong><em>product.module.ts</em></strong> file</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ProductService } from &#39;./product.service&#39;;<br>import { ProductController } from &#39;./product.controller&#39;;<br><br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br><br>import { Product } from &#39;./entities/product.entity&#39;;<br><br>import { ElasticsearchModule } from &#39;@nestjs/elasticsearch&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([Product]),<br>    ElasticsearchModule.register({<br>      node: &#39;http://localhost:9200&#39;,<br>    }),<br>],<br>controllers: [ProductController],<br>providers: [ProductService],<br>})<br><br>export class ProductModule {}</pre><p><strong>STEP 4</strong></p><p>We’ll set up DTOs for both <strong>create</strong> and <strong>update</strong>. We’ll define a <strong>CreateProductDto</strong> like so</p><pre>import { IsNotEmpty, IsNumber, IsString } from &#39;class-validator&#39;;<br><br><br>export class CreateProductDto {<br>  @IsNotEmpty()<br>  @IsString() <br>  name: string;<br><br>  @IsNotEmpty()<br>  @IsNumber()<br>  price: number;<br><br>  @IsNotEmpty()<br>  @IsString()<br>  description: string;<br>}</pre><p>And <strong>UpdateProductDto </strong>like so</p><pre>import { PartialType } from &#39;@nestjs/mapped-types&#39;;<br>import { CreateProductDto } from &#39;./create-product.dto&#39;;<br>export class UpdateProductDto extends PartialType(CreateProductDto) {}</pre><p><strong>STEP 5</strong></p><p>We’ll set up the product service with the different handlers like so</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ElasticsearchService } from &#39;@nestjs/elasticsearch&#39;;<br>import { CreateProductDto } from &#39;./dto/create-product.dto&#39;;<br>import { UpdateProductDto } from &#39;./dto/update-product.dto&#39;;<br><br>@Injectable()<br>export class ProductService {<br>  private readonly index = &#39;products&#39;;<br><br>  constructor(private readonly esService: ElasticsearchService) {}<br><br>  async create(product: CreateProductDto) {<br>    const response = await this.esService.index({<br>      index: this.index,<br>      document: product,<br>    });<br>    return response;<br>  }<br><br>  async findAll(): Promise&lt;any[]&gt; {<br>    const result = await this.esService.search({<br>      index: this.index,<br>      query: { match_all: {} },<br>    });<br><br>    return result.hits.hits.map((hit: any) =&gt; ({<br>      id: hit._id,<br>      ...hit._source,<br>    }));<br>  }<br><br>  async findOne(id: string) {<br>    const result = await this.esService.get({<br>      index: this.index,<br>      id,<br>    });<br>    return result._source;<br>  }<br><br>  async update(id: string, updateData: UpdateProductDto) {<br>    await this.esService.update({<br>      index: this.index,<br>      id,<br>      doc: updateData,<br>    });<br>    return this.findOne(id);<br>  }<br><br>  async remove(id: string) {<br>    return this.esService.delete({<br>      index: this.index,<br>      id,<br>    });<br>  }<br><br>  async search(query: string) {<br>    const result = await this.esService.search({<br>      index: this.index,<br>      query: {<br>        query_string: {<br>          query: `*${query}*`,<br>          fields: [&#39;name&#39;, &#39;description&#39;],<br>        },<br>      },<br>    });<br><br>    return result.hits.hits.map((hit) =&gt; hit._source);<br>  }<br>}</pre><p><strong>STEP 6</strong></p><p>We’ll set up the product controller with the different handlers like so</p><pre>import {<br> Get,<br> Put,<br> Post,<br> Body,<br> Query,<br> Param,<br> Delete,<br> UsePipes,<br> UseGuards,<br> Controller<br>} from &#39;@nestjs/common&#39;;<br><br><br>import { ProductsService } from &#39;./products.service&#39;;<br>import { CreateProductDto } from &#39;./dto/create-product.dto&#39;;<br>import { UpdateProductDto } from &#39;./dto/update-product.dto&#39;;<br><br>@Controller(&#39;products&#39;)<br>export class ProductsController {<br>  constructor(private readonly productsService: ProductsService) {}<br><br>  @Post()<br>  @UsePipes(new ValidationPipe({ transform: true }))<br>  create(@Body() dto: CreateProductDto) {<br>    return this.productsService.create(dto);<br>  }<br><br>  @Get()<br>  findAll() {<br>    return this.productsService.findAll();<br>  }<br><br>  @Get(&#39;search&#39;)<br>  search(@Query(&#39;q&#39;) q: string) {<br>    return this.productsService.search(q);<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  findOne(@Param(&#39;id&#39;) id: string) {<br>    return this.productsService.findOne(id);<br>  }<br><br>  <br>  @Put(&#39;:id&#39;)<br>  @UsePipes(new ValidationPipe({ transform: true }))<br>  update(@Param(&#39;id&#39;) id: string, @Body() dto: UpdateProductDto) {<br>    return this.productsService.update(id, dto);<br>  }<br><br>  @Delete(&#39;:id&#39;)<br>  remove(@Param(&#39;id&#39;) id: string) {<br>    return this.productsService.remove(id);<br>  }<br>}</pre><p><strong>STEP 7</strong></p><p>Start the app</p><pre>npm run start:dev</pre><p><strong>STEP 8</strong></p><p>Time to test the endpoints</p><p><strong>Creating a Product!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*SaDgXUK8iYB96sibYWf_iA.png" /></figure><p><strong>Fetching all products!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*1wGdPxP5okKaNcI_NUzXTA.png" /></figure><p>Finally, searching for a product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*VbNjQYwwS30vHDOroMpQbA.png" /></figure><p><strong>We can also visualise the data on Kibana</strong></p><p><strong>STEP 1</strong></p><p>Make sure Elastic Search and Kibana containers are currently running on your machine. You can confirm this by running.</p><pre>docker ps</pre><p>and confirming you get an output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RPpYjJj-9VkVfbQDu54s8g.png" /></figure><p>On your browser, navigate to <a href="http://localhost:5601/">http://localhost:5601</a>, then on the sidebar, <strong>Management</strong> &gt; <strong>Index Management, </strong>and you should see our products index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*M_t78YHo9bq6rtdXon6JYQ.png" /></figure><p><strong>STEP 3</strong></p><p>On the sidebar, click on <strong>Discover</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*F7GYQll6oK_TbAatnB-WWg.png" /></figure><p><strong>STEP 4</strong></p><p>Since it’s most likely our first time here, we’ll be creating a <strong>data view.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*u72S83QbJlBjQlACmh-v4g.png" /></figure><p>With an index pattern that matches the name of our earlier created index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCjLfgjS6zeazxhud4owNw.png" /></figure><p><strong>STEP 5</strong></p><p>After creating the<strong> date view, </strong>we should be able to search through the data in the index like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNp0N7DMPqGqaKJrMf5-Fw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aae7ad2e1f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up CI/CD for AWS Lambda with GitHub Actions and SAM CLI]]></title>
            <link>https://aws.plainenglish.io/setting-up-ci-cd-for-aws-lambda-with-github-actions-and-sam-cli-28fbca934362?source=rss-5c3060c26185------2</link>
            <guid isPermaLink="false">https://medium.com/p/28fbca934362</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Cedar Daniel]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 20:50:48 GMT</pubDate>
            <atom:updated>2025-11-15T15:19:15.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sul1FhskUB4zfwPCAECUgA.png" /></figure><h3>Introduction</h3><p>Continuous Integration and Continuous Deployment (CI/CD) are essential for automating the deployment of AWS Lambda functions, ensuring fast, reliable, and efficient updates. With <strong>GitHub Actions</strong> and the <strong>AWS Serverless Application Model (SAM) CLI</strong>, you can create a streamlined pipeline that automates building, testing, and deploying your Lambda functions.</p><p>In this article, we’ll walk through setting up a <strong>CI/CD pipeline</strong> for AWS Lambda using <strong>GitHub Actions</strong> and <strong>SAM CLI</strong>, covering everything from repository setup to automated deployments. Whether you’re new to AWS Lambda or looking to optimize your serverless workflow, this guide will help you build a robust deployment pipeline.</p><p><strong>Note:</strong> You need an <strong>AWS account</strong> with permissions to create and manage Lambda functions, S3, and IAM roles before proceeding.</p><ol><li>In your cloud console, search and navigate to <strong>IAM.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PhKbXZliWbYswrygvezbA.png" /><figcaption>IAM console</figcaption></figure><p>2. On the left, go to <strong>users</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*TMEkTN2P2TIDgdOQ2Q5GKw.png" /></figure><p>3. And then <strong>create user</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KeFv5T4IuhB2HRNiXJ-Tw.png" /></figure><p>4. Give the user a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iitfg45xzFsskEelTp-f5w.png" /></figure><p>5. Go to <strong>Attach policies directly,</strong> and for the sake of this, let’s give the user <strong>AdministratorAccess</strong> and proceed to create the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoOw-e5E_UaCj1dIPaTYpQ.png" /></figure><p>6. Amongst the list of users in the IAM dashboard, click on the user you just created, go to <strong>Security credentials,</strong> and then <strong>Create access key.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuD3piHmoh_pfkvDxRDlaw.png" /></figure><p>7. For the use case, choose <strong>Command Line Interface (CLI) </strong>and then download the CSV file for the keys, or else you won’t be able to access them again and will have to create new credentials<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRtngGQGSo1PTX0arNEOYQ.png" /></figure><p>8. Install AWS CLI depending on your OS using this link <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">here</a>. Confirm successful installation by running the command <strong>aws help, </strong>and be sure to get a response that is not an error.</p><p>9. Next, configure the AWS CLI. To do this, open your terminal and run the command <strong>aws configure </strong>and supply the <strong>access_id</strong> and <strong>secret_key</strong> and the region you want to deploy in, e.g., <strong>us-east-1</strong>.</p><p>10. Install SAM CLI depending on your OS using this link <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">here</a>.</p><p>11. Now, proceed to create a GitHub repo for your serverless function.</p><p>12. After creation, in the repo navigate to <strong>settings </strong>&gt; <strong>Secrets and variables </strong>&gt; <strong>Actions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2eLOLSLZBVMqS0UP-BDRw.png" /></figure><p>13. Go ahead and create action secrets one after the other with the names <strong>AWS_ACCESS_KEY_ID</strong>, <strong>AWS_SECRET_ACCESS_KEY</strong>, <strong>AWS_REGION</strong>, with their respective values, which you already saved in the CSV file earlier on. Note that the region should match the one you used when configuring the AWS CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4jZI4L3oYJa-RbT8oNh5w.png" /></figure><p>14. Proceed to spin up a boilerplate for a new Lambda function using the SAM CLI. In this example, I’ll be using Node.js, and I’ll name the function <strong>my-new-node-function</strong>. Run</p><pre>sam init --runtime nodejs18.x --name my-new-node-function --app-template hello-world, say yes to all the prompts.</pre><p>15. Once the function is created, use <strong>code . </strong>to open it up in your VS Code. It should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tshkqv7M8fyFKtMnmbuCWA.png" /></figure><p>16. The amazing thing about SAM CLI is that it gives you a really nice boilerplate that you can build upon. Let’s modify the default function, navigate to <strong>hello-world &gt; app.mjs, </strong>and change the default message from “hello world” to “hello world from my first function” like so:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PullMe2ARQ5_M8zUnL0XAA.png" /></figure><p>17. Let’s test the function locally. In other to do this, make sure you have Docker installed, use this link <a href="https://docs.docker.com/engine/install/">here</a> to install Docker for your particular OS, and confirm successful installation by running <strong>docker -v </strong>in your terminal to see if you get the version back.</p><p>18. In your terminal, make sure you’re in the root of the project and run <strong>sam build, </strong>then <strong>sam local invoke. </strong>You should get back the response</p><pre>{&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;{\&quot;message\&quot;:\&quot;hello world from my first function\&quot;}&quot;}.</pre><p>19. Go ahead and create a <strong>.github</strong> &gt; <strong>workflows</strong> &gt; <strong>sam-pipeline.yml </strong>in the root of the project<strong> </strong>and paste this code.</p><pre>on:<br> push:<br>   branches:<br>     - main<br>jobs:<br> build-deploy:<br>   runs-on: ubuntu-latest<br>   steps:<br>     - uses: actions/checkout@v2<br>     - uses: actions/setup-python@v2<br>     - uses: aws-actions/setup-sam@v1<br>     - uses: aws-actions/configure-aws-credentials@v1<br>       with:<br>         aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>         aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>         aws-region: ${{ secrets.AWS_REGION }}<br>     # sam build<br>     - run: sam build --use-container<br>     # sam deploy<br>     - run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset --stack-name sam-hello-world --capabilities CAPABILITY_IAM --region ${{ secrets.AWS_REGION }}</pre><p>20. Proceed to push this code to your already existing GitHub repo.</p><p>21. Once you’ve done that, go to the <strong>Actions</strong> tab in the repo and observe the pipeline; if all goes well, you should be able to see that the deployment was successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgckwDzQM4bJa--2Rzl_uA.png" /></figure><p>22. In your console, go to Lambda in the region you specified in the workflow, and you see the function show like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN8Vn5sLCBFjHTanLpfnng.png" /></figure><p><strong>Disclaimer: </strong>Sometimes the function name might show up as something like this <strong>hello-world-function-HelloWorldFunction-SzkBGik3L0qt</strong>, no worries, just add this extra line in your <strong>template.yaml</strong> file under Resources and Properties like so;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r-N9VCv7AO621Hk0X21uQ.png" /></figure><p>Then commit your changes and push again.</p><p>23. Your function is automatically created with an API for you to access it. In order to test it live, just click on it and then url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBlfKvBbAph--2M2RubqPA.png" /></figure><p>You should get the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2Q1DNp4D9OnCCnH4mZF1A.png" /></figure><blockquote><em>Setting up CI/CD for AWS Lambda with GitHub Actions and the SAM CLI brings automation, reliability, and speed to your deployment workflow. By integrating these tools, you’re not just streamlining delivery — you’re also building a foundation for scalable, maintainable, and production-ready serverless applications.</em></blockquote><blockquote><em>As you continue to iterate on your serverless projects, this pipeline will help you ship confidently and focus more on writing great code. Happy building!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28fbca934362" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/setting-up-ci-cd-for-aws-lambda-with-github-actions-and-sam-cli-28fbca934362">Setting Up CI/CD for AWS Lambda with GitHub Actions and SAM CLI</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>