Skip to content

Functions

Develop Appwrite Functions_

Master serverless function development with Appwrite. Learn how to write and test functions locally, debug code, and optimize for efficient execution.

16 min read

Raw

Appwrite Functions offer a familiar interface if you've developed REST endpoints. Each function is handled following a request and response pattern.

Lifecycle

There is a clear lifecycle for all Appwrite Functions, from beginning to end. Here's everything that happens during a function execution.

  1. The function is invoked.
  2. The active deployment's executor will handle the request.
  3. The Executor passes in request information like headers, body or path through the context.req object of your exported function.
  4. The runtime executes the code you defined, you can log through the context.log() or context.error() methods.
  5. Function terminates when you return results using return context.res.text(), return context.res.json() or similar. In Node.js 18 and later, Bun, Deno, Python, and Dart, it can also return a native response.

Locally developed functions follow the same lifecycle on your local machine.

Entrypoint

You'll find all of these steps in a simple function like this. Notice the exported entry point that the executor will call.

import { Client } from 'node-appwrite';
// This is your Appwrite function
// It's executed each time we get a request
export default async ({ req, res, log, error }) => {
// Why not try the Appwrite SDK?
//
// Set project and set API key
// const client = new Client()
// .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
// .setKey(req.headers['x-appwrite-key']);
// You can log messages to the console
log('Hello, Logs!');
// If something goes wrong, log an error
error('Hello, Errors!');
// The `req` object contains the request data
if (req.method === 'GET') {
// Send a response with the res object helpers
// `res.text()` dispatches a string back to the client
return res.text('Hello, World!');
}
// `res.json()` is a handy helper for sending JSON
return res.json({
motto: 'The open-source cloud for agents and developers_',
learn: 'https://appwrite.io/docs',
connect: 'https://appwrite.io/discord',
getInspired: 'https://builtwith.appwrite.io',
});
};

If you prefer to learn through more examples like this, explore the examples page.

Context object

Context is an object passed into every function to handle communication to both the end users, and logging to the Appwrite Console. All input, output, and logging must be handled through the context object passed in. The one exception is the response in Node.js 18 and later, Bun, Deno, Python, and Dart, where a function can return a native response instead.

You'll find these properties in the context object.

PropertyDescription
reqContains request information like method, body, and headers. See full examples in the request section.
resContains methods to build a response and return information. See full examples in the response section.
log()Method to log information to the Appwrite Console, end users will not be able to see these logs. See full examples in the logging section.
error()Method to log errors to the Appwrite Console, end users will not be able to see these errors. See full examples in the logging section.

Destructuring assignment

Some languages, namely JavaScript, support destructuring. You'll see us use destructuring in examples, which has the following syntax.

Learn more about destructuring assignment.

// before destructuring
export default async function (context) {
context.log("This is a log!");
return context.res.text("This is a response!");
}
// after destructuring
export default async function ({ req, res, log, error }) {
log("This is a log!");
return res.text("This is a response!");
}

Request

If you pass data into an Appwrite Function, it'll be found in the request object. This includes all invocation inputs from Appwrite SDKs, HTTP calls, Appwrite events, or browsers visiting the configured domain. Explore the request object with the following function, which logs all request params to the Appwrite Console.

Request types

RequestDescription
req.bodyTextReturns text that has been converted from binary data.
req.bodyJsonParses the body text as JSON.
req.bodyBinaryReturns the binary body.
req.rawReturns the request object of the runtime's web server, such as a Fetch API Request in Node.js 18 and later, Bun, and Deno. Learn more in native request and response.
export default async ({ req, res, log }) => {
log(req.bodyText); // Raw request body, contains request data
log(JSON.stringify(req.bodyJson)); // Object from parsed JSON request body, otherwise string
log(JSON.stringify(req.headers)); // String key-value pairs of all request headers, keys are lowercase
log(req.scheme); // Value of the x-forwarded-proto header, usually http or https
log(req.method); // Request method, such as GET, POST, PUT, DELETE, PATCH, etc.
log(req.url); // Full URL, for example: http://awesome.appwrite.io:8000/v1/hooks?limit=12&offset=50
log(req.host); // Hostname from the host header, such as awesome.appwrite.io
log(req.port); // Port from the host header, for example 8000
log(req.path); // Path part of URL, for example /v1/hooks
log(req.queryString); // Raw query params string. For example "limit=12&offset=50"
log(JSON.stringify(req.query)); // Parsed query params. For example, req.query.limit
return res.text("All the request parameters are logged to the Appwrite Console.");
};

Headers

Appwrite Functions will always receive a set of headers that provide meta data about the function execution. These are provided alongside any custom headers sent to the function.

VariableDescription
x-appwrite-triggerDescribes how the function execution was invoked. Possible values are http, schedule, event, or email.
x-appwrite-eventIf the function execution was triggered by an event, describes the triggering event.
x-appwrite-email-idIf the function execution was triggered by an email, the ID of the email delivery. Learn more about email triggers.
x-appwrite-email-domainIf the function execution was triggered by an email, the domain of the address in x-appwrite-email-recipient.
x-appwrite-email-recipientIf the function execution was triggered by an email, the first address of the function in the email delivery.
x-appwrite-keyThe ephemeral API key is used for server authentication. Learn more about ephemeral API keys.
x-appwrite-user-idIf the function execution was invoked by an authenticated user, display the user ID. This doesn't apply to Appwrite Console users or API keys.
x-appwrite-user-jwtJWT token generated from the invoking user's session. Used to authenticate Server SDKs to respect access permissions. Learn more about JWT tokens.
x-appwrite-country-codeDisplays the country code of the configured locale.
x-appwrite-continent-codeDisplays the continent code of the configured locale.
x-appwrite-continent-euDescribes if the configured local is within the EU.
x-appwrite-client-ipDisplays the IP of the client creating the execution.
x-appwrite-execution-idDisplays the ID of the current execution.

Executions triggered by an email do not receive the x-appwrite-execution-id, x-appwrite-client-ip, x-appwrite-country-code, x-appwrite-continent-code, or x-appwrite-continent-eu headers.

Response

Use the response object to send a response to the function caller. This could be a user, client app, or an integration. The response information will not be logged to the Appwrite Console. There are several possible ways to send a response, explore them in the following Appwrite Function.

Response types

ResponseDescription
emptySends a response with a code 204 No Content status.
jsonConverts the data into a JSON string and sets the content-type header to application/json.
binaryPackages binary bytes, the status code, and the headers into an object.
redirectRedirects the client to the specified URL link.
textConverts the body using UTF-8 encoding into a binary Buffer.
sendStreamSends the body in chunks as your function produces them. Learn more in streaming responses.
Native responseSends the status, headers, and body of a response object your function returns, in place of a res method. Return a Fetch API Response in Node.js 18 and later, Bun, and Deno, an aiohttp web.Response in Python, or a shelf Response in Dart. Learn more in native request and response.
const fs = require('fs');
export default async ({ req, res, log }) => {
switch (req.query.type) {
case 'empty':
return res.empty();
case 'json':
return res.json({"type": "This is a JSON response"});
case 'binary':
const bytes = await fs.readFile('file.png');
return res.binary(bytes);
case 'redirect':
return res.redirect("https://appwrite.io", 301);
case 'html':
return res.text(
"<h1>This is an HTML response</h1>", 200, {
"content-type": "text/html"
});
default:
return res.text("This is a text response");
}
}

To get the different response types, set one of the following query parameters in the generated domain of your function.

TypeQuery ParamExample
text/?type=texthttps://64d4d22db370ae41a32e.fra.appwrite.run/?type=text
json/?type=jsonhttps://64d4d22db370ae41a32e.fra.appwrite.run/?type=json
redirect/?type=redirecthttps://64d4d22db370ae41a32e.fra.appwrite.run/?type=redirect
html/?type=htmlhttps://64d4d22db370ae41a32e.fra.appwrite.run/?type=html
empty/https://64d4d22db370ae41a32e.fra.appwrite.run/

Streaming responses

Return res.sendStream() to send the response body in chunks. Each chunk is sent to the client as your function produces it, instead of once the function has finished. Use it for output that is produced over time, such as tokens from an LLM, server-sent events, progress updates, or large exports. The other response methods still send the whole body at once.

sendStream() takes the source of the chunks, then an optional status code and headers, in the same order as text(). The status code and headers are sent with the first chunk.

RuntimeCallSource of chunks
Node.js, Bun, Denores.sendStream()An async iterable, such as an async generator, of strings or Uint8Arrays
PHP$context->res->sendStream()An iterable, such as a generator, of strings
Pythoncontext.res.sendStream()A generator, an async generator, or another iterable, of strings or bytes
Rubycontext.res.send_stream()An Enumerator, or another object that responds to each, of strings
GoContext.Res.SendStream()An iter.Seq2[[]byte, error]
Dartcontext.res.sendStream()A Stream of strings or List<int>
Swiftcontext.res.sendStream()A Sendable AsyncSequence, such as an AsyncStream, of strings or Data
.NETContext.Res.SendStream()An IAsyncEnumerable<object> of strings or byte[]
Kotlincontext.res.sendStream()A Flow or a Sequence of strings or ByteArrays
Javacontext.getRes().sendStream()An Iterable of strings or byte[]
C++context.res.sendStream()A function that returns the next chunk as a std::optional<std::string>, or std::nullopt to end the stream

The Rust runtime does not support streaming, and neither do the deprecated node-14.5, dart-2.15 and swift-5.5 runtimes. In Go, require github.com/open-runtimes/types-for-go/v4 v4.0.11 or later in your go.mod.

This function streams three server-sent events, one second apart.

export default async ({ res }) => {
async function* events() {
for (let i = 1; i <= 3; i++) {
if (i > 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
yield `data: Message ${i}\n\n`;
}
}
return res.sendStream(events(), 200, {
'content-type': 'text/event-stream'
});
};

The Node.js example works the same on Bun. In Go, set the status code and headers with Context.Res.WithStatusCode() and Context.Res.WithHeaders(). In Swift, the status code and headers are the statusCode: and headers: arguments.

In Node.js 18 and later, Bun, and Deno, a function can also return a Fetch API Response. In Dart, it can return a shelf Response, after you add shelf to your pubspec.yaml. A streamed body in these responses is sent the same way as sendStream(). Python's native response, an aiohttp web.Response, doesn't stream.

export default async () => {
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
for (let i = 1; i <= 3; i++) {
if (i > 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
controller.enqueue(encoder.encode(`data: Message ${i}\n\n`));
}
controller.close();
}
});
return new Response(body, {
headers: { 'content-type': 'text/event-stream' }
});
};

These rules apply to streamed responses:

  • If the source fails before its first chunk, the client receives a 500 response, as when your function throws an error.
  • If the source fails after the first chunk, the status code and headers have already been sent, so the response ends early with only the chunks sent so far. If the client needs to know that a stream is complete, end it with a chunk of your own, such as a final event.
  • The execution lasts until the stream ends, not until your function returns. Your function's timeout, 15 seconds by default, covers the whole stream, and a stream that is still running when the timeout is reached ends there. A request to a function domain is a synchronous execution limited to 60 seconds, so its stream also ends there, even if your function's timeout is longer.

Executions created with the Create execution endpoint, including through an SDK, do not stream. A synchronous one returns the whole body after the stream ends, and fails with a timeout error if the execution takes longer than 30 seconds.

If you read the stream with the browser EventSource API, close it when you receive your final event. Otherwise it reconnects when the response ends and runs your function again.

Self-hosted Appwrite 2.7.1 and earlier do not stream responses.

Native request and response

Every runtime runs your function inside a web server. req.raw gives you that server's own request object, so you can use its methods and the libraries written for it. In Node.js 18 and later, Bun, Deno, Python, and Dart, your function can also return a native response object instead of calling a res method.

RuntimeRequestRequest typeResponse you can return
Node.js 18+, Bun, Denoreq.rawFetch API RequestFetch API Response
Pythoncontext.req.rawaiohttp web.Requestaiohttp web.Response
Dartcontext.req.rawshelf Requestshelf Response
PHP$context->req->rawSwoole\Http\RequestNot available
Rubycontext.req.rawSinatra::RequestNot available
GoContext.Req.Raw*http.RequestNot available
.NETContext.Req.RawASP.NET Core HttpRequestNot available
Kotlincontext.req.rawJavalin ContextNot available
Javacontext.getReq().getRaw()Javalin ContextNot available
Swiftcontext.req.rawVapor RequestNot available
C++context.req.rawDrogon HttpRequestPtrNot available
Rustcontext.req.rawOption<http::Request<Vec<u8>>>Not available

The deprecated node-14.5, dart-2.15, and swift-5.5 runtimes have no req.raw and don't accept native responses. The node-16.0 runtime has no Request or Response class, so use req and the res methods there. In Go, require github.com/open-runtimes/types-for-go/v4 v4.0.9 or later in your go.mod. In Rust, use openruntimes-types-for-rust 1.0.3 or later.

Read the request

In Node.js 18 and later, Bun, and Deno, req.raw is a Fetch API Request built from the same data as the rest of req:

  • Its URL is req.url and its method is req.method.
  • Its headers are req.headers, including Appwrite headers such as x-appwrite-key and x-appwrite-user-id.
  • Its body can be read once, as with any Request. GET and HEAD requests have no body.
  • Reading its body doesn't change req.bodyText, req.bodyJson, or req.bodyBinary.

req.raw throws an error for CONNECT, TRACE, and TRACK requests, because the Request class doesn't accept those methods.

In the other runtimes, req.raw is the web server's own request object:

  • It has the Appwrite headers, and also the x-open-runtimes-* headers the runtime uses internally. req.headers leaves those out.
  • The runtime reads the body before your function runs and then makes it readable again, so you can read it through req.raw too. In .NET, set Context.Req.Raw.Body.Position to 0 before you read it.
  • In Python, the body-reading methods of context.req.raw are coroutines, so declare your function with async def. await context.req.raw.post() parses URL-encoded forms but fails on multipart bodies, because the runtime has already read them. To parse a multipart body, pass context.req.body_binary to a multipart parser.

This function reads the method, path, and body through req.raw and returns them as JSON.

export default async ({ req, res }) => {
const raw = req.raw;
return res.json({
method: raw.method,
path: new URL(raw.url).pathname,
body: await raw.text()
});
};

In Node.js 18 and later, Bun, and Deno, formData() parses both URL-encoded and multipart bodies. This function reads a form sent with POST.

export default async ({ req, res }) => {
const raw = req.raw;
if (raw.method !== 'POST') {
return res.text('Send the form with POST', 405);
}
const form = await raw.formData();
return res.text(`Hello, ${form.get('name')}!`);
};

Return a response

In Node.js 18 and later, Bun, Deno, Python, and Dart, your function can return a native response instead of calling a res method. Appwrite sends its status, headers, and body to the client.

  • In Node.js, Bun, and Deno, return a Fetch API Response. A ReadableStream body is sent in chunks, the same way as sendStream().
  • In Python, return an aiohttp web.Response, including one built by a helper such as web.json_response(). The Python runtime already includes aiohttp, so you don't need to add it to requirements.txt. The body must be in memory, so returning a web.StreamResponse or web.FileResponse fails the execution. To stream from Python, use sendStream().
  • In Dart, return a shelf Response after you add shelf to your pubspec.yaml. A Stream body is sent in chunks, the same way as sendStream(). If the body is a String with non-ASCII characters, set the content-type header yourself, because shelf otherwise labels it application/octet-stream.
export default async () => {
return new Response(JSON.stringify({ status: 'ok' }), {
status: 200,
headers: {
'content-type': 'application/json',
'cache-control': 'max-age=60'
}
});
};

If a returned Response sets more than one cookie, use node-20.0 or later, Bun, or Deno. Earlier Node.js versions join the cookies into a single set-cookie header, and browsers don't split it back into separate cookies. Python and Dart send each cookie in its own set-cookie header, including cookies added with aiohttp's set_cookie().

Use a web framework

In Node.js 18 and later, Bun, and Deno, frameworks built on the Fetch API take a Request and return a Response. Pass them req.raw and return what they give back. This function serves two routes with Hono. In Node.js and Bun, add hono to your package.json first.

import { Hono } from 'hono';
const app = new Hono();
app.get('/', (c) => c.text('Hello from Hono!'));
app.get('/users/:id', (c) => c.json({ id: c.req.param('id') }));
export default async ({ req }) => app.fetch(req.raw);

Hono matches routes against the request path. For a request to the function's domain, that's the path in the URL. For an execution you create, it's the path you pass when you create it.

To call log() and error() from your routes, pass the context to Hono as its environment with app.fetch(req.raw, context), then use c.env.log() inside a route.

Logging

To protect user privacy, the request and response objects are not logged to the Appwrite Console by default.

We support the spread operator across most of the languages, meaning you can write code that is more concise and flexible.

This means, to see logs or debug function executions you need to use the log() and error() methods. These logs are only visible to developers with access to the Appwrite Console.

Here's an example of using logs and errors.

export default async ({ req, res, log, error }) => {
const message = "This is a log, use for logging information to console";
log("Message: ", message);
log(`This function was called with ${req.method} method`);
const errorMessage = "This is an error, use for logging errors to console"
error("Error: ", errorMessage);
return res.text("Check the Appwrite Console to see logs and errors!");
};

You can access these logs through the following steps.

  1. In Appwrite Console, navigate to Functions.
  2. Click to open a function you wish to inspect.
  3. Under the Executions tab, click on an execution.
  4. In the Response section, you'll be able to view logs under the Logs and Errors tabs.

Environment variables

Pass constants and secrets into your function with environment variables, and read them inside your function using your runtime's standard environment lookup.

Dependencies

To install your dependencies before your function is built, you should add the relevant install command to the top your function's Build setting > Commands. You can find this setting under Functions > your function > Settings > Configuration > Build settings.

Make sure to include dependency files like package.json, composer.json, requirements.txt, etc. in your function's configured root directory. Do not include the dependency folders like node_modules, vendor, etc. in your function's root directory. The dependencies installed for your local OS may not work in the executor environments

Your function's dependencies should be managed by the package manager of each language. By default, we include the following package managers in each runtime.

  LanguagePackage ManagerCommands
Node.js logoNode.jsNPMnpm install
PHP logoPHPComposercomposer install
Python logoPythonpippip install -r requirements.txt
Ruby logoRubyBundlerbundle install
Deno logoDenodenodeno cache <ENTRYPOINT_FILE>
Go logoGoGo ModulesN/A
Dart logoDartpubpub get
Swift logoSwiftSwift Package Managerswift package resolve
.NET logo.NETNuGetdotnet restore
Bun logoBunbunbun install
Kotlin logoKotlinGradleN/A
Java logoJavaGradleN/A
C++ logoC++NoneN/A
Rust logoRustCargocargo build --release

Using Appwrite in a function

Appwrite can be used in your functions by adding the relevant SDK to your function's dependencies. Authenticating with Appwrite is done via an ephemeral API key or a JWT token.

Ephemeral API key

Ephemeral API keys are the same as API keys but are automatically generated. They are generated in your functions per execution. However, you can only use ephemeral API keys inside Appwrite Functions and Appwrite Sites.

During the build process, ephemeral API keys are automatically provided as the environment variable APPWRITE_FUNCTION_API_KEY. This environment variable doesn't need to be initialized.

During execution, ephemeral API keys are automatically provided in the x-appwrite-key header.

Ephemeral API keys grant access and operate without sessions. They allow your function to act as an admin-type role instead of acting on behalf of a user. Update the function settings to configure the scopes of the function.

  1. In Appwrite Console, navigate to Functions.
  2. Click to open a function you wish to configure.
  3. Under the Settings tab, navigate to Scopes.
  4. Select the scopes you want to grant the ephemeral key.
  5. It is best practice to allow only necessary permissions.
import { Client, TablesDB, ID } from 'node-appwrite';
export default async ({ req, res, log, error }) => {
// Set project and set API key
const client = new Client()
.setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
.setKey(req.headers['x-appwrite-key']);
const tablesDB = new TablesDB(client);
try {
await tablesDB.createRow({
databaseId: '<DATABASE_ID>',
tableId: '<TABLE_ID>',
rowId: ID.unique(),
data: {}
})
} catch (e) {
error("Failed to create row: " + e.message)
return res.text("Failed to create row")
}
return res.text("Row created")
}

Using with JWT

JWTs allow you to act on behalf of an user in your Appwrite Function. When using JWTs, you will be able to access and change only the resources with the same permissions as the user account that signed the JWT. This preserves the permissions you configured on each resource.

If the Appwrite Function is invoked by an authenticated user, the x-appwrite-user-jwt header is automatically passed in.

import { Client, TablesDB, ID } from 'node-appwrite';
export default async ({ req, res, log }) => {
const client = new Client()
.setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
if (req.headers['x-appwrite-user-jwt']) {
client.setJWT(req.headers['x-appwrite-user-jwt'])
} else {
return res.text("Access denied: This function requires authentication. Please sign in to continue.");
}
const tablesDB = new TablesDB(client);
try {
await tablesDB.createRow({
databaseId: '<DATABASE_ID>',
tableId: '<TABLE_ID>',
rowId: ID.unique(),
data: {}
})
} catch (e) {
log("Failed to create row: " + e.message)
return res.text("Failed to create row")
}
return res.text("Row created")
}

Code structure

As your functions grow, you may find yourself needing to split your code into multiple files. This helps you keep your codebase maintainable and easy to read. Here's how you can accomplish code splitting.

Node.js
// src/utils.js
export function add(a, b) {
return a + b;
}
Node.js
// src/main.js
import { add } from './utils.js';
export default function ({ res }) {
return res.text(add(1, 2));
}

Was this page helpful?

Share what worked or what we should fix. Once approved, our agents automatically apply suggested updates to the docs.