Writing Serverless Functions
ServerlessFlow allows you to deploy code without provisioning servers. Your functions are event-driven, meaning they run only when triggered by an HTTP request, a scheduled cron job, or a database event.
How it works
- Write your function code in one of our supported languages.
- We containerize your code automatically.
- We invoke your container when a request comes in.
- We scale your function from 0 to 1,000+ instances instantly.
Function Anatomy
Regardless of the language, every function follows the same input/output contract. This strict contract allows us to normalize requests from different sources.
Input (Args)
Your function receives a single parameter (usually called args). This contains:
- HTTP Query Parameters
- HTTP Body (JSON)
- Path Parameters
Output (Return)
You must return a JSON object (or Dictionary).
body: The actual response data.statusCode: (Optional) HTTP status.headers: (Optional) Custom headers.
Runtime Examples
Select your preferred language to see the boilerplate code. This code is ready to deploy immediately.
function main(args) {
// 1. Parse Input
let name = args.name || 'stranger';
// 2. Do Logic
let greeting = 'Hello ' + name + '!';
console.log("Processing request for: " + name);
// 3. Return JSON
return { "body": greeting };
}Language Specific Note
We run Node.js 18.x LTS. 'require' is supported, but ES Modules (import/export) require setting 'type': 'module' in package.json.
Best Practices
Statelessness
Functions should be stateless. Do not rely on local variables persisting between requests. Use a database (like Redis or MongoDB) for state.
Execution Time
Keep functions fast. The default timeout is 60 seconds. Long-running tasks should be offloaded to a background worker or queue.
Error Handling
Always return standard HTTP status codes in your response body or error object to trigger retries properly.
Dependencies
Keep your deployment package small. Remove devDependencies before deploying to ensure faster cold starts.
Logging & Monitoring
ServerlessFlow automatically captures standard output (stdout) and standard error (stderr) streams. You do not need a third-party logging library.
How to view logs
- Dashboard Stream:
Navigate to your function details page. The "Real-time Logs" tab shows a live websocket connection to your running container.
- Structured Logging:
If you print a JSON string (e.g.
console.log(JSON.stringify(obj))), our dashboard will automatically parse and format it for easier reading.
Environment Variables
Security Warning
Never hardcode API keys or database passwords in your function code. Use the "Settings" tab in your dashboard to add encrypted environment variables.