routerEdit this page

API routes

The file-system based router provides a way to define API routes in a file-system based manner. You can use the same routing structure as the basic routing for pages.

API routes are similar to middlewares, but they are used for handling API requests. To create an API route, create a file with the matching path for the API route with the .server.{js,mjs,ts,mts} extension and export default an async function or async functions with an HTTP method name from your module. These functions will be the API route handlers. You can also create your API route handler in files with a HTTP method prefix, like GET.posts.server.mjs or POST.posts.server.mjs to apply the handler only for the specified HTTP method. If you create a file with the .server.mjs extension without the prefix, it will be used for all HTTP methods and only the exported function with the current HTTP method name or the default exported function will be called. Supported HTTP methods are GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.

// GET.posts.server.mjs

export default async function GetPosts(context) {
  return new Response(JSON.stringify({ posts: [ /* posts */ ] }), {
    headers: {
      "Content-Type": "application/json",
    },
  });
};