0
0
Vueframework~5 mins

Server routes and API in Vue

Choose your learning style9 modes available
Introduction

Server routes let your app talk to a server to get or send data. APIs are like menus that show what data you can ask for or send.

When you want to load user info from a server to show on your page.
When you need to save a form's data to a database.
When your app needs to get updated info without reloading the whole page.
When you want to connect your frontend app with backend services.
When you want to build features like login, comments, or live updates.
Syntax
Vue
import { defineEventHandler } from 'h3'

export default defineEventHandler(async (event) => {
  // Your code to handle the request
  return { message: 'Hello from API' }
})

This example shows a simple server route handler in a Vue 3 + Nitro environment (like Nuxt 3).

Server routes are placed in the server/api folder and automatically become API endpoints.

Examples
A simple GET route that returns a greeting message as JSON.
Vue
export default defineEventHandler(() => {
  return { greeting: 'Hi there!' }
})
This route reads data sent by the client and sends it back in the response.
Vue
import { readBody } from 'h3'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  return { received: body }
})
Returns the current server time as a string.
Vue
export default defineEventHandler(() => {
  return { time: new Date().toISOString() }
})
Sample Program

This server route handles POST requests. It reads the JSON body sent by the client, extracts the name field, and replies with a greeting message. If the request is not POST, it tells the client what to do.

Vue
import { defineEventHandler, readBody } from 'h3'

export default defineEventHandler(async (event) => {
  if (event.node.req.method === 'POST') {
    const data = await readBody(event)
    return { message: `Hello, ${data.name}!` }
  }
  return { message: 'Send a POST request with { name } in JSON.' }
})
OutputSuccess
Important Notes

Server routes run only on the server, so you can safely handle secrets or database calls here.

Use readBody(event) to get data sent by the client in POST or PUT requests.

Server routes in Vue/Nuxt are automatically available based on their file path under server/api.

Summary

Server routes let your app communicate with backend logic and data.

APIs define how your frontend and backend talk using requests and responses.

In Vue with Nitro, server routes are simple functions that handle requests and return JSON.