Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt3 prerender all routes

Tags:

nuxt3.js

Nuxt will prerender and generate payload for almost all routes.

However for dynamic pages I believe you need to specify inside nuxt.config

nitro: {
    prerender: {
        crawlLinks: false,
        routes: [
            // all my routes goes here
        ]
    }
 }

My problem is where to make the fetch for all my routes and how to import it to nuxt.config the result.

like image 203
mart cube Avatar asked Oct 23 '25 09:10

mart cube


1 Answers

As pointed out in the comments above by mart cube, this is what works in Nuxt 3.8.2 : (my nuxt config is also testing multilingual, that's why I create 2 arrays. Essentially you can do anything you want inside the getRoutes function, as long as you return an array of routes)

Here's the whole config file:


import axios from "axios";

const getRoutes = async () => {

    const endpoint = 'https://jsonplaceholder.typicode.com/posts'
    const response = await axios.get(endpoint)
    let articles = response.data.slice(0, 20);

    let slugsFR = articles.map((each:any) => { return '/presse/' + each.id })
    let slugsEN = articles.map((each:any) => { return '/en/articles/' + each.id })
    const all = [...slugsFR, ...slugsEN];
    return all
}


export default defineNuxtConfig({
  devtools: { enabled: true 
  },

  modules: [
    '@nuxtjs/tailwindcss',
    ['@nuxtjs/i18n', { locales: ['fr', 'en'], defaultLocale: 'fr', } ],
  ],


  hooks: {
    async 'nitro:config'(nitroConfig) {
        if (nitroConfig.dev) { return }
        let slugs = await getRoutes();
        //@ts-ignore
        nitroConfig.prerender.routes.push(...slugs)
        return
    }
  },

})
like image 146
martinval Avatar answered Oct 27 '25 01:10

martinval