Expose JSON endpoints in Nuxt 3 using server/api
Add server-side JSON API routes to a Nuxt 3 app without a separate backend by placing handlers in server/api.
29 Jul 2025, 22:24 UTC

Problem and useful takeaway
You need a small server-side JSON endpoint—for example, a health check, a webhook receiver, or a thin proxy to an external API—but you do not want to provision and maintain a separate Express or Fastify service just for one route.
In Nuxt 3, any handler file placed in server/api is automatically registered as an HTTP route. Nuxt uses h3, a lightweight HTTP framework, so exporting a default defineEventHandler is enough. No manual router configuration or additional server framework is required.
Desired outcome
- Expose
/api/helloand return a JSON object. - Verify it locally with
nuxi devand in a production preview withnuxi buildfollowed bynuxi preview. - Confirm the handler code stays out of the client-side JavaScript bundle.
Prerequisites
- A Nuxt 3 project scaffolded with
nuxi(for example,npx nuxi init my-app). - Node.js LTS installed.
- Basic familiarity with h3-style handlers:
defineEventHandler((event) => { ... }). h3 is the HTTP framework Nuxt uses for server routes. - No external Express, Fastify, or custom Node server is required.
Procedure
1. Create a GET endpoint
Create server/api/hello.get.ts in your project root. The .get.ts suffix tells Nuxt to handle only GET requests for this path.
export default defineEventHandler((event) => {
return {
ok: true,
message: 'hello from server/api',
timestamp: new Date().toISOString(),
}
})
2. Start the development server
Run this command in a terminal at the project root. No sudo is required.
npx nuxi dev
Expected check: the dev server starts, typically on http://localhost:3000. If port 3000 is already in use, Nuxt usually reports an alternative port in the terminal.
3. Request the endpoint
From another terminal window, run:
curl -i http://localhost:3000/api/hello
Expected result: HTTP status 200, Content-Type: application/json, and a JSON body similar to the object returned by the handler. If you receive 405 Method Not Allowed, you likely used the wrong HTTP method for the file suffix (see the table below).
4. Add a dynamic segment (optional)
For routes with URL parameters, use square brackets in the filename. Values arrive through event.context.params. Always validate parameters before using them in database or filesystem operations.
export default defineEventHandler((event) => {
const id = event.context.params?.id
if (!id || typeof id !== 'string') {
throw createError({ statusCode: 400, statusMessage: 'Missing user id' })
}
return { id }
})
File: server/api/users/[id].get.ts, accessible at /api/users/123.
5. Access raw Node request and response (fallback)
If you need the raw Node.js objects—for example, to inspect raw headers for a webhook—use event.node.req and event.node.res. Prefer h3 event helpers for ordinary JSON APIs.
6. Expose configuration safely
Do not hardcode secrets in handler files. Use runtimeConfig in nuxt.config.ts. Keys outside public remain server-only.
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '',
public: {
apiBase: '/api',
},
},
})
Inside a handler, read server-only values with useRuntimeConfig().
Method suffix reference
| File suffix | HTTP method | Example path |
|---|---|---|
.get.ts | GET | /api/hello |
.post.ts | POST | /api/hello |
[id].get.ts | GET with dynamic segment | /api/users/123 |
Expected checks
- HTTP 200 response with a JSON body.
Content-Typeheader isapplication/json.- Handler code does not appear in client-side JavaScript bundles;
server/apifiles are server-only. - The route still responds after
nuxi buildandnuxi preview.
Production preview verification
- Run
npx nuxi buildat the project root. - Run
npx nuxi previewto start the production preview server. - Repeat the
curl -irequest against the preview URL, typicallyhttp://localhost:3000unless configured otherwise. - If the route returns 404 in preview but worked in dev, confirm the file is inside
server/apiand uses the correct method suffix.
Recovery and rollback
Adding a route file changes application state, so the simplest rollback is to remove or rename the file.
- Stop the dev server (
Ctrl+C). - Delete
server/api/hello.get.tsor rename it tohello.get.ts.disabled. - Restart the dev server with
npx nuxi dev. - If a handler throws an error, inspect the terminal stack trace, fix the code, and restart. Do not edit the file while the server is running and expect hot reload to catch every server-only change reliably.
Limitations
- Handlers run in a Node/server context only. Importing
window,document, or browser-only libraries causes runtime errors. - Dynamic route parameters are user input. Validate and sanitize them before database or filesystem access.
- Method suffixes are enforced. A request with the wrong method returns 405 Method Not Allowed.
- Server-only
runtimeConfigvalues are not sent to the browser. Never place secrets underpublic. - This guide covers local development and production preview. Deployment behavior depends on your hosting platform and Nuxt output preset.
Practical result check
After starting the preview server, run:
curl -i http://localhost:3000/api/hello
Expect HTTP 200 and a JSON payload. If you receive 404, verify the file location and suffix. If you receive 405, verify you used the matching HTTP method.