How to build a local API route in Nuxt 3

Nuxt guide logo

Setup local Nuxt API route

Create a server folder at the root of your Nuxt project if it doesn't exist.

Inside the server folder, create an api folder /server/api.

Inside the api folder create a file and let's name it as users.ts, i.e /server/api/users.ts.

The code

Fetching data from external API

In users.ts file:

                                
                                        // users.ts
// We are using a dummy API mock from reqres.in

export default defineCachedEventHandler(
  async (event) => {
    const data = await $fetch('https://reqres.in/api/users?page=2')
                 .catch((error) => error.data);
    
    return data;
  },
  { swr: true } // this will enable caching
);
                                    
                            

Fetching data from the Nuxt application

Now the server api has been set up, we ready to fetch it from our Nuxt 's application

                                
                                        // pages/index.vue

<template>
  <section>
    {{ data }}
  </section>
</template>

<script setup lang="ts">
  const { data } = await useFetch('/api/users');
</script>
                                    
                            
Previous post Payload CMS - How to query image content from Richtext field
Next post How to use Pinia in Nuxt