Nuxt has built-in support to create server endpoints. You can use it to fetch your data from your database, request other API, return static content, think like express.js with super powers, thanks to Nitro and H3 ecosystem.
This is a basic example of directory structure for your <app>/server/
directory:
server/
├── api/
│ └── hello.ts # /api/hello
├── routes/
│ └── sitemap.xml.ts # /sitemap.xml
├── plugins/ # nitro plugins
├── tasks/ # nitro tasks
├── middleware/ # nitro middlewares
├── utils/ # server only utils
└── tsconfig.json # server only tsconfig
We will create a /api/hello
route that will return a greeting message.
export default defineEventHandler((event) => {
// extract the "from" query parameter
const from = getQuery(event)?.from || 'tairo'
return `Hello ${from}!`
})
You can test your API route by visiting http://localhost:3000/api/hello?from=world
in your browser, or by using curl in your terminal:
curl -i http://localhost:3000/api/hello?from=world
# HTTP/1.1 200 OK
# content-type: text/html
# date: Wed, 12 Mar 2025 16:31:06 GMT
# connection: close
# content-length: 12
#
# Hello world!
Useful resources:
Now that you have a page and an API route, you can connect them together. We will request the hello API route from the page created in the previous section and display the result.
<script setup lang="ts">
// definePageMeta ...
// create a reactive input value
const input = ref('')
// create a computed object that will be updated
// every time the input value changes
const query = computed(() => ({ from: input.value }))
// call our API route, it will be re-fetched
// every time the query object changes
// note that data type is detected automatically!
const { data } = useFetch('/api/hello', {
query,
})
</script>
<template>
<div class="max-w-lg">
<BaseCard class="p-6">
<!-- reactive input -->
<BaseField label="Your name">
<BaseInput v-model="input" />
</BaseField>
<!-- display the result -->
<BaseParagraph class="mt-4 line-clamp-1 max-w-sm">
{{ data }}
</BaseParagraph>
</BaseCard>
</div>
</template>
You may also want to take a look at how we do form validation and explore form pages from the demo to learn more about how to build forms with Tairo.
Useful resources: