Docs/API Routes
API ROUTES

API Routes

You can easily add API endpoints in Elegance by creating a route.ts file anywhere in your project.

Just like pages, API routes follow fs-routing conventions. A route.ts in <project-root>/pages/api/route.ts will be available at http://localhost:3000/api/.

HTTP Methods

To define the methods available for your API endpoint, you can export async functions with method names like GET or POST.

The methods: GET, POST, PUT, DELETE and OPTIONS are supported.

A simple get endpoint that returns some JSON might look like this:

ts
export async function GET(req, res) { const payload = JSON.stringify({ message: "Hello, World!", }); res.end(payload); return; }

You can define as many methods in one file as you'd like.

ts
export async function GET(req, res) {} export async function DELETE(req, res) {} export async function POST(req, res) {}

Notes

Types

The types of req and res are from the standard Node HTTP library, and are req: IncomingMessage and res: ServerResponse. For proper type inference you'll need to import type { IncomingMessage, ServerResponse } from "node:http"; at the top of the route.ts file.

Conflicts

Whilst you can define a route.ts in the same directory as a page.ts(x), it's important to note that the GET method wont be available, and it might conflict with some methods of the page.