Exploring nested dynamic folder routing in Next.js

Update:

  1. Why is this error occurring due to [category_slug]-index.js using getServerSideProps?
  2. I attempted creating an index.js under the product folder, and it seems to work fine with [category_slug] using getServerSideProps, am I correct?

This is how my folder structure looks like

pages
   |-categories
       |-[category_slug]
           |-index.js     
           |-product
               |-[product_slug].js       

An error occurs when I navigate to [product_slug]. It displays:

Error: A required parameter (category_slug) was not provided as a string in getStaticPaths for /categories/[category_slug]/product/[product_slug]

Is it possible to have nested routing folders in Next.js? I couldn't find any information on this.

Here's the code snippet for reference

// [product_slug].js

export async function getStaticProps({ params: { product_slug } }) {
  const product_res = await fetch(
    `${API_URL}/products/?product_slug=${product_slug}`
  ); 
  const found = await product_res.json();

  return {
    props: {
      product: found[0],
    }
  };
}

export async function getStaticPaths() {
  // Retrieve all possible paths
  const products_res = await fetch(`${API_URL}/products/`);
  const products = await products_res.json();

  return {
    paths: products.map((product) => ({
          params: { product_slug: product.product_slug },
        }),
    fallback: false, 
  };
}

I experimented with providing a hardcoded value to [category_slug]. Is this the correct approach or not? The documentation doesn't clarify on this matter.

export async function getStaticProps({ params: { product_slug } }) {
  const product_res = await fetch(
    `${API_URL}/products/?product_slug=orange_juice`
  ); 

  const found = await product_res.json();

  return {
    props: {
      product: found[0],
    },
  };
}

export async function getStaticPaths() {
  // Retrieve all possible paths
  const products_res = await fetch(`${API_URL}/products/`);
  const products = await products_res.json();

  return {
    paths: [
      {
        params: {
          product_slug:
            "categories/orange/product/orange_juice",
        },
      },
    ],
    fallback: false,
  };
}

Can someone guide on the correct method to input the first dynamic path in [product_slug] dynamic route?

Answer №1

In accordance with @ckoala's suggestion, the key is to obtain the potential category_slugs within your [product_slug]'s getStaticPaths.

Considering your routing structure, it seems that each product is associated with a specific category. As a result, you would need to retrieve all products for every category in the getStaticPaths.

// categories/[category_slug]/product/[product_slug].js

export async function getStaticPaths() {
    // Implement your logic to fetch all products by category

    return {
        paths: [
            // There will be an entry like this for each category/product combination:
            {
                params: {
                    category_slug: 'orange'
                    product_slug: 'orange_juice',
                }
            }
        ],
        fallback: false
  };
}

Subsequently, your getStaticProps should expect the additional category_slug parameter.

export async function getStaticProps({ params: { category_slug, product_slug } }) {
    // Include logic to fetch a single product based on `category_slug`, and/or `product_slug`

    return {
        props: {
            product
        }
    };
}

With the example utilized in getStaticPaths, you can access the following path:

/categories/orange/product/orange_juice
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to align the ul, li, and span elements in a single row?

To display the 'previous' on the left side of the list item and the 'next' on the right side, aligned in a single line, how can this layout be achieved? <ul style= 'list-style-type: none;' class="filter1"> <li&g ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

Encountering a syntax/parse error while utilizing jQuery within Velocity code

<script type="text/javascript> (function($, win) { function myCustomInit () { var self = this; var options = { 'params' : "userId=" + userId; }; self.init = function() { self.initButtonAction(); }; ...

The AngularJS ng-if directive functions on a variable will only function on the

I'm currently working on updating an old codebase that was written in AngularJS, a framework I am not very familiar with. My task is to implement a spinner that appears when an HTTP request is sent and disappears once the response is received. The sp ...

Having trouble displaying form in a different view, form is not appearing as expected

I am facing an issue with rendering a form inside a modal. The form is being rendered but the form_for does not show up, only the inputs are visible. This prevents me from targeting the submit button, which I need for ajax functionality. My file path: Adg ...

Stop the page from scrolling when the mouse hovers over the scene in Firefox

I have a three.js application embedded within a div on a webpage. The issue I am facing is that when using the OrbitControls.js for zooming with the mouse wheel, it also scrolls the entire page. To overcome this, I need to prevent scrolling when the mouse ...

How can I retrieve the total number of records (count) in an XML response using PostMan?

Hello, I'm currently attempting to determine the length of an XML response but I'm running into some issues. The error message I am encountering is as follows: "There was an error in evaluating the test script: ReferenceError: xml2json is not def ...

Performing string replacement on an Ajax response prior to adding it to the document

I'm facing an issue when trying to update the response from a jQuery ajax request. I need to replace myPage.aspx with /myfolder/myPage.aspx before adding it to the DOM. Is it possible to achieve this using jQuery or plain Javascript? This is how a pa ...

Encountered a VUE error stating "Cannot use 'in' operator to search for 'path' in undefined". This issue led to an infinite loop, prompting me to search for solutions on StackOverflow and other similar forums. More details can be found

I am currently using this demo for learning purposes. If you want to see the full code, you can visit my GitHub repository here: https://github.com/tNhanDerivative/nhanStore_frontEnd and access my domain: vuestore.nhan-thenoobmaster.com. The error I am exp ...

Angular directive for automatically selecting a <select> value when there is only one option available in ngOptions

How can I create a directive that automatically preselects an option if only one item is available in the ngOptions scope? Currently, my code looks like this: <select id="provider" name="provider" class="form-control" ng-model="foo.provider" ...

Configuring Cache-Control Header in Next.js App Routing

I've been struggling to figure this out. I'm working with the latest version of NextJS 13 and trying to use the new App Router feature. Despite my attempts in setting the response Cache-Control header through middleware.ts, it seems that the chan ...

Starting a Nextjs application with the NewRelic agent: A step-by-step guide

I recently set up the Newrelic agent for my Nextjs application. Here are the steps I have taken so far: npm install @newrelic/next After installation, I copied the newrelic.js file to the root folder and added my license key and app name to it. Furtherm ...

Create a datastring using a JSON object

When receiving data in JSON format from an AJAX call, the following code is used to parse it: var parsed=JSON.parse(data); An example output could look like this: {"confirm_type":"contract_action","job_id":12,"id":7} To generate a dynamic data string f ...

How can I transfer information from Node.js to Vue in an Nuxt.js server-side rendering setup?

I need to find a way to pass Firestore data to Vue files from Node.js (Express) because I have to utilize Firestore's getCollections() method, which cannot be executed on the client side. I have set up nuxt-ssr for deploying Google Cloud Functions an ...

What is the reason for having to add my IP to the white-list daily?

As a beginner, I am delving into the world of back-end development with Node.js, Express.js, and Mongoose for educational purposes. My database is hosted on Atlas-Mongo DB. Initially, everything seemed to be running smoothly as I configured it with the fre ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

Building a versatile component library for Next.js using TypeScript and Tailwind CSS: Step-by-step guide

Lately, I've been utilizing Next.js and crafting components such as buttons, inputs, and cards with Tailwind CSS for my various projects. However, the repetitive task of rewriting these components from scratch for each new project has become quite tir ...

Is it possible to reload the page using Node.js and Express?

In my small Node and Express application, I am looking to automatically refresh the page when a user connects. I attempted using res.redirect('index.html') in a particular section of code, but encountered an error when trying to connect to the ro ...

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

Tips for creating a nested div structure using JavaScript

I am facing an issue with my results object that includes data like Creation_date and approval_date. I have put the results in a loop in JavaScript and created nested divs. However, when I debug it, the divs are not nested as expected. Each one seems to ...