🌿 Nuxt.js Intermediate

How do you create API routes in Nuxt.js server directory?

Answer

API routes are created as files inside server/api/. The file name determines the URL path and HTTP method. A file at server/api/users.get.ts handles GET /api/users. Each file exports a default function wrapped in defineEventHandler(): export default defineEventHandler(async (event) => { return { users: [] } }). You can read request body with await readBody(event), query params with getQuery(event), and headers with getHeader(event, 'authorization'). Nitro automatically serializes returned objects as JSON. Utility functions in server/utils/ are auto-imported in the server context, enabling clean separation of database logic from route handlers.