Docs/API Routes

API Routes

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

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 PATCH 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

Defining a conflicting GET route in a directory with a page, will cause that page to never be available.