Server functions

Write JavaScript or TypeScript in server/api.js that wakes on demand to validate input, call outside services with secrets and use your app's database, reached at /_smn/api. Isolated, short and private.

Most of an app runs in the visitor's browser. Some work should not: checking input before it is saved, calling a service with a secret key, or combining data. Studio Functions run your server code. A server function is JavaScript (or TypeScript) that runs on SeeMyNotes when the app asks, then goes back to sleep. There is nothing to deploy or keep running.

How it works

  1. Put your code in server/api.js or server/api.ts (and other files under server/ if you like). The AI builder can write it, or you add it in the code editor.

  2. Your page calls it at /_smn/api/<route> on the same address, with any method:

    const response = await fetch('/_smn/api/weather?city=Lisbon');
    const data = await response.json();
  3. SeeMyNotes starts your code in an isolated sandbox, hands it the request, waits for the answer, and throws the sandbox away.

Server code is private: the files under server/ are never served to visitors, and the app's secrets never enter the sandbox.

Write a handler

server/api.js is an ES module. Export a function for each method you handle, or one default function for all of them. It receives the request and a context object and returns an answer.

// server/api.js
export async function GET(request, ctx) {
  if (request.path !== '/weather') {
    return Response.json({ error: 'Not found' }, { status: 404 });
  }
  const city = request.query.city;
  if (!city) {
    return Response.json({ error: 'city is required' }, { status: 400 });
  }
  const response = await smn.fetch('weather', 'forecast?city=' + encodeURIComponent(city));
  if (!response.ok) {
    return Response.json({ error: 'The weather service failed' }, { status: 502 });
  }
  const data = await response.json();
  return Response.json({ city, temperature: data.temperature });
}

export async function POST(request, ctx) {
  if (request.path !== '/sign-up') {
    return Response.json({ error: 'Not found' }, { status: 404 });
  }
  const body = await request.json();
  const name = String(body.name || '').trim().slice(0, 80);
  if (!name) {
    return Response.json({ error: 'name is required' }, { status: 400 });
  }
  await smn.db.run('sign_up', { name });
  return Response.json({ ok: true });
}

The two routes above use an endpoint named weather (see App configuration) and an operation named sign_up (see App data).

The request

PropertyWhat it is
request.methodGET, POST, PUT, PATCH or DELETE
request.pathThe route after /_smn/api, starting with /
request.queryThe query parameters as an object
request.headersThe headers, with get, has and forEach
await request.text()The body as text
await request.json()The body parsed as JSON

Request bodies are UTF-8 text.

The context

The second argument, ctx, tells you who is calling:

The answer

Return a Response (for example Response.json(value, { status })), a string, bytes, or any JSON value. Return nothing for an empty answer (status 204).

What you can use inside

What you cannot use

There is no fetch, no timers, no file system, no process, no npm packages (so no bare imports such as import x from 'lodash') and no JSX. The only way out is through smn.fetch, smn.mcp and smn.db, which use the connections and operations you configured. Server functions call the database like a visitor: they read the tables visitors can read, and write only through operations.

Write it in TypeScript

Any file under server/ can be TypeScript, in React apps, HTML apps and apps imported from GitHub. Name the entry server/api.ts instead of server/api.js, and import your other files with a relative path, with or without the extension (./helper, ./helper.ts and ./helper.js all name the same file).

// server/api.ts
import { toCelsius } from './temperature.ts';
import type { Forecast } from './types.ts';

export async function GET(request: { query: Record<string, string> }): Promise<Response> {
  const city = request.query.city;
  if (!city) {
    return Response.json({ error: 'city is required' }, { status: 400 });
  }
  const response = await smn.fetch('weather', 'forecast?city=' + encodeURIComponent(city));
  const data: Forecast = await response.json();
  return Response.json({ city, celsius: toCelsius(data.fahrenheit) });
}
// server/temperature.ts
export function toCelsius(fahrenheit: number): number {
  return Math.round(((fahrenheit - 32) * 5) / 9);
}
// server/types.ts
export interface Forecast {
  fahrenheit: number;
}

When you save a version, SeeMyNotes turns each .ts file into a .js file next to it, and that is what runs. In the code editor you keep editing your .ts files; the generated .js files are not listed and cannot be edited on their own.

Secrets

Never put a key in server code. Save it as a secret variable and use it in an endpoint's header, for example Authorization: Bearer {{OPENAI_KEY}}. The server fills it in outside the sandbox; the code never sees the value, and any copy of it in a response is replaced by [secret]. See App configuration.

Limits

Each call has a time limit and a memory limit, caps on the size of the code, the request, the answer and the number of calls to outside services, and per-visitor, per-app and per-account limits per minute and per day. A call over its limit gets a clear error, and your other calls are not affected.

The current limits are shown on the plans and limits page.

Test and fix errors

Who can call it

The same people who can open the app: for a public app, everyone; for a private app, only people with access. See Who can open your app.

Related pages