<?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 &lt;saraahso/&gt; on Medium]]></title>
        <description><![CDATA[Stories by &lt;saraahso/&gt; on Medium]]></description>
        <link>https://medium.com/@santanasparrerdevelopment?source=rss-c0840b48621------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fz8uSrEN_rGEj_42YMTfPg.png</url>
            <title>Stories by &amp;lt;saraahso/&amp;gt; on Medium</title>
            <link>https://medium.com/@santanasparrerdevelopment?source=rss-c0840b48621------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:59:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@santanasparrerdevelopment/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[Testing Next.js 15RC with React compiler]]></title>
            <link>https://blog.stackademic.com/testing-next-js-15rc-with-react-compiler-e987669054c3?source=rss-c0840b48621------2</link>
            <guid isPermaLink="false">https://medium.com/p/e987669054c3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-compiler]]></category>
            <dc:creator><![CDATA[<saraahso/>]]></dc:creator>
            <pubDate>Fri, 24 May 2024 15:47:24 GMT</pubDate>
            <atom:updated>2024-05-28T00:25:13.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYvAxzv20uLoExIILcwszg.png" /></figure><p>Hey there 👋,</p><p>Those of us that watched React Conf 2024 were seeking to put the React compiler to the test with our beloved frameworks. Since then, I’ve been experimenting with Next.js, and just yesterday, they launched Next.js 15 Release Candidate with React 19 compatibility. Yay!</p><p>Let’s test it together?! For the sake of seeing how it works, I’ll set up a pretty simple example. Let’s get it started!</p><p>For today’s guide, having the React Developer Tools extension installed in your browser will be quite handy. If you don’t have it yet, check it out: <a href="https://react.dev/learn/react-developer-tools">https://react.dev/learn/react-developer-tools</a></p><p>First things first, let’s start a new project using a version of Next.js that is stable:</p><pre>npx create-next-app@latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*r5DFHkHBnVNVlx82dPjLSw.png" /></figure><p>Okay, did you recall that this code is only a basic example to understand how React compiler works? That being said, we are going to include the <em>‘use client’</em> notation into our <em>page.tsx</em> file. However, newbie Next.JS developers should be aware that this isn’t the best idea to add this notation inside pages, but this is a story for another guide. Now that I’m excused, let’s add some logic to our <em>page.tsx:</em></p><pre>&#39;use client&#39;<br>import {useState} from &quot;react&quot;;<br>import ChildComponent from &quot;@/components/child&quot;;<br><br>export default function Home() {<br>  const [ counter, setCounter ] = useState(0);<br><br>  const handleCounter = () =&gt; {<br>    setCounter(counter+1);<br>  }<br><br>  return (<br>    &lt;main className=&quot;flex min-h-screen flex-col items-center justify-between p-24&quot;&gt;<br>      &lt;h1&gt;{counter}&lt;/h1&gt;<br>         &lt;button className=&quot;h-10 px-5 text-indigo-100 bg-blue-600 rounded-lg hover:bg-blue-800&quot; onClick={handleCounter}&gt;Count&lt;/button&gt;<br>      &lt;ChildComponent/&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>The next step is to create a child component, which is as simple as that:</p><pre>function ChildComponent(){<br>    return &lt;h1&gt;Am I memoized?&lt;/h1&gt;<br>}<br>export default ChildComponent</pre><p>If you’re familiar with react re-renders, you probably know what happens if we run this code, but for those who aren’t, let me explain.</p><p>All the necessary information for our counter is located on the <em>page.tsx</em>, our ChildComponent is rendered within the page but has nothing to do with the counter itself and because of it, it will be rendered every time we click the button and update the counter, even if there are no changes within the ChildComponent. Let’s test it out:</p><pre>npm run dev</pre><p>Open the inspector in your browser and navigate to the profile tab; make sure that “Record why each component rendered with profiling” is checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBXywaHI7ayhgph9CGUVsA.png" /></figure><p>Now you can start recording with profiler. Click “Start profiling” and then play around with our counter. Click the button a few times to make it go up. When you’re done, stop the profiler and look at the results. You’ll notice that ChildComponent is rendered every time the button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3JPkZUs0fDsev-HpbIc3w.gif" /></figure><p>Okay, let’s make the necessary changes to see the magic of the React compiler. Let’s go ahead and install all the necessary packages.</p><pre> npm install next@rc react@rc react-dom@rc --force</pre><p>In addition, we need to install the react compiler plugin.</p><pre>npm install babel-plugin-react-compiler</pre><p>If you happen to have a next.config.mjs file, you can simply change its extension to .js and include the following:</p><pre>const nextConfig = {<br>  experimental: {<br>    reactCompiler: true,<br>  },<br>};<br> <br>module.exports = nextConfig;</pre><p>Simple enough? Now let’s return to our browser and see whether anything has changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8-_KLas0Wz_6HQALBgKDw.gif" /></figure><p>As you can see, our ChildComponent is now memoized instead of rendered with each button click. Easy like this! 🌟</p><p>If you’re interested in learning more, be sure to check out the sources:</p><p><a href="https://nextjs.org/blog/next-15-rc">https://nextjs.org/blog/next-15-rc</a><br><a href="https://react.dev/learn/react-compiler">https://react.dev/learn/react-compiler</a></p><p>Have fun exploring React Compiler with Next.js and feel free to share your thoughts with me.</p><p>See you 👋</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e987669054c3" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/testing-next-js-15rc-with-react-compiler-e987669054c3">Testing Next.js 15RC with React compiler</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Stripe Checkout Mode with Next.js 13]]></title>
            <link>https://blog.stackademic.com/integrating-stripe-checkout-mode-with-next-js-13-7fbf1680c600?source=rss-c0840b48621------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbf1680c600</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[shopping-cart]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[nextjs-13]]></category>
            <dc:creator><![CDATA[<saraahso/>]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 14:33:47 GMT</pubDate>
            <atom:updated>2023-10-27T06:23:11.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating Stripe Checkout Mode with Next.js App Router</h3><p>Hey there! 👋<br>Since the release of the Next.js App router last year, there have been numerous integrations that require updating. Today we will look into the steps of integrating Stripe Checkout mode with Next.JS App Router.</p><p>If you came from <a href="https://medium.com/stackademic/creating-a-modal-shopping-cart-with-next-js-13-63b3889ba875">Part I</a>, that’s great. Let’s keep going. If not, you can use this guide to assist you in integrating Stripe checkout mode into your application. You will only need to make the necessary changes to your checkout button.</p><p>Alright, let’s dive right in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*w6YpVMITvfjyvbjuoGnE8A.gif" /></figure><h3>Requirements</h3><ul><li>The keys required to make this project work will only be available to you if you have a Stripe account. If you don’t already have it, check out their website: <a href="http://www.stripe.com/">www.stripe.com</a></li><li>This guide assumes you have a shopping cart set up in your project. If you don’t already have one, check my previous post: <a href="https://medium.com/stackademic/creating-a-modal-shopping-cart-with-next-js-13-63b3889ba875">Creating a Modal Shopping Cart with Next.js 13 and Stripe</a></li><li>Considering the last point, it’s likely that you have a Next.JS 13 project going in your local.</li></ul><h3>First steps</h3><p>To install the Stripe package and its dependencies, you can use the following command:</p><pre>npm install --save stripe @stripe/stripe-js</pre><p>To configure your project, make sure to have a .env.local file at the root directory and include the necessary Stripe API keys obtained from your Stripe Dashboard.</p><pre># Stripe keys<br>NEXT_PUBLIC_TEST_STRIPE_PUBLISHABLE_KEY={YOUR_STRIPE_PUBLISHABLE_KEY}<br>STRIPE_TEST_SECRET_KEY={YOUR_STRIPE_SECRET_KEY}</pre><p>To utilize the keys, it is necessary to initialize a new instance of Stripe. We will create a new <em>config/stripe.ts</em> path. In this file, we will ensure that there’s an instance of our environment variable or raise a new error if it is not found. Please include your Stripe key within the new Stripe constructor instance and specify the API version to ensure compatibility with a specific version of the Stripe API.</p><pre>import Stripe from &#39;stripe&#39;;<br><br>if (!process.env.STRIPE_TEST_SECRET_KEY) {<br>    throw new Error(&#39;STRIPE_TEST_SECRET_KEY is missing. Please set the environment variable.&#39;);<br>}<br><br>const stripe = new Stripe(process.env.STRIPE_TEST_SECRET_KEY, {<br>    apiVersion: &quot;2023-08-16&quot;,<br>});<br><br>export default stripe;</pre><h3>Adding a new route handler</h3><p>Let’s create a new <em>api/</em> folder in our <em>src/app/</em> directory, and inside of it, a <em>checkout_sessions/</em> folder with a <em>route.ts</em> file. This handler will be responsible to create a Stripe session id, which will contain the cart items and other payment options.</p><pre>├── app<br>│   ├── api<br>│   │   ├── checkout_sessions<br>│           ├──route.ts<br>├── config<br>│   ├── stripe.ts</pre><pre>import {NextRequest, NextResponse} from &quot;next/server&quot;;<br>import {headers} from &quot;next/headers&quot;;<br>import {CartItem} from &quot;@/types/type&quot;;<br>import stripe from &quot;@/config/stripe&quot;;<br><br><br>export async function POST(req: NextRequest, res: NextResponse) {<br>    const headersList = headers();<br>    const {cartDetails} = await req.json();<br>    const cartDetailsArray: CartItem[] = Object.values(cartDetails) as CartItem[];<br><br>    const lineItems = cartDetailsArray.map((item: CartItem) =&gt; {<br>        return {<br>            price_data: {<br>                currency: item.currency,<br>                product_data: {<br>                    name: item.name,<br>                },<br>                unit_amount: item.price,<br>            },<br>            quantity: item.quantity,<br>        };<br>    });<br><br>    try {<br>        const session = await stripe.checkout.sessions.create({<br>            payment_method_types: [&quot;card&quot;],<br>            line_items: lineItems,<br>            mode: &quot;payment&quot;,<br>            success_url: `${headersList.get(&quot;origin&quot;)}/thank-you`,<br>            cancel_url: `${headersList.get(&quot;origin&quot;)}/`,<br>        });<br><br>        return NextResponse.json({sessionId: session.id});<br>    } catch (err) {<br>        console.log(err)<br>        return NextResponse.json({error: &quot;Error creating checkout session&quot;});<br>    }<br>}</pre><p>Let’s break our <em>route.ts</em> down:</p><ol><li>To handle the request, let’s define a POST function.</li><li>The receiving request includes <em>cartDetails</em> in its body from the next step. Then, we will convert it into an array.</li><li>In order to align <em>cartDetails</em> with Stripe’s line Items format, we will need to make some adjustments.</li><li>Following this, we will initiate a new checkout session, which, if successful, will result in the creation of a session id. You can configure the payment options available in your app. In this step, you have the option to pass a shipping method or specify the allowed countries. You have the flexibility to customize your success and cancel URLs according to your preferences.</li><li>If there is a problem, it logs it and sends an error message in response.</li></ol><h3>Handling checkout button</h3><p>If you have followed my previous guide, we can refactor our code by extracting the checkout button from the <em>modal.tsx</em> file and placing it in a separate <em>checkout.tsx</em> file. If your shopping cart was set up differently, go to the code for your checkout button and add a new handler. This is how the file looks like:</p><pre>import {useShoppingCart} from &quot;use-shopping-cart&quot;;<br>import {loadStripe} from &quot;@stripe/stripe-js&quot;;<br><br>export default function CheckoutButton() {<br>    const {cartCount = 0, cartDetails} = useShoppingCart();<br><br>    const redirectToCheckout = async () =&gt; {<br>        try {<br>            const stripe = await loadStripe(process.env.NEXT_PUBLIC_TEST_STRIPE_PUBLISHABLE_KEY as string);<br><br>            if (!stripe) throw new Error(&#39;Stripe failed to initialize.&#39;);<br><br>            const checkoutResponse = await fetch(&#39;/api/checkout_sessions&#39;, {<br>                method: &#39;POST&#39;,<br>                headers: {<br>                    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                },<br>                body: JSON.stringify({cartDetails}),<br>            });<br><br>            const {sessionId} = await checkoutResponse.json();<br>            const stripeError = await stripe.redirectToCheckout({sessionId});<br><br>            if (stripeError) {<br>                console.error(stripeError);<br>            }<br>        } catch (error) {<br>            console.error(error);<br>        }<br>    };<br><br>    return (<br>        &lt;button<br>            onClick={() =&gt; cartCount &gt; 0 &amp;&amp; redirectToCheckout()}<br>            disabled={cartCount === 0}<br>            className=&quot;rounded-md border border-transparent bg-sky-900 px-6 py-3 text-base font-medium text-white shadow-sm hover:bg-sky-700 mr-2 disabled:bg-gray-600&quot;&gt;<br>            Checkout<br>        &lt;/button&gt;<br>    );<br>}</pre><p>To sum up, this code shows how to add a redirect method to Stripe’s checkout mode. First, we utilize the useShoppingCart library hook to obtain the information about our cart. Once we have the information about the cart, we fetch our /api/checkout_sessions handler to start the checkout process.</p><p>For this flow to work, the sessionId we get back from our API call is very important. Next, we utilize the sessionId variable together with Stripe’s redirectToCheckout function. If everything is in order, the user will be automatically forwarded to Stripe’s checkout page, where Stripe will take care of processing the payment. After that, you can use your Stripe dashboard to keep an eye on the transaction and handle it.</p><h3>That&#39;s it for today…</h3><p>Hopefully this guide was useful, but if you run into any problems or want to contribute some ideas, please leave a comment.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbf1680c600" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/integrating-stripe-checkout-mode-with-next-js-13-7fbf1680c600">Integrating Stripe Checkout Mode with Next.js 13</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Modal Shopping Cart with Next.js App Router and Stripe]]></title>
            <link>https://blog.stackademic.com/creating-a-modal-shopping-cart-with-next-js-13-63b3889ba875?source=rss-c0840b48621------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b3889ba875</guid>
            <category><![CDATA[shopping-cart]]></category>
            <category><![CDATA[nextjs-13]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[<saraahso/>]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 15:13:09 GMT</pubDate>
            <atom:updated>2023-10-27T06:22:52.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! 👋</p><p>Today we’ll be creating a shopping cart functionality using Next.js 13 and Stripe. This guide will be divided into two parts. To create a cart modal, we’ll build the basic pages and elements in Part I and Part II covers checkout.</p><p>Stripe is a business payment system. It makes taking customer payments simple and safe for businesses. Stripe lets you easily add payment capability to your website or app and while Stripe has many options, we’ll use Stripe Checkout for this guide.</p><p>Vercel recently released Next.js Commerce 2.0, and in this tutorial, we will walk you through the process of setting up a project using the Commerce 2.0 cart structure.</p><h3>UI and Interactivity Tools</h3><p>For this scenario, the cart will utilize a transition using <em>@headlessui/react.</em> This library provides unstyled and accessible UI components that have been created to work smoothly with Tailwind CSS.</p><p>In addition, we’ll make use of the <em>use-shopping-cart</em> package. It will take care of managing the cart’s state, as we will be utilizing Stripe Checkout Mode for our transactions. This means we won’t require a dedicated ecommerce backend solution. Of course, this covers a project that doesn’t need a certain amount of complexity because the cart is a state and isn’t recorded in a database. Since Stripe manages user identification and address, we won’t be handling authentication or user management. You can manage each transaction and certain client features using their dashboard. For a more robust solution, it is highly recommended to explore an ecommerce platform that offers improved store management capabilities.</p><h3>What to Expect in Part I</h3><p>We’ll concentrate on building the essential pages and elements in Part I of this guide to create a fully functional cart modal. This will involve UI setup, any necessary service integration, and ensuring smooth user interactions. Our next step will be to look at the checkout process in Part II, after our cart mode is up and running. Taking care of cart info and integrating the checkout mode are part of this. Let’s get started on Part I and create our cart modal!</p><p>At the end of this first guide, the structure should look like this:</p><pre>├── data/<br>│   └── products.ts<br>├── src/<br>│   └── app/<br>│   └── components/<br>│       ├── productCard/<br>│       │   └── index.tsx<br>│       ├── cart/<br>│       │   ├── add-to-cart.tsx<br>│       │   ├── index.tsx<br>│       │   ├── modal.tsx<br>│       │   └── open-cart.tsx<br>│       ├── provider/<br>│           └── index.tsx<br>│   └── types/<br>│       └── type.ts<br>├── ...</pre><h3>Let’s get it started 🙌</h3><p>If you do not yet have a Next.js project set up, let’s create one. To start a new Next.js project, please run the following command in your terminal:</p><pre>npx create-next-app@latest</pre><p>Follow the instructions; for this project, I used:</p><pre>What is your project named? next-app-stripe<br>Would you like to use TypeScript? Yes<br>Would you like to use ESLint? Yes<br>Would you like to use Tailwind CSS? Yes<br>Would you like to use `src/` directory? Yes<br>Would you like to use App Router? (recommended) Yes<br>Would you like to customize the default import alias (@/*)? No <br>What import alias would you like configured? @/*</pre><p>Ideally, your products should be received from an API endpoint. For the sake of this guide, we can simply create a new folder <em>data</em>/ in the root of our project so that we have some mocked products to work with. Inside of it, we add a new <em>products.ts</em> file.</p><pre>export const data = [<br>    {<br>        id: &#39;price_1McB1XC4V4bOyW0mEbCcuNPe&#39;,<br>        name: &#39;Earthen Bottle&#39;,<br>        price: 1000,<br>        currency: &#39;USD&#39;,<br>        imageSrc: &#39;https://tailwindui.com/img/ecommerce-images/category-page-04-image-card-01.jpg&#39;,<br>        imageAlt: &#39;Tall slender porcelain bottle with natural clay textured body and cork stopper.&#39;,<br>    },<br>    {<br>        id: &#39;price_1McBPVC4V4bOyW0mqtp8qNLn&#39;,<br>        name: &#39;Nomad Tumbler&#39;,<br>        price: 800,<br>        currency: &#39;USD&#39;,<br>        imageSrc: &#39;https://tailwindui.com/img/ecommerce-images/category-page-04-image-card-02.jpg&#39;,<br>        imageAlt: &#39;Olive drab green insulated bottle with flared screw lid and flat top.&#39;,<br>    },<br>    {<br>        id: &#39;price_1McBQBC4V4bOyW0m4sCYXwDz&#39;,<br>        name: &#39;Focus Paper Refill&#39;,<br>        price: 650,<br>        currency: &#39;USD&#39;,<br>        imageSrc: &#39;https://tailwindui.com/img/ecommerce-images/category-page-04-image-card-03.jpg&#39;,<br>        imageAlt: &#39;Person using a pen to cross a task off a productivity paper card.&#39;,<br>    },<br>    {<br>        id: &#39;price_1McBQkC4V4bOyW0mk4NGp6bY&#39;,<br>        name: &#39;Machined Mechanical Pencil&#39;,<br>        price: 1320,<br>        currency: &#39;USD&#39;,<br>        imageSrc: &#39;https://tailwindui.com/img/ecommerce-images/category-page-04-image-card-04.jpg&#39;,<br>        imageAlt: &#39;Hand holding black machined steel mechanical pencil with brass tip and top.&#39;,<br>    },<br>]</pre><p>Let’s go ahead and set up a new <em>components/ </em>directory within our <em>src/</em> folder. Let’s create a new component for each product card in order to display them on our home page. Add a new file to the following path: <em>components/productCard/index.tsx</em></p><pre><br>import { Product } from &#39;@/types/type&#39;<br>import Image from &#39;next/image&#39;<br>import AddToCart from &quot;@/components/cart/add-to-cart&quot;;<br><br>type Props = {<br>    product: Product<br>}<br><br>export default function ProductCard({ product }: Props) {<br>    return (<br>        &lt;a key={product.id} href={product.href} className=&quot;group&quot;&gt;<br>            &lt;div className=&quot;aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-lg bg-gray-200 xl:aspect-h-8 xl:aspect-w-7&quot;&gt;<br>                &lt;Image<br>                    src={product.imageSrc}<br>                    alt={product.imageAlt}<br>                    width={500}<br>                    height={500}<br>                    className=&quot;h-full w-full object-cover object-center group-hover:opacity-75&quot;<br>                /&gt;<br>            &lt;/div&gt;<br>            &lt;h3 className=&quot;mt-4 text-sm text-gray-700&quot;&gt;{product.name}&lt;/h3&gt;<br>            &lt;p className=&quot;mt-1 text-lg font-medium text-gray-900&quot;&gt;{product.price}&lt;/p&gt;<br>            &lt;AddToCart/&gt;<br>        &lt;/a&gt;<br>    )<br>}</pre><p>To ensure the reusability of our types, it would be wise to create a new <em>type.ts</em> file.</p><pre>export type Product = {<br>    id: string;<br>    name: string;<br>    price: number;<br>    currency: string;<br>    imageSrc: string;<br>    imageAlt: string;<br>}</pre><p>Now, let’s move on building our <em>AddToCart</em> component. This component will include the button element and its corresponding event handler.Since we’ll be using the useTransition and useShoppingCart hooks, it’ll perform as a client-side component. All files related to the cart will be found under <em>/components/cart/. </em>For now keep it like below.</p><pre>&#39;use client&#39;;<br><br>import {useTransition} from &quot;react&quot;;<br><br>export default function AddToCart() {<br>    const [isPending, startTransition] = useTransition();<br><br>    const handleAddToCartButton = () =&gt; {<br>        startTransition(() =&gt; {<br>        })<br>    }<br>    return (<br>        &lt;button aria-label=&quot;Add item to cart&quot; title=&quot;Add Item to Cart&quot; disabled={isPending}<br>                className=&#39;w-full border mt-4 py-2 px-8 rounded-lg hover:bg-black hover:text-white&#39;<br>                onClick={() =&gt; handleAddToCartButton}&gt;&lt;span&gt;Add To Cart&lt;/span&gt;&lt;/button&gt;<br>    )<br>}</pre><p>Alright! We will include our mocked products to work with our newly created product cards. Inside our <em>app/page.tsx </em>let&#39;s add:</p><pre>import ProductCard from &#39;@/components/productCard&#39;<br>import {Product} from &#39;@/types/type&#39;<br>import {data} from &#39;../../data/products&#39;<br><br>export default function Home() {<br>    return (<br>        &lt;section className=&quot;w-full h-full mx-auto px-4 py-16 sm:px-6 sm:py-24 lg:px-8 bg-white&quot;&gt;<br>            &lt;h2 className=&quot;text-4xl text-black py-8&quot;&gt;Products&lt;/h2&gt;<br><br>            &lt;div className=&quot;grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8&quot;&gt;<br>                {data.map((product: Product) =&gt; (<br>                    &lt;ProductCard key={product.id} product={product}/&gt;<br>                ))}<br>            &lt;/div&gt;<br>        &lt;/section&gt;<br>    )<br>}</pre><p>Create a navbar inside<em> app/layout.tsx</em>, it will call a Cart component and cause a modal to appear when the user clicks on it.</p><pre>import &#39;./globals.css&#39;<br>import type {Metadata} from &#39;next&#39;<br>import {Inter} from &#39;next/font/google&#39;<br>import React, {Suspense} from &quot;react&quot;;<br>import OpenCart from &quot;@/components/cart/open-cart&quot;;<br>import Cart from &quot;@/components/cart&quot;;<br><br>const inter = Inter({subsets: [&#39;latin&#39;]})<br><br>export const metadata: Metadata = {<br>    title: &#39;Next App Shopping Cart&#39;,<br>    description: &#39;A simple shopping cart app built with Next.js and Tailwind CSS&#39;<br>}<br><br>export default function RootLayout({children,}: { children: React.ReactNode }) {<br>    return (<br>        &lt;html lang=&quot;en&quot;&gt;<br>        &lt;body className={inter.className}&gt;<br>        &lt;nav className=&quot;relative flex items-center justify-between p-4 lg:px-6 bg-gray-100&quot;&gt;<br>            &lt;div className=&quot;flex w-full h-24 items-center text-black text-xl&quot;&gt;<br>                &lt;div className=&quot;md:w-1/2&quot;&gt;<br>                    &lt;span&gt;Next App Cart&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div className=&quot;flex justify-end md:w-1/2&quot;&gt;<br>                    &lt;Suspense fallback={&lt;OpenCart/&gt;}&gt;<br>                        &lt;Cart/&gt;<br>                    &lt;/Suspense&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/nav&gt;<br>        &lt;Suspense&gt;<br>            &lt;main&gt;{children}&lt;/main&gt;<br>        &lt;/Suspense&gt;<br>        &lt;/body&gt;<br>        &lt;/html&gt;<br>    )<br>}</pre><p>To set up the cart, we’ll start by creating an <em>index.tsx</em> file within the <em>components/cart/</em> directory. This file will serve as a server component, and we’ll add a request to it later on. Right now, the implementation only consists of a <em>modal.tsx</em> file, which serves as our client component.</p><pre>import CartModal from &quot;@/components/cart/modal&quot;;<br><br>export default async function Cart() {<br>    return &lt;CartModal/&gt;<br>}</pre><p>It is time to install the required <a href="http://twitter.com/headlessui/react">@headlessui/react</a> that will be used in our modal in a moment.</p><pre>npm install @headlessui/react</pre><p>Our <em>cart/modal.tsx</em> component will utilize the Dialog and Transition to achieve a smooth opening and closing animation, placed on the right side of the screen. Let’s break down it into smaller parts. As an interactive element, this will be a client-side component where we will define a state to trigger the opening of the cart.</p><pre>&#39;use client&#39;;<br><br>import {Fragment, useState} from &#39;react&#39;;<br>import {Dialog, Transition} from &#39;@headlessui/react&#39;;<br>import OpenCart from &quot;@/components/cart/open-cart&quot;;<br>import {XMarkIcon} from &quot;@heroicons/react/24/outline&quot;;<br><br>export default function CartModal() {<br>    const [openCart, setOpenCart] = useState(false)<br>    return ();<br>}</pre><p>We begin by returning our button, which is in control of the state.</p><pre>&lt;button aria-label=&quot;Open cart&quot; onClick={() =&gt; setOpenCart(true)}&gt;<br>  &lt;OpenCart/&gt;<br>&lt;/button&gt;</pre><p>Then, we open our transition, which will make the opening and closing of the cart modal effect smooth. This ensures a visually pleasing user experience. Within the <em>&lt;Transition&gt;</em> element, we utilize the <em>&lt;Dialog&gt;</em> to display our modal. This modal consists of various elements such as the title, close button, cart items, subtotal, and checkout options. The first <em>&lt;Transition.child&gt;</em> is in charge of adding a gray overlay background to the screen where the modal is not visible. By now, have a look at how the file is organized.</p><pre>&#39;use client&#39;;<br><br>import {Fragment, useState} from &#39;react&#39;;<br>import {Dialog, Transition} from &#39;@headlessui/react&#39;;<br>import OpenCart from &quot;@/components/cart/open-cart&quot;;<br>import {XMarkIcon} from &quot;@heroicons/react/24/outline&quot;;<br><br>export default function CartModal() {<br>    const [openCart, setOpenCart] = useState(false)<br>    return &lt;&gt;<br>        &lt;button aria-label=&quot;Open cart&quot; onClick={() =&gt; setOpenCart(true)}&gt;<br>            &lt;OpenCart/&gt;<br>        &lt;/button&gt;<br>        &lt;Transition.Root show={openCart} as={Fragment}&gt;<br>          &lt;Dialog as=&quot;div&quot; className=&quot;relative z-10&quot; onClose={() =&gt; setOpenCart(false)}&gt;<br>            &lt;Transition.Child<br>              as={Fragment}<br>              enter=&quot;ease-in-out duration-500&quot;<br>              enterFrom=&quot;opacity-0&quot;<br>              enterTo=&quot;opacity-100&quot;<br>              leave=&quot;ease-in-out duration-500&quot;<br>              leaveFrom=&quot;opacity-100&quot;<br>              leaveTo=&quot;opacity-0&quot;<br>              &gt;<br>                &lt;div className=&quot;fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity&quot;/&gt;<br>             &lt;/Transition.Child&gt;<br>          &lt;/Dialog&gt;<br>        &lt;/Transition.Root&gt;<br>      &lt;/&gt;<br>}</pre><p>Within the same file, nested inside the <em>&lt;Dialog&gt;</em> component, we implement a new <em>&lt;Transition.child&gt;</em> block to manage the animation. The items in the shopping cart, the close button, the checkout button, and other items are now displayed on a new dialog panel called <em>&lt;Dialog.Panel&gt;</em>.</p><pre>&lt;div className=&quot;fixed inset-0 overflow-hidden&quot;&gt;<br>    &lt;div className=&quot;absolute inset-0 overflow-hidden&quot;&gt;<br>        &lt;div className=&quot;pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10&quot;&gt;<br>            &lt;Transition.Child <br>              as={Fragment} <br>              enter=&quot;transform transition ease-in-out duration-500 sm:duration-700&quot; <br>              enterFrom=&quot;translate-x-full&quot; <br>              enterTo=&quot;translate-x-0&quot; <br>              leave=&quot;transform transition ease-in-out duration-500 sm:duration-700&quot; <br>              leaveFrom=&quot;translate-x-0&quot; <br>              leaveTo=&quot;translate-x-full&quot;&gt;<br>                &lt;Dialog.Panel className=&quot;pointer-events-auto w-screen max-w-md&quot;&gt;<br>                    &lt;div className=&quot;flex h-full flex-col overflow-y-scroll bg-white shadow-xl&quot;&gt;<br>                        &lt;div className=&quot;flex-1 overflow-y-auto px-4 py-6 sm:px-6&quot;&gt;<br>                            &lt;div className=&quot;flex items-start justify-between&quot;&gt;<br>                                &lt;Dialog.Title className=&quot;text-lg font-medium text-gray-900&quot;&gt;<br>                                  Shopping cart <br>                                &lt;/Dialog.Title&gt;<br>                                &lt;div className=&quot;ml-3 flex h-7 items-center&quot;&gt;<br>                                    &lt;button type=&quot;button&quot; className=&quot;relative -m-2 p-2 text-gray-400 hover:text-gray-500&quot; <br>                                      onClick={()=&gt; setOpenCart(false)}&gt; <br>                                        &lt;span className=&quot;absolute -inset-0.5&quot; /&gt;<br>                                        &lt;span className=&quot;sr-only&quot;&gt;Close panel&lt;/span&gt;<br>                                        &lt;XMarkIcon className=&quot;h-6 w-6&quot; aria-hidden=&quot;true&quot; /&gt;<br>                                    &lt;/button&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;mt-8&quot;&gt;<br>                                &lt;div className=&quot;flow-root&quot;&gt;<br>                                    &lt;ul role=&quot;list&quot; className=&quot;grid grid-cols-1 divide-y divide-gray-200&quot;&gt;<br>                                      {/* Items*/} <br>                                    &lt;/ul&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                        &lt;div className=&quot;border-t border-gray-200 px-4 py-6 sm:px-6&quot;&gt;<br>                            &lt;div className=&quot;flex justify-between text-base font-medium text-gray-900&quot;&gt;<br>                                &lt;p&gt;Subtotal&lt;/p&gt;<br>                                &lt;p&gt;$262.00&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;p className=&quot;mt-0.5 text-sm text-gray-500&quot;&gt;Shipping and taxes calculated at checkout.&lt;/p&gt;<br>                            &lt;div className=&quot;mt-6&quot;&gt;<br>                                &lt;a href=&quot;#&quot; <br>                                  className=&quot;flex items-center justify-center rounded-md border border-transparent bg-sky-900 px-6 py-3 text-base font-medium text-white shadow-sm hover:bg-sky-700&quot;&gt; <br>                                  Checkout <br>                                &lt;/a&gt;<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;mt-6 flex justify-center text-center text-sm text-gray-500&quot;&gt;<br>                                &lt;p&gt; or <br>                                  &lt;button <br>                                    type=&quot;button&quot; <br>                                    className=&quot;font-medium text-sky-900 hover:text-sky-700 px-2&quot; <br>                                    onClick={()=&gt; setOpenCart(false)}&gt; <br>                                      Continue Shopping &lt;span aria-hidden=&quot;true&quot;&gt; &amp;rarr;&lt;/span&gt;<br>                                   &lt;/button&gt;<br>                                &lt;/p&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/Dialog.Panel&gt;<br>            &lt;/Transition.Child&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>This is how our project should look at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7X8q7nZS7Pk8kqfPhvHQeg.gif" /></figure><p>Now we need to implement the functionality for the “Add To Cart” button and ensure that our products are displayed properly during the cart transition. As previously explained, our shopping cart will have a state and will be properly handled by the use-shopping-cart library. This library will ensure that the correct information is sent to our Stripe Checkout. Now, go ahead with use-shopping-cart installation.</p><pre>npm install --save use-shopping-cart</pre><p>Let’s add a new component to the route <em>components/provider/index.tsx.</em> You must provide your Stripe Publishable Key, which can be found in the developers part of your Stripe dashboard, to use this in our cart provider. We will use</p><p>⚠️ It’s always a good practice to activate and use the test mode for local development. ⚠️</p><pre>&#39;use client&#39;<br><br>import React from &#39;react&#39;<br>import {CartProvider as USCProvider} from &#39;use-shopping-cart&#39;<br><br>type Props = {<br>    children: React.ReactNode<br>}<br>export default function CartProvider({children}: Props) {<br><br>    return (<br>        &lt;USCProvider<br>            // @ts-ignore<br>            mode=&quot;payment&quot;<br>            cartMode={&quot;checkout-session&quot;}<br>            stripe={process.env.NEXT_PUBLIC_TEST_STRIPE_PUBLISHABLE_KEY as string}<br>            currency={&#39;USD&#39;}<br>            successUrl={&#39;https://example.com/success&#39;}<br>            cancelUrl={&#39;https://example.com/cancel&#39;}<br>            allowedCountries={[&#39;US&#39;, &#39;GB&#39;, &#39;CA&#39;]}<br>            billingAddressCollection={true}<br>        &gt;<br>            {children}<br>        &lt;/USCProvider&gt;<br>    )<br>}</pre><p>Wrap it in our <em>app/layout.tsx</em> file:</p><pre><br>&lt;CartProvider&gt;<br>  &lt;nav className=&quot;relative flex items-center justify-between p-4 lg:px-6 bg-gray-100&quot;&gt;<br>    {...}<br>  &lt;/Suspense&gt;<br>&lt;/CartProvider&gt;</pre><p>Now, let’s return to our AddToCart function. We also want to handle the quantity of things to add to the cart at this point, so we’ll develop a new button to increase or decrease the number of items. We also established a minimum and maximum for quantity, making the minimum in this instance 1 item and the maximum 10 of the same product per cart logically applicable.<br>Next, we will continue with the implementation of the “Add to Cart” button. We will utilize the useShoppingCart hook to manage the cart functionality. This hook will take care of all the cart-related operations. We need to provide the quantity and our single product info to addItem().</p><pre>&#39;use client&#39;;<br><br>import {useState, useTransition} from &quot;react&quot;;<br>import {Product} from &quot;@/types/type&quot;;<br>import {useShoppingCart} from &quot;use-shopping-cart&quot;;<br><br>type Props = {<br>    product: Product<br>}<br>enum Action {<br>    Increment,<br>    Decrement<br>}<br><br>export default function AddToCart({product}: Props) {<br>    const [isPending, startTransition] = useTransition();<br>    const [quantity, setQuantity] = useState(1);<br>    const {addItem} = useShoppingCart();<br><br>    const handleQuantity = (action: Action) =&gt; {<br>        switch (action) {<br>            case Action.Increment:<br>                if (quantity &gt;= 10) return;<br>                setQuantity(quantity + 1)<br>                break;<br>            case Action.Decrement:<br>                if (quantity &lt;= 1) return;<br>                setQuantity(quantity - 1)<br>                break;<br>        }<br>    }<br>    <br>    return (<br>        &lt;&gt;<br>            &lt;div<br>                className=&quot;w-full flex flex-row justify-center border rounded-lg&quot;&gt;<br>                &lt;button<br>                    data-action=&quot;decrement&quot;<br>                    className={<br>                        &#39; h-full w-20 cursor-pointer outline-none py-3&#39;<br>                    }<br>                    onClick={() =&gt; handleQuantity(Action.Decrement)}<br>                    aria-label={`Add one ${product.name} to your cart`}<br>                &gt;<br>                    &lt;span className=&quot;m-auto text-base&quot;&gt;−&lt;/span&gt;<br>                &lt;/button&gt;<br>                &lt;input<br>                    type=&quot;number&quot;<br>                    className=&quot;text-center w-full text-base hover md:text-basecursor-default flex items-center outline-none bg-transparent&quot;<br>                    name=&quot;custom-input-number&quot;<br>                    readOnly<br>                    value={quantity}<br>                &gt;&lt;/input&gt;<br>                &lt;button<br>                    data-action=&quot;increment&quot;<br>                    className=&quot;h-full w-20 cursor-pointer py-3&quot;<br>                    onClick={() =&gt; handleQuantity(Action.Increment)}<br>                    aria-label={`Add one ${product.name} to your cart`}<br>                &gt;<br>                    &lt;span className=&quot;m-auto text-base&quot;&gt;+&lt;/span&gt;<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;button aria-label=&quot;Add item to cart&quot; title=&quot;Add Item to Cart&quot; disabled={isPending}<br>                    className=&#39;w-full border mt-4 py-2 px-8 rounded-lg hover:bg-black hover:text-white&#39;<br>                    onClick={() =&gt; addItem(product, {count: quantity})}&gt;&lt;span&gt;Add To Cart&lt;/span&gt;&lt;/button&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><p>💬 Don&#39;t forget to pass product as props inside ProductCard. 💬</p><p>We are nearly done. Let’s return to our modal component. We are now able to use the useShoppingCart() hook to request items in our cart.</p><pre>const {cartCount, cartDetails} = useShoppingCart();</pre><p>Look for the comment <em>{/* Items*/}</em> inside an unordered list. Let’s implement a conditional rendering in our cart component to display a message when it is empty, and render the list of items when it is not.</p><pre>{cartCount &amp;&amp; cartCount &gt; 0<br>? Object.values(cartDetails ?? {}).map((item) =&gt; (<br>  &lt;CartItem key={item.id} item={item}/&gt;<br>))<br>: &lt;div<br>    className=&quot;mt-20 flex w-full flex-col items-center justify-center overflow-hidden&quot;&gt;<br>    &lt;ShoppingCartIcon className=&quot;h-16&quot;/&gt;<br>    &lt;p className=&quot;mt-6 text-center text-2xl font-bold&quot;&gt;Your cart is empty.&lt;/p&gt;<br>  &lt;/div&gt;<br>}</pre><p>Inside our <em>cart/ </em>directory, create the <em>cart-item.tsx</em> file. To remove each item from the cart, we are putting the handler into action.</p><pre>import {formatCurrencyString, useShoppingCart} from &quot;use-shopping-cart&quot;;<br>import {CartItem} from &quot;@/types/type&quot;;<br>import {XMarkIcon} from &quot;@heroicons/react/24/outline&quot;;<br><br>type Props = {<br>    item: CartItem<br>}<br>export default function CartItem({item}: Props) {<br>    const {name, quantity, price} = item;<br>    const {removeItem} = useShoppingCart();<br><br>    const handleRemoveItem = () =&gt; {<br>        removeItem(item.id);<br>    };<br><br>    return (<br>        &lt;div className=&quot;flex items-center gap-4 py-3&quot;&gt;<br>            &lt;div&gt;<br>                {name} &lt;span className=&quot;text-xs&quot;&gt;({quantity})&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;ml-auto&quot;&gt;<br>                {formatCurrencyString({value: price, currency: &quot;USD&quot;})}<br>            &lt;/div&gt;<br>            &lt;button<br>                onClick={() =&gt; handleRemoveItem()}<br>                className=&quot;hover:bg-emerald-50 transition-colors rounded-full duration-500 p-1&quot;<br>            &gt;<br>                &lt;XMarkIcon className=&quot;h-4 w-4 text-red-500&quot; aria-hidden=&quot;true&quot;/&gt;<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Finally, include a formater in the subtotal.</p><pre> &lt;p&gt;{formatCurrencyString({value: totalPrice || 0, currency: &quot;USD&quot;})}&lt;/p&gt;</pre><p>Our shopping cart functionality is done! 🎉</p><p>For the implementation of transaction functionality using Stripe’s Checkout Mode, stay tuned for the upcoming Part II of this guide. If you want to use a different payment gateway or add more features, you can keep tweaking your code.</p><p>That’s a wrap for today — catch you in <a href="https://medium.com/@santanasparrerdevelopment/integrating-stripe-checkout-mode-with-next-js-13-7fbf1680c600">Part II</a>!</p><h3>Resources</h3><p>Visit my github repository at <a href="https://github.com/saraahso/next-13-shopping-cart">https://github.com/saraahso/next-13-shopping-cart</a> to view the code that was written for this guide.</p><p>Part II: <a href="https://medium.com/@santanasparrerdevelopment/integrating-stripe-checkout-mode-with-next-js-13-7fbf1680c600">https://medium.com/@santanasparrerdevelopment/integrating-stripe-checkout-mode-with-next-js-13-7fbf1680c600</a></p><p><a href="https://vercel.com/blog/introducing-next-js-commerce-2-0">https://vercel.com/blog/introducing-next-js-commerce-2-</a><a href="https://stripe.com/">https://stripe.com/</a><br><a href="https://useshoppingcart.com/">https://useshoppingcart.com/</a><br><a href="https://headlessui.com/">https://headlessui.com/</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b3889ba875" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/creating-a-modal-shopping-cart-with-next-js-13-63b3889ba875">Creating a Modal Shopping Cart with Next.js App Router and Stripe</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating translations from react-intl to next-intl]]></title>
            <link>https://medium.com/@santanasparrerdevelopment/migrating-translations-from-react-intl-to-next-intl-4b9f5c08814b?source=rss-c0840b48621------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9f5c08814b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[<saraahso/>]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 12:02:47 GMT</pubDate>
            <atom:updated>2023-09-03T12:02:47.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Since Next.js’ last version was announced, many of us have been updating our projects. Despite the fact that the app and router can work simultaneously, we don’t want to end up with a little monster, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*ABW-9KwHX90KAsX0PXt5SA.gif" /></figure><p>If you are like me and are curious about what’s new and what’s working best with the last version, you should consider looking at next-intl.</p><h3>Why consider next-intl? 🤔</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Y6I73c1UXLcK35bnj7015g.png" /><figcaption><a href="https://next-intl-docs.vercel.app/">https://next-intl-docs.vercel.app/</a></figcaption></figure><p>As the name suggests, the library is designed to work well with Next.js, especially when it comes to routing.<br>According to BundlePhobia, it is ligther than react-intl. But it doesn’t support AST-based extraction, so for more complex applications, you’ll have to choose your battle, performance x size.<br>But what could be more pleasing than a hooks-only API? Your code will remain neat and tidy with the useTranslations() hook!</p><h3>⚠️⚠️⚠️ But… Heads-up ⚠️⚠️⚠️</h3><p>As of today (September 3, 2023), next-intl is a champ for <em>CLIENT</em> side usage. That’s what we’ll focus on here. There’s also a beta version for the Server Side, but that’s a story for another day.</p><h3>Requirements and basic install</h3><p>Assuming you’ve got a Next.js project ready to go, let’s first install next-intl package</p><pre>npm install next-intl</pre><p>After installing it, it’s time to create our middleware. Place it at the same level as your app/ directory. <br>The library provides a createMiddleware function that allows you to easily set up i18n. This function also sets the link header to inform search engines that the content is available in multiple languages—a significant SEO-friendly advantage.</p><pre>import createMiddleware from &#39;next-intl/middleware&#39;;<br><br>export default createMiddleware({<br>  locales: [&#39;en&#39;, &#39;de&#39;],<br>  defaultLocale: &#39;en&#39;<br>});<br><br>export const config = {<br>  matcher: [&#39;/((?!api|_next|.*\\..*).*)&#39;]<br>};</pre><p>In this file, you’ll configure all the locales supported by your application. You’ll also need to specify a defaultLocale, which will operate without any URL prefix.</p><p>Additionally, you can set a matcher to skip paths that shouldn&#39;t be internationalized.</p><h3>Replacing the Provider</h3><p>While utilizing react-intl, I had already organized my variables in a messages directory within the src folder, following this structure: src/messages/en.json <em>and</em> de.json</p><p>I prefer to keep the JSON structure unchanged to avoid wasting time. If you haven’t already, you might want to use namespaces to organize messages. This will help keep things clean and organized.</p><p>If you were using react-intl, you probably had something like this:</p><pre>&lt;IntlProvider locale={shortLocale} messages={messages}&gt;<br>       &lt;Component {...pageProps} /&gt;<br>   &lt;/IntlProvider&gt;</pre><p>In the new app/ directory approach the provider moves to app/[locale]/layout.</p><pre>import { NextIntlClientProvider } from &#39;next-intl&#39;<br>import { notFound } from &#39;next/navigation&#39;<br><br>interface LocaleLayoutProps {<br>  children: ReactNode<br>  params: { locale: string }<br>}<br><br>export function generateStaticParams() {<br>  return [{ locale: &#39;en&#39; }, { locale: &#39;de&#39; }]<br>}<br><br>export default async function LocaleLayout({ children, params: {locale} }: LocaleLayoutProps) {<br>  let messages<br>  try {<br>    messages = (await import(`../../messages/${locale}.json`)).default<br>  } catch (error) {<br>    console.error(&#39;Failed to load messages:&#39;, error);<br>    notFound()<br>  }<br>  return (<br>    &lt;html lang={locale}&gt;<br>      &lt;body&gt;<br>        &lt;NextIntlClientProvider locale={locale} messages={messages}&gt;<br>          {children}<br>        &lt;/NextIntlClientProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><p>For generating static pages with different locales, we are creating a generateStaticParams() function. <br>A new variable messages is used to import the correct translation file for the current locale. A missing translation file, for example, will display a console log error and redirect to a 404 page (or you can take other action).</p><p>Set the locale and messages properties in the NextIntlClientProvider you wrap your application in.</p><h3>Updating Your Components 🌟</h3><p>We have everything ready, let&#39;s update our components.</p><p>With react-intl you probably had:</p><pre>import { FormattedMessage } from &quot;react-intl&quot;<br><br>export default function ExamplePage() {<br>  return(<br>  &lt;h3&gt;&lt;FormattedMessage id=&quot;prj-contact&quot; defaultMessage=&quot;Contact Us&quot; /&gt;&lt;/h3&gt;<br>  )<br>}</pre><p>Replace that with:</p><pre>&#39;use client&#39;<br>import { useTranslations } from &quot;next-intl&quot;<br><br>export default function ExamplePage() {<br>  const translations = useTranslations()<br><br>  return(<br>    &lt;h3&gt;{translations(&#39;prj-contact&#39;)}&lt;/h3&gt;<br>  )<br>}</pre><h3>Updating Your Navigation 🌟</h3><p>When it comes to navigation, the library has a Link component that wraps next/link and automatically prefixes href with the current locale.</p><pre>import Link from &#39;next-intl/link&#39;;<br> <br>&lt;Link href=&quot;/about&quot;&gt;{translations(&#39;prj-nav-about&#39;)}&lt;/Link&gt;<br>&lt;Link href=&quot;/&quot; locale=&quot;de&quot;&gt;{translations(&#39;prj-nav-switch-german&#39;)}&lt;/Link&gt;<br> </pre><p>And that’s it! Fair and simple, don’t forget to clean up unused libraries. 😉</p><p>If you are interested in exploring next-intl, <a href="https://next-intl-docs.vercel.app/">check their documentation</a>.</p><p>I’ll dive into Server Side Internationalization in upcoming posts. Stay tuned, folks! 📺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9f5c08814b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>