コンテンツにスキップ
Vantage
English
Esc
navigateopen⌘Jpreview
このページの内容

API & server

Adding server/ enables an API. Conventions for ApiContext, HttpError, and HTTP methods.

Vantage’s server is optional. Add a server/ directory to your project and the API turns on, switching the build to fullstack mode. Without it, your app is client-only (a SPA) and /api/* is just a client route (matching production).

API route conventions

APIs are derived from server/api/** using the same filename conventions as pages.

File Endpoint
server/api/customers.ts /api/customers
server/api/customers/[id].ts /api/customers/:id
server/api/monthly-analysis.ts /api/monthly-analysis

Each file exports functions named after HTTP methods. Allowed methods are GET / POST / PUT / PATCH / DELETE / OPTIONS.

// server/api/customers/[id].ts  →  /api/customers/:id
import type { ApiContext } from "@squadbase/vantage/server";
import { HttpError } from "@squadbase/vantage/server";

export async function GET({ params, env }: ApiContext) {
  const customer = await findCustomer(params.id!);
  if (!customer) throw new HttpError(404, "Customer not found");
  return Response.json(customer);
}

ApiContext

Handlers speak in web-standard types. The ApiContext argument carries:

Property Meaning
request The standard Request
params Dynamic params (e.g. params.id)
env Server-side environment variables and secrets
waitUntil Fire-and-forget background work after the response

Return a standard Response. Use Response.json(...) or the json() helper.

import { json } from "@squadbase/vantage/server";

export async function GET() {
  return json({ ok: true });
}

Handling errors

To surface an error to the client, throw HttpError(status, message) — its status and message reach the client verbatim.

if (!authorized) throw new HttpError(403, "Forbidden");

Any other thrown error is logged on the server and returned to the client as a generic 500 (no internals leak).

dev and prod behave identically

Request dispatch (route matching, 405 handling, request-id) goes through one shared core in both dev and prod. What you see in development reproduces in production.

Secrets stay on the server

ApiContext.env is readable only on the server. It never reaches the client. Read API keys, DB credentials, and the like from here. For values you do want on the client, see Environment variables.

このページは役に立ちましたか?