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
Put your code in
server/api.jsorserver/api.ts(and other files underserver/if you like). The AI builder can write it, or you add it in the code editor.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();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
| Property | What it is |
|---|---|
request.method | GET, POST, PUT, PATCH or DELETE |
request.path | The route after /_smn/api, starting with / |
request.query | The query parameters as an object |
request.headers | The 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:
ctx.viewer.kind:visitor,owner,buyerorreader, depending on how the person is allowed in.ctx.visitor: a pseudonymous id for this visitor in this app, not their identity.ctx.preview: true when you are running from your private preview.ctx.app: the app's id and label.
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
The same names as the browser helper:
smn.db.query,smn.db.all,smn.db.run,smn.db.schema,smn.fetch,smn.mcpandawait smn.env(). See the helper reference.Response,Headers,TextEncoder,TextDecoder,console,crypto.randomUUIDandcrypto.getRandomValues.Relative imports of other
.js,.mjsand.tsfiles underserver/, and.jsonfiles imported as data.
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.
Types are removed, not checked. A type mistake does not stop the save or the call; a syntax error does, and the message names the file, line and column. Run a type checker yourself if you need one (for example after pushing the app to GitHub).
Some TypeScript-only constructs are refused.
namespaceandmoduleblocks, decorators,import x = require()andexport =have no JavaScript equivalent here, so the save fails with the file and line. Useexportof values, a plain object, a normalimportorexport defaultinstead. Enums, classes with parameter properties anddeclareblocks work.No JSX.
.tsxand.jsxfiles underserver/are refused.One file per module. Having both
server/api.tsandserver/api.js(orapi.mjs) is refused, and the message names both files.The
smnhelper is available as in JavaScript. It is not declared for the type checker, so declare it yourself in aserver/globals.d.tsfile if your own tools need it.
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
In your preview, an error in server code is shown in detail, and what your code printed with
console.logis kept. On the live app, only errors are kept, so visitors' data stays out of the logs.Ask the AI builder to read the server logs and fix the problem: "The sign-up route returns 500. Check the logs and fix it."
Each version with server code is screened like any other version before it goes live. A flagged version runs only in your preview until you publish it.
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.