Creating dynamic routes with Nuxt3

Within my nuxt.config.ts file, I have the ability to generate multiple routes using the following code:

export default defineNuxtConfig({
  generate: {
    routes: ['/products/1', '/products/2']
  },
})

After running nuxt generate, this will create a product folder inside my dist directory with subfolders for each product (product 1 and product 2) containing the HTML files.

However, these product routes are accessed via a GET request to an API endpoint, so I need to generate them directly within my pages. In Nuxt 2, we accomplished this by referring to .

generate: {
    routes: ['/products/1', '/products/2']
  }

When attempting this in Nuxt3, my product pages are not being generated. I am uncertain if the 'generated' property is still available and how to achieve the desired outcome. Can you provide any insight on this?

Answer №1

To solve this issue, the solution lies in utilizing nitro, a plugin embedded within nuxtJs 3.

By integrating nitro, we gain the ability to perform asynchronous API calls and define custom routes:

import axios from 'axios'

async function getProductsRoutes() {
  const { data } = await axios.get('https://mydata/api/products/list.json')
  return data.map(product => `/products/${product.id}`)
}

export default defineNuxtConfig({
  devtools: { enabled: true },
  hooks: {
    async 'nitro:config'(nitroConfig) {
      if (nitroConfig.dev) return

      let slugs = await getProductsRoutes();
      nitroConfig.prerender.routes.push(...slugs);
      return
    },
  },
})

Unfortunately, I have not been able to find a direct method to accomplish this on the page itself, especially without being able to pass certain payloads at this time.

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

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

Is there a way to remove specific items from my array in Vue.js?

Essentially, I am using an HTML select element that is populated with arrays of registered users. <label > <b> <i style="opacity:0.8">Users:</i> </b> </label>&nbsp;&nbsp; <select class=&quo ...

Using Bootstrap Select with a callback function

I am currently working with 2 Bootstrap Select dropdowns. One dropdown contains a list of countries, while the other contains a list of states. The country list is static and loads when the page is loaded. On the other hand, the state list is populated dyn ...

Utilize Express.js to seamlessly stream and process uploaded files with formidable and gm, ensuring a streamlined process without

I am looking for a solution to upload and resize an image in one step without having to write to disk twice. For uploading images, I am using: node-formidable: https://github.com/felixge/node-formidable And for resizing the images, I am using: gm: Howev ...

Obtain information in JSP from a JavaScript function that was generated in another JSP file

I have created a code that allows the admin to toggle a user's status between active and inactive using radio buttons. The technologies I have used for this project are JSP, MySQL, and JS. admin.jsp: <tr> <td> ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

I am facing hurdles with firebase permissions as it is not granting me the necessary access

https://i.sstatic.net/oYAdY.png firebase.database().ref('meetups').push(meetup) .then((data)=> { console.log(data) commit('createMeetup', meetup) }) .catch((error ...

How to retrieve attributes of a model from a related model in Sails.js

Currently, I am utilizing the beta version(v0.10.0-rc3) of Sails.js and have updated the database adapter to PostgreSQL in order to enable associations via the Waterline ORM. My main focus is on creating a role-based user model for authorization based on d ...

Ways to determine the specific content type within req.body?

Based on the information found at https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, it is stated that the body of a request can be one of the following types: ArrayBuffer Blob formData JSON text I am wondering if there is a way ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Utilizing Bootstrap and JavaScript features to showcase specific tab data

I am currently designing a universal search page. Users input a search query, and all relevant results are displayed. However, I also want to incorporate tabs that users can click on to filter the results further. Currently, the only tab that is functional ...

Cypress Error: Unable to locate module: Error - Unable to find 'cypress/types/lodash'

I am currently conducting my inaugural test in Cypress directly from the Visual Studio IDE. Everything was running smoothly until I suddenly encountered the error below, without making any changes or updates whatsoever. My Cypress (version 7.0.0) was inst ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

The URL for this page is not within the app's designated domains and will not open Facebook Dialogs (FB UI)

I am currently working on integrating Facebook UI Dialogs into my website. My goal is to add custom actions when users share a post from my site. I have created my app, added the app URL and domain (which is the same as the URL), and included all necessa ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Applying "Max-Height" property to the cells of a kendo

I've been struggling to figure out how to set a max-height for a tr or td element within a Kendo grid. Is it possible to set the height to 100% and restrict the max-height to 200px? The grid itself is scrollable with a height of 500px, so the scrollin ...

Save the outcome of the apollo query in a local state?

Imagine having a collection of condensed items associated with user IDs. When clicked, I aim to asynchronously fetch and display additional data using an Apollo query - like username, address, etc. How can I effectively "cache" or store this information lo ...

Ensure all keys in a Javascript JSON object are checked for undefined or null values, and assign default values if necessary

After just two days of learning JavaScript, I find myself a bit ahead of the game in what I'm trying to accomplish. I have a JSON array that I use to update content on my webpage. However, I've encountered a problem where if an empty ('null& ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...