API routes
import type { EndpointHttpContext } from '@markless/router';
export default function user({ params }: EndpointHttpContext<{ id: string }>) {
return Response.json({ id: params.id });
}GET /api/users/42 answers {"id":"42"}. The path gives the address, .get in the name gives the method, and the default export is the function that runs.
The file name picks the method
An endpoint is one file in api/, at the app root next to pages/. Its name sets what it answers:
[id]is one part of the address, read asparams.id..get,.post,.put,.patch,.delete,.head,.options,.connector.tracepicks one method.- No method in the name answers every method.
Type an id, then drop the coin in GET or POST.
Only the file that matches both the method and the path answers. A POST to /api/users/42 matches no file and gets a 404.
One function gets the whole request
The default export gets one object, the context:
request,urlandparamsdescribe what was asked.localsholds what middleware set.response.headerslets you add headers; or return your ownResponse.
export const cache = { maxAge: 60 };That line lets the answer be cached for 60 seconds.
Writes from other sites are refused
A browser sends your app's cookies with every request to it, even one that a page on another site starts. Without a check, a page elsewhere could submit a form to your POST route as if your signed-in visitor had sent it. This attack is called cross-site request forgery.
So every endpoint answers 403 to a write that a browser sent from another site, before your function runs. A write is any method except GET, HEAD and OPTIONS. The browser tells the server where a request came from in the Sec-Fetch-Site header. Only requests from the same origin (same scheme, host and port) pass, so admin.example.com cannot write to example.com. Older browsers that do not send Sec-Fetch-Site are judged by their Origin header, which must match the address the request was sent to. A request with neither header, such as one from curl or from another server, always passes.
If a proxy in front of your app changes the host or the scheme (https to http) that the server sees, that Origin check can refuse your own pages in those older browsers. Current browsers send Sec-Fetch-Site and are not affected.
There is no switch to trust another site's pages. If another site needs to write, have its server call your endpoint, with whatever credentials you choose to check.
A form can post straight to an endpoint
A plain HTML form can send its fields to an endpoint, with no handler of your own:
import { computed } from '@markless/core';
export default function Todos() @{
const todos = computed(async () => (await fetch('/api/todos')).json() as Promise<Array<{ id: number; title: string }>>);
@try {
<form method="post" action="/api/todos">
<input name="title" />
<button type="submit">Add</button>
</form>
<ul>
@for (const todo of todos; key todo.id) {
<li>{todo.title}</li>
}
</ul>
} @pending {
<p>Loading</p>
} @catch (error, reset) {
<p>{error.message} <button type="button" onClick={reset}>Dismiss</button></p>
}
}import type { EndpointHttpContext } from '@markless/router';
const todos: Array<{ id: number; title: string }> = [];
export default async function addTodo({ request }: EndpointHttpContext) {
const title = String((await request.formData()).get('title') ?? '').trim();
if (!title) return new Response('A title is required.', { status: 422 });
todos.push({ id: todos.length + 1, title });
return new Response(null, { status: 303, headers: { location: '/' } });
}The endpoint answers 303 with a location: a redirect, which tells the browser which page to show next. Without JavaScript, the browser does what it always does with a form: it sends the POST, follows the redirect and loads the page again, now with the new item.
With JavaScript, Markless sends the same request without leaving the page:
- From the press until the list has loaded again, the form has
aria-busy="true"and the button that sent it hasaria-disabled="true", as for a form whose handler is sending. Pressing the button again while nothing changed sends nothing. - A redirect back to the page you are on keeps the page: the values it shows inside a
@tryload again, and the form is cleared, as a freshly loaded page would show it, but only if it still holds exactly what that press sent: anything typed since the press stays. A form with a field that shows state, such asvalue={title}, keeps what it shows. - A redirect to another page of your app opens that page the way a link does, without a full page load.
- A redirect to another site, such as a payment or sign-in page, loads that site, as the browser would.
- An answer that is not a success (a status of 400 or more) shows in the form's
@catch, and the page and what was typed stay. The message is themessageof a JSON answer, the text of atext/plainanswer, or otherwise the status text. A failed connection shows the browser's own error.
The endpoint gets the request the browser would send: the same address, method and encoding (including files, for enctype="multipart/form-data"), and the name and value of the button that was pressed. Markless marks the request with a header, and the code that wraps every endpoint answers that POST's 301, 302 or 303 to a web address with the address in a header instead of a redirect, and tells caches not to store it. A redirect to an address that is not a web address, such as javascript:, is never followed: the save shows as failed in @catch. So your server does no more work than it would without JavaScript: the page the redirect names is never rendered and thrown away, and a one-time message the POST sets in a cookie is still there for the page that shows it. A 307 or 308, which asks the browser to send the POST again, is left to the browser.
Your page's own JavaScript comes first. A submit listener you add with addEventListener runs before Markless decides, sees event.defaultPrevented as false, and if it calls event.preventDefault(), Markless sends nothing.
If the code that sends the form cannot load, for example on a lost connection, the browser sends the form itself, as it would without JavaScript. Until it is sent, the form already has aria-busy="true".
This happens for a form inside a @try that has a @catch, whose method is post (written as text, or as an expression that is post when the form is sent), and that has no onSubmit on it or on an element around it. Everything else stays the browser's:
- A form outside any
@trywith a@catchloads the answer as a page, because there is nowhere on the page to show a failure. - A
targetother than_self, on the form, on the button asformtarget, or on a<base>element, sends the form where it says. - An
action, or a button'sformaction, on another site goes there. - A button with
formmethod="get"loads the page it names. rel="external"on the form loads the answer as a page, the same way it makes a link do a full page load.- A form inside another component counts only when that component is not exported, is used only as a tag in its own file, and every one of those tags sits inside a
@trywith a@catch. Otherwise it stays the browser's, because the build decides from the file it compiles, one file at a time, whether a@catchwill be there to show a failure. When such a form renders inside a@trywith a@catchin this file but stays the browser's, the build warns withMARKLESS_ASYNC_POST_FORM_LEAVES_PAGE, which names the reason and a fix. - A redirect that does not come from an endpoint, such as one from middleware, is followed by the request itself; one to another site then fails and shows in
@catch, so give such a formrel="external".
The check that decides this is about 700 bytes compressed, and only pages with such a form carry it.
Middleware runs on every request
A file in middleware/ runs before every page and endpoint. The full-stack starter ships this one:
export default function request(http: import('@markless/router').MiddlewareHttpContext) {
http.response.headers.set('x-markless-router', '1');
}Each file in api/ or middleware/ is a .ts file with one export default function, and the file name gives the method.
Ready to put it online? Build and deploy your app.