A Vercel Runtime to write serverless functions in Dart.
A serverless function file should contain a shelf handler named handler
. Behind the scenes, the runtime will combine the handler with an AWS runtime and compile it into a binary file using dart2native
.
Example
Create a file called api/hello.dart
with the following contents.
import 'dart:io' show Platform;
import 'package:shelf/shelf.dart';
Response handler(Request req) {
final version = Platform.version.split(" ").first;
return Response.ok('Hello, from Dart v$version!');
}
Next, select the vercel-dart
runtime to handle serverless dart functions in your vercel.json
file.
{
"functions": {
"api/**/*.dart": { "runtime": "vercel-dart@1.1.0" }
}
}
Demo: vercel-dart.vercel.app/api/hello
Check out the repository's
api
folder for more examples.
import 'package:shelf/shelf.dart';
Response handler(Request req) {
return Response.ok('Query is: ${req.requestedUri.query}');
}
Demo: vercel-dart.vercel.app/api/query
import 'package:shelf/shelf.dart';
Response handler(Request req) =>
Response.movedPermanently('https://youtu.be/dQw4w9WgXcQ');
// Response.movedPermanetly -> 301
// Response.notFound -> 404
// etc.
Demo: vercel-dart.vercel.app/api/redirect
import 'dart:convert';
import 'dart:io';
import 'package:shelf/shelf.dart';
Response handler(Request req) {
final data = {
'host': req.requestedUri.host,
'path': req.requestedUri.path,
'query': req.requestedUri.queryParameters
};
return Response.ok(
jsonEncode(data),
headers: {
'content-type': ContentType.json.toString(),
},
);
}
Demo: vercel-dart.vercel.app/api/json
import 'dart:io';
import 'package:shelf/shelf.dart';
Response handler(Request req) {
final html = '''
<h1>Hello, World</h1>
''';
return Response.ok(
html,
headers: {
'content-type': ContentType.html.toString(),
},
);
}
Demo: vercel-dart.vercel.app/api/html
Here are the build environment variables that you may configure for your serverless functions.
Name | Description | Default |
---|---|---|
DART_CHANNEL |
The dart channel that serverless function will use. |
stable |
DART_VERSION |
The dart version that serverless function will use. |
2.10.5 |
Note that you need to use dart version
>= 2.6
fordart2native
to work.
Learn more about dart channels and versions here.
Yes, just make sure it is at the same directory level as the function. The runtime will automatically run pub get
before building the binary file.
I'm not sure because I don't know how to benchmark. But according to my experience, it feels like it's really fast. I may be biased so help me benchmark it if you know how to.
Yes, but because it won't install dart
during development, make sure your machine has a working version of dart >= 2.6
installed properly.
While I was trying to build this, because I didn't any prior experience with things, a lot of open-source libraries/projects were very useful to me. The prominent ones of them are now-rust, vercel-bash, vercel-deno and aws-lambda-dart-runtime.
MIT © Frenco