Deploying a Shelf Server
Shelf is a flexible web server framework for Dart. Globe supports deploying Shelf applications with zero custom configuration. This page outlines requirements and deployment behaviour.
Project Setup
To create a new project using the Globe template, run the following command:
globe create –t crud_rest_api_shelf
To create a Shelf project manually
-
Create a basic Dart application:
dart create my_shelf_app
-
Rename
lib/my_shelf_app.dart
tolib/main.dart
for the application entry point -
Install the Shelf package:
dart pub add shelf
-
Copy this code into lib/main.dart:
import 'dart:io'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; void main() async { final handler = const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest); final server = await shelf_io.serve( handler, InternetAddress.anyIPv4, int.tryParse(Platform.environment['PORT'] ?? '8080') ?? 8080, ); print('Serving at http://${server.address.host}:${server.port}'); } Response _echoRequest(Request request) => Response.ok('Request for "${request.url}"... worked!');
For Globe to correctly run your backend application, it must listen to the
PORT
environment variable as shown in the example. -
Test your application locally:
dart run lib/main.dart
-
Visit
http://localhost:8080/hello
in your browser to see:Request for "hello"... worked!
Deploying to Globe
-
Run the deployment command from your project root:
globe deploy
-
For first-time deployments:
- Confirm setup when prompted (press Y)
- Enter a name for your project (e.g., my-shelf-app) or accept the default
-
Wait for the deployment to complete. You'll receive a unique URL for accessing your deployment.
Deployment Behaviour
- Environment: Globe sets the
PORT
variable automatically. Your app must listen to it. - Build runner: Detected and triggered based on Dart project structure.
- Preset: No config needed for Shelf; Globe uses sensible defaults.
- Logs: Real-time logs are available in the dashboard under the Logs tab.
Best practices
- Always listen on the
PORT
environment variable with a fallback for local development. - Implement proper error handling with appropriate HTTP status codes.
- Use middleware for logging, authentication, and other cross-cutting concerns.
- Separate route handlers into dedicated files for better maintainability.
- Validate and sanitize all user input to prevent security vulnerabilities.