How to build a local API route in Nuxt 3
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>