Search code examples
vue.jsnuxt.jsvuejs3nuxt3.jsnitro

Nuxt3: /server directory structure. Dynamic Nested API routes


In Nuxt3, I am using useFetch to call this url endpoint:

company = await useFetch(`/api/company/${companyKey}/profile`)

Notice the extra /profile at the end? How can I organize my /server directory to cater to a url endpoint of this structure?

For example: if the url had been without the /profile (i.e. /api/company/${companyKey}), then the /server directory would be simple to achieve:

/server/company/[companyKey].get.js 

However, with the extra /profile appended at the end, it becomes more tricky to think about.

How can I handle this scenario? Thank you.


Solution

  • I think they call this a nested dynamic server API routes.

    I created an example for you based on your question. Tested and it works. https://stackblitz.com/edit/nuxt-starter-wv9cuk?file=app.vue

    Edit

    /* 
    * Folder structure would be
     - server
       - api - FOLDER
        - company - FOLDER
         - [company_key] - FOLDER
          - profile.get.ts - FILE
    *    - [company_kuy].get.ts - FILE
    */

    Alternative

    You can also use the catch-all-route. See link example https://stackoverflow.com/a/76151522/21341655