Alfred는 Express.js를 영감으로 한 고성능 웹 서버 및 REST API 프레임워크로, Flutter 애플리케이션을 위한 것입니다. 단순성과 속도에 초점을 맞춰 필수 기능들을 하나의 통합 패키지로 제공합니다. Alfred는 최소한의 보일러플레이트로 확장 가능한 백엔드 서비스를 구축할 수 있게 해주며, Flutter 생태계 내에서 풀스택 개발을 지원합니다. Android, iOS, macOS, Windows, Linux 등 다양한 플랫폼에서 작동하므로 크로스플랫폼 서버 측 로직에 이상적입니다. 직관적인 라우팅과 미들웨어 지원을 통해 API 생성과 배포를 간편하게 만듭니다.
사용 사례
Flutter 앱에서 REST API 구축하기
모바일 앱용 백엔드 서비스 만들기
풀스택 플러터 애플리케이션 개발
데스크톱 및 모바일 장치에서 서버 실행
백엔드 기능을 빠르게 프로토타이핑하기
주요 기능
Express.js와 유사한 구문
내장된 라우팅 및 미들웨어
크로스플랫폼 서버 지원
최소한의 보일러플레이트
고성능 및 확장성
적합한 대상
백엔드 기능을 찾는 Flutter 개발자
Dart를 사용하는 풀스택 개발자
경량 서버 로직이 필요한 프로젝트
하이브리드 모바일 및 서버 애플리케이션을 개발하는 팀
API의 빠른 프로토타이핑
고려 사항
대규모 기업용 백엔드를 위한 것이 아님
성숙한 프레임워크에 비해 생태계가 제한적
서버 측 Dart에 대한 이해가 필요합니다
작은 규모에서 중간 규모의 애플리케이션에 가장 적합
플랫폼별 배포 고려 사항
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Alfred
A performant, expressjs like web server / rest api framework thats easy to use and has all the bits in one place.
There is also a 6 part video series that walks you through creating a web server using Alfred from start to deployment, including databases and authentication. You can find that here: https://www.youtube.com/playlist?list=PLkEq83S97rEWsgFEzwBW2pxB7pRYb9wAB
It should do pretty much what you expect. Handling bodies though do need an "await":
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.post('/post-route', (req, res) async {
final body = await req.body; //JSON body
body != null; //true
});
await app.listen(); //Listening on port 3000
}
Internally dart provides a body parser, so no extra dependencies there.
The big difference you will see is the option to not call res.send or res.json etc - although you still can.
Each route accepts a Future as response. Currently you can pass back the following and it will be sent appropriately:
Return Dart Type
Returning REST type
List<dynamic>
JSON
Map<String, Object?>
JSON
Serializable object (Object.toJSON or Object.toJson) * see note
JSON
String
Plain Text
Stream<List<int>>
Binary
List<int>
Binary
File
Binary, with mime type inferred by extension
Directory
Serves static files
* If your object has a "toJSON" or "toJson" function, alfred will run it, and then return the result
If you want to return HTML, just set the content type to HTML like this:
import'dart:io';
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.get('/html', (req, res) {
res.headers.contentType = ContentType.html;
return'<html><body><h1>Title!</h1></body></html>';
});
await app.listen(); //Listening on port 3000
}
If you want to return a different type and have it handled automatically, you can extend Alfred with
custom type handlers.
Quick start guide
If its all a bit overwhelming @iapicca put together a quick start guide which goes into a little
more detail: https://medium.com/@iapicca/alfred-an-express-like-server-framework-written-in-dart-1661e8963db9
Routing & incoming requests
Routing follows a similar pattern to the more basic ExpressJS routes. While there is some regex
matching, mostly just stick with the route name and param syntax from Express:
"/path/to/:id/property" etc
The Express syntax has been extended to support parameter patterns and types. To enforce parameter
validation, a regular expression or a type specifier should be provided after the parameter name, using
another : as a separator:
/path/to/:id:\d+/property will ensure "id" is a string consisting of decimal digits
/path/to/:id:[0-9a-f]+/property will ensure "id" is a string consisting of hexadecimal digits
/path/to/:word:[a-z]+/property will ensure "word" is a string consisting of letters only
/path/to/:id:uuid/property will ensure "id" is a string representing an UUID
Available type specifiers are:
int: a decimal integer
uint: a positive decimal integer
double: a double (decimal form); note that scientific notation is not supported
date: a UTC date in the form of "year/month/day"; note how this type "absorbs" multiple segments of the URI
timestamp: a UTC date expressed in number of milliseconds since Epoch
uuid: a string resembling a UUID (hexadecimal number formatted as xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx); note that no effort is made to ensure this is a valid UUID
You can also use a wildcard for a route, and provided another route hasn't already resolved the
response it will be hit. So for example if you want to authenticate a whole section of an api youc
can do this:
import'dart:async';
import'package:alfred/alfred.dart';
FutureOr_authenticationMiddleware(HttpRequest req, HttpResponse res) async {
res.statusCode = 401;
await res.close();
}
voidmain() async {
final app = Alfred();
app.all('/resource*', (req, res) => _authenticationMiddleware);
app.get('/resource', (req, res) {}); //Will not be hit
app.post('/resource', (req, res) {}); //Will not be hit
app.post('/resource/1', (req, res) {}); //Will not be hitawait app.listen();
}
Route params
You can access any params for routes from the req.params object as below:
Querystring variables are exposed req.uri.queryParameters object in the request as below:
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.post('/route', (req, res) async {
/// Handle /route?qsvar=truefinal result = req.uri.queryParameters['qsvar'];
result == 'true'; //true
});
await app.listen(); //Listening on port 3000
}
Body parsing
To access the body, simply call await req.body.
Alfred will interpret the body type from the content type headers and parse it appropriately. It handles url encoded, multipart & json bodies out of the box.
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.post('/post-route', (req, res) async {
final body = await req.body; //JSON body
body != null; //true
});
await app.listen(); //Listening on port 3000
}
File uploads
To upload a file the body parser will handle exposing the data you need. Its actually pretty easy
just give it a go and set a breakpoint to see what the body parser spits back.
A working example of file uploads is below to get you started:
import'dart:io';
import'package:alfred/alfred.dart';
final _uploadDirectory = Directory('uploadedFiles');
Future<void> main() async {
final app = Alfred();
app.get('/files/*', (req, res) => _uploadDirectory);
/// Example of handling a multipart/form-data file upload
app.post('/upload', (req, res) async {
final body = await req.bodyAsJsonMap;
// Create the upload directory if it doesn't existif (await _uploadDirectory.exists() == false) {
await _uploadDirectory.create();
}
// Get the uploaded file contentfinal uploadedFile = (body['file'] asHttpBodyFileUpload);
var fileBytes = (uploadedFile.content asList<int>);
// Create the local file name and save the fileawaitFile('${_uploadDirectory.absolute}/${uploadedFile.filename}')
.writeAsBytes(fileBytes);
/// Return the path to the user////// The path is served from the /files route abovereturn ({
'path': 'https://${req.headers.host ?? ''}/files/${uploadedFile.filename}'
});
});
await app.listen();
}
Middleware
You can specify a middleware for all routes by using wildcards:
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.all('*', (req, res) {
// Perform action
res.headers.set('x-custom-header', "Alfred isn't bad");
/// No need to call next as we don't send a response./// Alfred will find the next matching route
});
app.get('/otherFunction', (req, res) {
//Action performed nextreturn {'message': 'complete'};
});
await app.listen();
}
Middleware declared this way will be executed in the order its added to the app.
You can also add middleware to a route, this is great to enforce authentication etc on an endpoint:
import'dart:async';
import'package:alfred/alfred.dart';
FutureOrexampleMiddleware(HttpRequest req, HttpResponse res) {
// Do workif (req.headers.value('Authorization') != 'apikey') {
throwAlfredException(401, {'message': 'authentication failed'});
}
}
voidmain() async {
final app = Alfred();
app.all('/example/:id/:name', (req, res) {}, middleware: [exampleMiddleware]);
await app.listen(); //Listening on port 3000
}
What? No 'next'? how do I even?
OK, so the rules are simple. If a middleware resolves a http request, no future middleware gets executed.
So if you return an object from the middleware, you are preventing future middleware from executing.
If you return null it will yield to the next middleware or route.
** returning null is the equivalent of 'next' **
CORS
There is a cors middleware supplied for your convenience. Its also a great example of how to write a middleware for Alfred
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
// Warning: defaults to origin "*"
app.all('*', cors(origin: 'myorigin.com'));
await app.listen();
}
Responses
Alfred is super easy, generally you just return JSON, a file, a String or a Binary stream and you are all good.
The big difference from express is you will see is the option to not call res.send or res.json etc - although you still can.
Each route accepts a Future as response. Currently you can pass back the following and it will be sent appropriately:
List<dynamic> - JSON
Map<String, Object?> - JSON
String - Plain text
Stream<List<int>> - Binary
List<int> - Binary
File - Binary, with mime type inferred by extension
Alfred has a pretty cool mechanism thanks to Dart's type system to automatically resolve a response
based on the returned type from a route. These are called Type Handlers.
If you want to create custom type handlers, just add them to the type handler
array in the app object. This is a bit advanced, and I expect it would be more
for devs wanting to extend Alfred:
import'package:alfred/alfred.dart';
classChicken{
Stringget response => 'I am a chicken';
}
voidmain() {
final app = Alfred();
app.typeHandlers.add(TypeHandler<Chicken>((req, res, Chicken val) async {
res.write(val.response);
await res.close();
}));
/// The app will now return the Chicken.response if you return one from a route
app.get('/kfc', (req, res) => Chicken()); //I am a chicken;
app.listen(); //Listening on 3000
}
Static Files, uploads and deleting
This one is super easy - just pass in a public path and a dart Directory object and Alfred does
the rest.
import'dart:io';
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
/// Note the wildcard (*) this is very important!!
app.get('/public/*', (req, res) => Directory('test/files'));
await app.listen();
}
You can also pass in a directory and a POST or PUT command and upload files to a local directory if
you are using multipart/form encoding. Simply supply the field as file:
import'dart:async';
import'dart:io';
import'package:alfred/alfred.dart';
FutureOrisAuthenticatedMiddleware(HttpRequest req, HttpResponse res) {
if (req.headers.value('Authorization') != 'MYAPIKEY') {
throwAlfredException(
401, {'error': 'You are not authorized to perform this operation'});
}
}
voidmain() async {
final app = Alfred();
/// Note the wildcard (*) this is very important!!////// You almost certainly want to protect this endpoint with some middleware/// to authenticate a user.
app.delete('/public/*', (req, res) => Directory('test/files'),
middleware: [isAuthenticatedMiddleware]);
await app.listen();
}
Security? Build in a middleware function to authenticate a user etc.
File downloads
As mentioned above - if you want to return a file, simply return it from the route callback.
However the browser will probably try to render it in browser, and not download it.
You can just set the right headers, but there is a handy little helper that will do it all for you.
The file handler fully supports resumable downloads (RFC9110 compliant), including:
Range requests for partial content
Multiple range requests with multipart responses
Conditional requests using ETags and Last-Modified dates
Proper handling of If-Range header
Support for suffix ranges (e.g., last 500 bytes)
See res.setDownload below.
import'dart:io';
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.get('/image/download', (req, res) {
res.setDownload(filename: 'image.jpg');
returnFile('test/files/image.jpg');
});
await app.listen(); //Listening on port 3000
}
Error handling
You can either set the status code on the response object yourself and send the data manually, or
you can do this from any route:
404 Handling works the same as 500 error handling (or uncaught error handling). There is a default
behaviour, but if you want to override it, simply handle it in the app declaration.
The other two systems that inspired this project to be kicked off - Aqueduct and Angel - both had
some sort of database integration built in.
You do not need this.
Access the dart drivers for the database system you want directly, they all use them behind the scenes:
Mongo - https://pub.dev/packages/mongo_dart
Postgres - https://pub.dev/packages/postgres
SQLLite - https://pub.dev/packages/sqlite3
You will be fine. I have used them this way and they work.
I have rolled my own classes that act as a sort of ORM, especially around Mongo. Its suprisingly effective
and doesn't rely on much code.
What I want to do isn't listed
While there are bunch of helpers built in - you have direct access to the low level apis available
from the dart:io package. All helpers are just extension methods to:
So you can compose and write any content you can imagine there. If there is something you want to do
that isn't expressly listed by the library, you will be able to do it with a minimum of research into
underlying libraries. A core part of the architecture is to not build you into a wall.
Websockets
Alfred supports websockets too!
There is a quick chat client in the examples
import'dart:async';
import'dart:io';
import'package:alfred/alfred.dart';
import'package:alfred/src/type_handlers/websocket_type_handler.dart';
Future<void> main() async {
final app = Alfred();
// Path to this Dart filevar dir = File(Platform.script.path).parent.path;
// Deliver web client for chat
app.get('/', (req, res) => File('$dir/chat-client.html'));
// Track connected clientsvar users = <WebSocket>[];
// WebSocket chat relay implementation
app.get('/ws', (req, res) {
returnWebSocketSession(
onOpen: (ws) {
users.add(ws);
users
.where((user) => user != ws)
.forEach((user) => user.send('A new user joined the chat.'));
},
onClose: (ws) {
users.remove(ws);
for (var user in users) {
user.send('A user has left.');
}
},
onMessage: (ws, dynamic data) async {
for (var user in users) {
user.send(data);
}
},
);
});
final server = await app.listen();
print('Listening on ${server.port}');
}
Want to quickly print out the registered routes? (recommended when you fire up the server)
call Alfred.printRoutes ie:
import'package:alfred/alfred.dart';
voidmain() async {
final app = Alfred();
app.get('/html', (req, res) {});
app.printRoutes(); //Will print the routes to the consoleawait app.listen();
}
Multi threading and isolates
You can use the app in multithreaded mode. When spawning this way, requests are evenly distributed
amongst the various isolates. Alfred is not particularly prescriptive about how you manage the isolates
just that "it works" when you fire up multiples.
import'dart:isolate';
import'package:alfred/alfred.dart';
Future<void> main() async {
// Fire up 5 isolatesfor (var i = 0; i < 5; i++) {
unawaited(Isolate.spawn(startInstance, ''));
}
// Start listening on this isolate alsostartInstance(null);
}
/// The start function needs to be top level or static. You probably want to/// run your entire app in an isolate so you don't run into trouble sharing DB/// connections etc. However you can engineer this however you like.///voidstartInstance(dynamic message) async {
final app = Alfred();
app.all('/example', (req, res) => 'Hello world');
await app.listen();
}
/// Simple function to prevent linting errors, can be ignoredvoidunawaited(Future future) {}
Deployment
There are many ways to skin this cat, you can upload the source code to a VPS yourself, build a binary locally and upload it to a server somewhere, but a fairly elegant way to accomplish a production level deployment is to containerize an AOT build of the server and run it on a PAAS.
Lucky there is a tutorial for that!
https://ryan-knell.medium.com/build-and-deploy-a-dart-server-using-alfred-docker-and-google-cloud-run-from-start-to-finish-d5066e3ab3c6
Contributions
PRs are welcome and encouraged! This is a community project and as long as the PR keeps within the key principles listed it will probably be accepted. If you have an improvement you would like to to add but are not sure just reach out in the issues section.
NB. The readme is generated from the file in tool/templates/README.md which pulls in the actual source code from the example dart files - this way we can be sure its no pseudocode! If you need to change anything in the documentation please edit it there.
Before you submit your code, you can run the ci_checks.sh shell script that will do many of the tests the CI suite will perform.