<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aman Vishwakarma</title>
    <description>The latest articles on DEV Community by Aman Vishwakarma (@itsamanvishwakarma).</description>
    <link>https://dev.to/itsamanvishwakarma</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F852079%2Ff2212b10-7b64-4567-b94a-486f4757a5cc.jpg</url>
      <title>DEV Community: Aman Vishwakarma</title>
      <link>https://dev.to/itsamanvishwakarma</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/itsamanvishwakarma"/>
    <language>en</language>
    <item>
      <title>SSR vs CSR with Next.js</title>
      <dc:creator>Aman Vishwakarma</dc:creator>
      <pubDate>Sun, 17 Mar 2024 08:14:36 +0000</pubDate>
      <link>https://dev.to/itsamanvishwakarma/ssr-vs-csr-with-nextjs-1op3</link>
      <guid>https://dev.to/itsamanvishwakarma/ssr-vs-csr-with-nextjs-1op3</guid>
      <description>&lt;p&gt;With modern web development frameworks, the age-old debate around server-side rendering (SSR) and client-side rendering (CSR), which rendering method is more effective, has returned to the general tech community. Since Appwrite aims to enable all developers, regardless of their preferences, in this debate, we decided to research and extend our support for both paradigms. This article will explore the differences between SSR and CSR and how Appwrite Authentication can be leveraged with both in Next.js.&lt;/p&gt;

&lt;h2&gt;
  
  
  How server-side and client-side rendering differ
&lt;/h2&gt;

&lt;p&gt;Before we jump further into this article, it is necessary to understand what SSR and CSR are. &lt;strong&gt;Server-side rendering&lt;/strong&gt; allows the content of a web page to be generated on the server rather than in the browser. In &lt;strong&gt;client-side rendering&lt;/strong&gt;, the rendering of a web page is performed in the client's browser. Unlike SSR, where the server generates the full page's HTML for each request, in CSR, the server sends a minimal HTML document with a JavaScript bundle to the client. The browser executes the JavaScript, which typically fetches data from the server and generates the HTML content dynamically on the client.&lt;/p&gt;

&lt;p&gt;Here are some of the strengths and drawbacks of both methods:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;SSR&lt;/th&gt;
&lt;th&gt;CSR&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Rendering location&lt;/td&gt;
&lt;td&gt;The HTML is fully rendered on the server, and a complete page is sent to the client.&lt;/td&gt;
&lt;td&gt;The browser receives minimal HTML, and JavaScript renders the content on the client-side.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Initial load time&lt;/td&gt;
&lt;td&gt;Generally offers faster initial page load times because the browser can display the page as soon as it receives the HTML.&lt;/td&gt;
&lt;td&gt;May have slower initial load times since the browser needs to load, parse, and execute JavaScript before rendering the content.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SEO Optimization&lt;/td&gt;
&lt;td&gt;More SEO-friendly as search engines can crawl the fully rendered HTML content.&lt;/td&gt;
&lt;td&gt;Less SEO-friendly out of the box since search engines might struggle to index content that is rendered asynchronously via JavaScript.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Resource utilization&lt;/td&gt;
&lt;td&gt;Increases the load on the server since it has to render content for each request.&lt;/td&gt;
&lt;td&gt;Offloads rendering to the client, reducing server load but increasing the client's processing requirements.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;User experience&lt;/td&gt;
&lt;td&gt;Can provide a better initial user experience with faster-perceived load times.&lt;/td&gt;
&lt;td&gt;Might enhance the user experience in dynamic applications with smooth transitions and interactions after the initial load.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Development Complexity&lt;/td&gt;
&lt;td&gt;Can be more complex to implement, especially for highly dynamic sites, due to the need for server infrastructure and handling of the initial rendering.&lt;/td&gt;
&lt;td&gt;Simplifies initial development since the rendering is handled in the browser, but managing state and interactivity can become complex.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Caching&lt;/td&gt;
&lt;td&gt;Easier to cache at the server level or through a CDN as the content is static and pre-rendered.&lt;/td&gt;
&lt;td&gt;Caching strategies can be more complex due to dynamic content rendering, often requiring sophisticated service worker setups.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Data fetching&lt;/td&gt;
&lt;td&gt;The server pre-fetches data before rendering the page, which can improve performance for the initial load.&lt;/td&gt;
&lt;td&gt;Data is fetched on the client-side, which can delay content rendering until after the data is retrieved.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Understanding auth patterns for CSR and SSR in Next.js
&lt;/h2&gt;

&lt;p&gt;When it comes to implementing authentication in Next.js, Appwrite supports different authentication patterns between SSR and CSR apps. The key difference is in how Appwrite handles a user's session secret. Let's explore both patterns to understand how they are supposed to be implemented.&lt;/p&gt;

&lt;h3&gt;
  
  
  CSR authentication pattern
&lt;/h3&gt;

&lt;p&gt;With single page applications (SPAs) that are rendered on the client-side, the Appwrite web SDK handles the session for us, so we never need to manually access it. After creating a user session with account.createEmailPasswordSession (or any other authentication method Appwrite offers), we can directly retrieve the current user with account.get() and process any other authentication checks or move forward to our main app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;account.createEmailPasswordSession('[email]', '[password]')
const user = await account.get()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  SSR authentication pattern
&lt;/h3&gt;

&lt;p&gt;With SSR apps, we need a way to access the session secret after creation to set a session cookie on the server and then return to the client's browser (the Web SDK cannot achieve this by default). Therefore, with SSR, we must manually handle how we set the session after creation and retrieve it on subsequent requests.&lt;/p&gt;

&lt;p&gt;For this purpose, we rely on Appwrite's server SDKs for Next.js apps, we use our Node.js SDK. The first step of this process is installing the node-appwrite NPM package.&lt;/p&gt;

&lt;h3&gt;
  
  
  Admin and Session clients
&lt;/h3&gt;

&lt;p&gt;The first step of understanding how we initialize the client in SSR apps. In this scenario, we need to create two types of Appwrite clients:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Admin client: performs admin requests using an API key.&lt;/li&gt;
&lt;li&gt;Session client: performs authenticated requests on behalf of a user.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Generating a session secret
&lt;/h3&gt;

&lt;p&gt;The admin client must be set with an API key that has the necessary scopes in order to perform all necessary tasks on your Appwrite project. For example, we need an admin client to create a session, and this client must have an API key with the auth scope session.write, enabled at the very least.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const adminClient = new Client()
  .setEndpoint('https://cloud.appwrite.io/v1')
  .setProject('&amp;lt;PROJECT_ID&amp;gt;')
  .setKey('&amp;lt;API_KEY&amp;gt;')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We set this session in the response cookies of a server action or an API route (we'll use the latter for our examples).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { cookies } from 'next/headers'

export async function POST(request) {
    // initiate an admin client and account here
    // ...

    const { email, password } = await request.json()
    const session = await account.createEmailPasswordSession(email, password)

    cookies().set('my-session-cookie', session.secret)

    return Response.redirect('/api/user')
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Using session secrets
&lt;/h3&gt;

&lt;p&gt;The session client accepts the generated session secret and sets it using the client.setSession method. This session secret will typically be retrieved from a session cookie.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sessionClient = new Client()
    .setEndpoint('https://cloud.appwrite.io/v1')
    .setProject('&amp;lt;PROJECT_ID&amp;gt;')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use the session secret to authenticate a user from an API route. This can also be done at the page component level.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function GET(request){
    // initiate a session client and account here
    // ...

    const session = request.cookies.get('my-session-cookie')
    if (session) {
        client.setSession(session.value)
    }

    try {
        const user = await account.get()
        return Response.json(user)
    } catch(error){
        return Response.json(error)
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
&lt;a href="https://dev.tourl"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How To: Dynamic Routing in Next.js</title>
      <dc:creator>Aman Vishwakarma</dc:creator>
      <pubDate>Sat, 16 Mar 2024 11:20:14 +0000</pubDate>
      <link>https://dev.to/itsamanvishwakarma/how-to-dynamic-routing-in-nextjs-32ga</link>
      <guid>https://dev.to/itsamanvishwakarma/how-to-dynamic-routing-in-nextjs-32ga</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In the dynamic world of web development, developing flexible and scalable applications is critical. One of the most important components of achieving this flexibility is learning to use dynamic routes. This article will explore the domain of Next.js' dynamic routing, elucidating its meaning and providing a comprehensive guide to assist you in using its potential.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Building web applications that can adapt to changing requirements requires dynamic routes. They enable developers to design pages with changeable paths, which makes applications more scalable and flexible. This flexibility provides a solid base for creating dynamic web applications.&lt;/p&gt;

&lt;p&gt;To better understand dynamic routes, we will build a web app that displays a list of products. When a user navigates to the &lt;code&gt;/products&lt;/code&gt; &lt;code&gt;URL&lt;/code&gt; path, we should display a list of all the products. However, if the user navigates to &lt;code&gt;/products/productID/&lt;/code&gt;, we should display details about a specific product.&lt;/p&gt;

&lt;p&gt;For instance, navigating to &lt;code&gt;/products/1&lt;/code&gt; should display details about the product with ID as “1”, navigating to &lt;code&gt;products/23&lt;/code&gt; should display details of the product with ID as “23”, and so on. Let’s explore how to do this with Next.js dynamic routes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Dynamic Routes in Next.Js
&lt;/h2&gt;

&lt;p&gt;Understanding how to construct dynamic routes in &lt;code&gt;Next.js&lt;/code&gt; is crucial to fully utilize their potential. You can create dynamic routes by following the simple steps in this section. We’ll also look at the file name convention that &lt;code&gt;Next.js&lt;/code&gt; needs to properly identify and manage dynamic routes.&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;Next.js&lt;/code&gt; web app using the following command. At the time of writing this article, the current version is &lt;code&gt;Next.js V 14.0.4&lt;/code&gt;. If you are using a later version, please check if there are changes in the &lt;a href="https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"&gt;Next.Js Docs&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When installing &lt;code&gt;Next.js&lt;/code&gt;, leave everything as default by clicking enter for every prompt. &lt;code&gt;Next.js&lt;/code&gt; comes packaged with &lt;code&gt;TypeScript&lt;/code&gt;, &lt;code&gt;ESLint&lt;/code&gt;, and &lt;code&gt;Tailwind CSS&lt;/code&gt; configuration by default.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;app&lt;/code&gt; directory, create a new folder and name it &lt;code&gt;products&lt;/code&gt;. Create a file &lt;code&gt;page.tsx&lt;/code&gt; in the’ products’ folder. This file will contain the list of products to be displayed and the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

const ProductsList = () =&amp;gt; {
return (
    &amp;lt;div className="flex justify-center items-center"&amp;gt;
      &amp;lt;div className="bg-slate-500 w-96 text-center my-20 p-10"&amp;gt;
        &amp;lt;h1 className="text-xl"&amp;gt;Products List&amp;lt;/h1&amp;gt;
        &amp;lt;hr /&amp;gt;
        &amp;lt;ul&amp;gt;
          &amp;lt;li&amp;gt;Product 1&amp;lt;/li&amp;gt;
          &amp;lt;li&amp;gt;Product 2&amp;lt;/li&amp;gt;
          &amp;lt;li&amp;gt;Product 3&amp;lt;/li&amp;gt;
          &amp;lt;p&amp;gt;.&amp;lt;/p&amp;gt;
          &amp;lt;p&amp;gt;.&amp;lt;/p&amp;gt;
          &amp;lt;p&amp;gt;.&amp;lt;/p&amp;gt;
          &amp;lt;li&amp;gt;Product n&amp;lt;/li&amp;gt;
        &amp;lt;/ul&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ProductsList;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code simply displays a list of products. So when a user navigates to &lt;code&gt;/products&lt;/code&gt;, a product list should be displayed below. The list can contain any number of products.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frz1jn2nioiyoussp98rw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frz1jn2nioiyoussp98rw.png" alt="Image description" width="537" height="427"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The objective is to allow the user to navigate to a page that gives more details for each product in the list. An approach that can be taken is using &lt;a href="https://nextjs.org/docs/getting-started/project-structure#nested-routes"&gt;nested routes&lt;/a&gt;. This is achieved by creating five separate folders in the &lt;code&gt;products&lt;/code&gt; directory for each product in the list.&lt;/p&gt;

&lt;p&gt;The file structure in such a case will look as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; products
   &amp;gt; 1
      - page.tsx
   &amp;gt; 2
      - page.tsx
   &amp;gt; 3
      - page.tsx
   .
   .
   .

   &amp;gt; n
      - page.tsx
 -page.tsx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can observe, this approach is not a viable solution. Take a broader view and assume that the list has one hundred products. Creating separate folders for each one hundred product will be a hassle. The correct approach is to use a dynamic route segment.&lt;/p&gt;

&lt;h3&gt;
  
  
  How do we create a dynamic route in Next.js?
&lt;/h3&gt;

&lt;p&gt;Create a folder in the &lt;code&gt;products&lt;/code&gt; directory to create a dynamic route. The folder name should be enclosed with square brackets.&lt;/p&gt;

&lt;p&gt;The folder can be named however you want, according to the context of your web app. In this case, name the folder &lt;code&gt;productID&lt;/code&gt; so the format of the folder name will be &lt;code&gt;[productID]&lt;/code&gt;. This is the naming convention of dynamic routes in &lt;code&gt;Next.js&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is what your file structure looks like when using dynamic segments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; products
  &amp;gt;[productID]
    -page.tsx
 -page.tsx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Compare this file structure with the previous one and notice how this one is clear and less complicated.&lt;/p&gt;

&lt;h2&gt;
  
  
  Working With Dynamic Parameters
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Next.js&lt;/code&gt; applications gain additional liveliness via dynamic parameters. It is necessary to comprehend these elements to develop applications that can adapt to various user inputs.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Next.js&lt;/code&gt; treats square brackets in a folder name as a dynamic segment, enabling us to create dynamic routes. Whatever name you use as the folder name is the dynamic parameter.&lt;/p&gt;

&lt;p&gt;By convention, the dynamic folder names are named according to the context of your application. If, for instance, the web app consists of blogs, you may name it &lt;code&gt;[blogID]&lt;/code&gt; etc.&lt;/p&gt;

&lt;p&gt;In our scenario, the &lt;code&gt;productID&lt;/code&gt;, which can be any number, should be a dynamic value that maps to a specific product in the list.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;[productID]&lt;/code&gt; folder, create a new file &lt;code&gt;page.tsx&lt;/code&gt;. This file is where we will have the logic to display the details of each product when a user navigates to the specific product through its ID.&lt;/p&gt;

&lt;h2&gt;
  
  
  Utilizing Route Parameters in Next.js
&lt;/h2&gt;

&lt;p&gt;To utilize the &lt;code&gt;route parameters&lt;/code&gt; from the &lt;code&gt;URL&lt;/code&gt; path, we will write the following code on the &lt;code&gt;page.tsx&lt;/code&gt; file we just created in the &lt;code&gt;[productID]&lt;/code&gt; folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

const ProductDetails = ({ params }: { params: { productID: string } }) =&amp;gt; {
const { productID } = params;
return (
    &amp;lt;div className="bg-slate-500 w-96 text-center my-20 p-10 mx-20"&amp;gt;
      &amp;lt;h1&amp;gt;
        The Product ID is &amp;lt;b&amp;gt;{productID}&amp;lt;/b&amp;gt;
      &amp;lt;/h1&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ProductDetails;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;ProductDetails&lt;/code&gt; component takes a single prop named &lt;code&gt;params&lt;/code&gt;. This prop is anticipated to be an object with a property &lt;code&gt;productID&lt;/code&gt; of type string, so we add that as the type to avoid a red squiggly from &lt;code&gt;Typescript&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Inside the component, it destructures the &lt;code&gt;productID&lt;/code&gt; from the &lt;code&gt;params&lt;/code&gt; object. The extracted &lt;code&gt;productID&lt;/code&gt; is then used in the component’s return statement to dynamically display product details. Note that the extracted &lt;code&gt;productID&lt;/code&gt; is named exactly as the dynamic folder &lt;code&gt;[productID]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Simply, this component receives a &lt;code&gt;params&lt;/code&gt; object containing a &lt;code&gt;productID&lt;/code&gt; and renders a message indicating the ID of the specified product. For example, if &lt;code&gt;params.productID&lt;/code&gt; is “13”, the component displays “The product ID is 13”.&lt;/p&gt;

&lt;p&gt;The following are examples of how the ID of the products will be displayed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fas02j0uywa7mky4pe1d7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fas02j0uywa7mky4pe1d7.png" alt="Image description" width="457" height="323"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Navigating to &lt;code&gt;products/63&lt;/code&gt; displays the Id as “63”, while navigating to &lt;code&gt;products/136&lt;/code&gt; displays the Id as “136”.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz20j1l7vtzvf7p8z3vor.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz20j1l7vtzvf7p8z3vor.png" alt="Image description" width="457" height="323"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The above examples demonstrate how dynamic parameters function. In the next section, we will use this understanding to display actual product details, similar to the manner used in a standard application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dynamic Routes and Data Fetching
&lt;/h2&gt;

&lt;p&gt;A dynamic route can only be as effective as the data it can use. In our previous scenario, we kept it simple by displaying the product in the browser.&lt;/p&gt;

&lt;p&gt;In this section, I demonstrate the amazing possibilities of dynamic routes in &lt;code&gt;Next.js&lt;/code&gt; by illustrating how they can be connected with &lt;code&gt;API&lt;/code&gt; calls to retrieve specific product data using unique IDs.&lt;/p&gt;

&lt;p&gt;Using a dynamic route, I connect to a mock &lt;code&gt;API&lt;/code&gt; created for testing. This presentation demonstrates the ease of using dynamic parameters to display relevant product information within a &lt;code&gt;Next.js&lt;/code&gt; application.&lt;/p&gt;

&lt;p&gt;Write the following code in the &lt;code&gt;page.tsx&lt;/code&gt; file of the &lt;code&gt;[productID]&lt;/code&gt; folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import React, { useEffect, useState } from "react";

interface Product {
id: number;
title: string;
description: string;
}

const ProductDetails = ({ params }: { params: { productID: string } }) =&amp;gt; {
const { productID } = params;
const [product, setProduct] = useState&amp;lt;Product | null&amp;gt;(null);

//Fetch details for the specified productID
const fetchProductDetails = async () =&amp;gt; {
try {
const response = await fetch(
`https://dummyjson.com/products/${productID}`
      );
const data = await response.json();
setProduct(data);
    } catch (error) {
      console.log(error, "error while fetching data");
    }
  };

useEffect(() =&amp;gt; {
fetchProductDetails();
  }, [productID]);

if (!product) {
return (
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;Product Not Found&amp;lt;/h2&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }

return (
    &amp;lt;div className="bg-slate-500 w-96 text-center my-20 p-10 mx-20"&amp;gt;
      &amp;lt;h1&amp;gt;
        &amp;lt;b&amp;gt;Product Details of :&amp;lt;/b&amp;gt; {product.title}
      &amp;lt;/h1&amp;gt;
      &amp;lt;hr /&amp;gt;
      &amp;lt;br /&amp;gt;
      &amp;lt;h2&amp;gt;
        &amp;lt;b&amp;gt;Product ID&amp;lt;/b&amp;gt; : {product.id}
      &amp;lt;/h2&amp;gt;
      &amp;lt;br /&amp;gt;
      &amp;lt;h2&amp;gt;
        &amp;lt;b&amp;gt;product name :&amp;lt;/b&amp;gt; {product.title}
      &amp;lt;/h2&amp;gt;
      &amp;lt;br /&amp;gt;
      &amp;lt;h2&amp;gt;
        &amp;lt;b&amp;gt;Product description : &amp;lt;/b&amp;gt;
{product.description}
      &amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ProductDetails;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code snippet demonstrates the utilization of dynamic routes in a &lt;code&gt;Next.js&lt;/code&gt; application to fetch and display product details based on a specific product ID. The &lt;code&gt;ProductDetails&lt;/code&gt; component receives the product ID as a parameter by destructuring the &lt;code&gt;params prop&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The component uses the &lt;code&gt;useState hook&lt;/code&gt; to manage the &lt;code&gt;state&lt;/code&gt; of the retrieved product data, initially set to &lt;code&gt;null&lt;/code&gt;. The &lt;code&gt;useEffect hook&lt;/code&gt; triggers the &lt;code&gt;asynchronous&lt;/code&gt; &lt;code&gt;fetchProductDetails&lt;/code&gt; function upon mounting or when the product ID changes.&lt;/p&gt;

&lt;p&gt;This function makes an &lt;code&gt;API&lt;/code&gt; call to a mock endpoint - (&lt;a href="https://dummyjson.com/products/$%7BproductID%7D"&gt;https://dummyjson.com/products/${productID}&lt;/a&gt;), retrieves the product data, and updates the &lt;code&gt;state&lt;/code&gt;. The component then conditionally renders either a “Product Not Found” message or a structured layout containing the product details, such as the product ID, name, and description.&lt;/p&gt;

&lt;p&gt;The screenshots below show the &lt;code&gt;productDetails&lt;/code&gt; page, showcasing how the code integrates dynamic routing and &lt;code&gt;API&lt;/code&gt; calls.&lt;/p&gt;

&lt;p&gt;Example 1 (product ID = 34)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7a8hbrhnpb0xg0z4kmyy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7a8hbrhnpb0xg0z4kmyy.png" alt="Image description" width="487" height="486"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Example 2 (product ID = 93)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2d5xiy7aa1y35kpeh4ub.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2d5xiy7aa1y35kpeh4ub.png" alt="Image description" width="487" height="527"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These examples vividly demonstrate the power of dynamic routes when combined with &lt;code&gt;API&lt;/code&gt; calls, displaying specific product details according to the ID provided.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advanced Dynamic Routing in Next.Js
&lt;/h2&gt;

&lt;p&gt;In addition to the dynamic parameters we’ve previously explored, &lt;code&gt;Next.js&lt;/code&gt; offers powerful tools for handling various segments in your &lt;code&gt;URLs&lt;/code&gt;. They consist of:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Catch-All Segments&lt;/li&gt;
&lt;li&gt;Optional Catch-All Segments&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Catch-All Segments
&lt;/h3&gt;

&lt;p&gt;With Catch-All Segments you can create routes that match any number of dynamic segments, providing a flexible solution for unpredictable &lt;code&gt;URL&lt;/code&gt; structures. The beauty lies in the simplicity of the syntax. Denoted by three dots (&lt;code&gt;...&lt;/code&gt;) followed by the parameter name in square brackets (&lt;code&gt;[...parameterName]&lt;/code&gt;), this combination empowers developers to capture a variable number of segments effortlessly.&lt;/p&gt;

&lt;p&gt;Suppose you have a page with the following dynamic route, &lt;code&gt;/products/[...categories]&lt;/code&gt;. Whether a user navigates to &lt;code&gt;/products/electronics&lt;/code&gt;, &lt;code&gt;/products/electronics/laptops&lt;/code&gt;, &lt;code&gt;/products/electronics/laptops/hp&lt;/code&gt;, or even &lt;code&gt;/products/clothing/shoes/sneakers&lt;/code&gt;, Catch-All Segments dynamically capture and adapt to the varying depth of the nested categories.&lt;/p&gt;

&lt;h3&gt;
  
  
  Optional Catch-All Segments
&lt;/h3&gt;

&lt;p&gt;With this syntax, parameters enclosed in double square brackets (&lt;code&gt;[[...parameterName]]&lt;/code&gt;), become optional, allowing routes to accommodate both the presence and absence of the parameter.&lt;/p&gt;

&lt;p&gt;Consider the dynamic route &lt;code&gt;/products/[[...categories]]&lt;/code&gt;. In this scenario, a user may navigate to &lt;code&gt;/products/categories&lt;/code&gt;, &lt;code&gt;/products/categories/phones&lt;/code&gt;, &lt;code&gt;/products/clothing&lt;/code&gt;, or even &lt;code&gt;/products&lt;/code&gt; (without any nested route).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;categories&lt;/code&gt; parameter is optional. Users may provide one, multiple, or no categories at all, and the Optional Catch-All Segments will offer a solution for diverse routing needs.&lt;/p&gt;

&lt;p&gt;The difference between Catch-All and Optional Catch-All Segments is that with optional, the route without the parameter is also matched (&lt;code&gt;/products&lt;/code&gt; in the example above).&lt;/p&gt;

&lt;p&gt;Your &lt;code&gt;Next.js&lt;/code&gt; dynamic routing toolkit becomes much more versatile when you include Catch-All and Optional Catch-All Segments. This lets you build web apps that can smoothly adapt to the unpredictable nature of user inputs and dynamic paths.&lt;/p&gt;

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

&lt;p&gt;In conclusion, mastering dynamic routes brings paramount benefits to the world of web development. Throughout this article, we’ve explored the significance of dynamic routes, such as enhancing flexibility in web development.&lt;/p&gt;

&lt;p&gt;We’ve created dynamic routes from scratch and explored how to extract dynamic parameters from the dynamic routes and use them to fetch data from an &lt;code&gt;API&lt;/code&gt; endpoint. We’ve also touched on advanced features like Catch-All and Optional Catch-All Segments.&lt;/p&gt;

&lt;p&gt;As you explore &lt;code&gt;Next.js&lt;/code&gt; dynamic routes’ capabilities and adaptability, I urge you to implement them in your applications. Dynamic routes are not merely a feature, but a fundamental change in the way we approach web development. I appreciate you taking the time to learn about the aspects of &lt;code&gt;Next.js'&lt;/code&gt; dynamic routes. Happy coding!&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
