server library
Spark Framework Server Utilities.
This library provides server-side utilities for rendering HTML pages,
routing, and serving static files. It includes the SparkServer implementation
and helpers for SSR.
Note: This library uses dart:io and should strictly not be imported
in code that targets the browser.
Usage with Pages
For the recommended annotation-based approach:
// lib/pages/user_page.dart
@Page(path: '/users/:id')
class UserPage extends SparkPage<User> {
@override
Future<PageResponse<User>> loader(PageRequest request) async {
final user = await fetchUser(request.pathParamInt('id'));
return PageData(user);
}
@override
String render(User data, PageRequest request) {
return '<h1>${data.name}</h1>';
}
}
// bin/server.dart
void main() async {
final server = await createSparkServer(SparkServerConfig(
port: 8080,
));
print('Running at http://localhost:${server.port}');
}
Manual Usage
For manual routing without code generation:
import 'package:spark_framework/server.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
void main() async {
final app = Router();
app.get('/', (req) {
final html = Counter(start: 100).render();
return Response.ok(
renderPage(
title: 'Home',
content: html,
scriptName: 'home.dart.js',
),
headers: {'content-type': 'text/html'},
);
});
// Serve compiled JS files
app.mount('/', createStaticHandler('build/web'));
await serve(app.call, 'localhost', 8080);
}
Classes
- Attribute
- Marks a field as a reactive attribute.
- Component
- Marks a class as an island component that can be hydrated on the client.
- ComponentInfo
- Information about a component used by a page.
- Cookie
- Represents an HTTP Cookie.
- Validates that a string is a valid email.
- Endpoint
- Annotation for defining API endpoints.
- ExternalDocumentation
- Allows referencing an external resource for extended documentation.
- IsBooleanString
- Validates that a string represents a boolean ("true", "false", "1", "0").
- IsDate
- Validates that a string is a valid date (ISO 8601).
- IsNumeric
- Validates that a string contains only numbers.
- IsString
- Validates that a value is a string.
- Length
- Validates that a string length is within min and max.
- Max
- Validates that a number is at most value.
- Min
- Validates that a number is at least value.
- MultipartPart
- Represents a part in a multipart request.
- NotEmpty
- Validates that a string is not empty.
- OpenApi
- global configuration for the OpenAPI specification.
- Page
- Marks a class as a page that will be registered with the Spark router.
-
PageData<
T> - Response containing typed data to render the page.
- PageError
- Response for rendering an error page.
- PageOptions
- Configuration options for page rendering.
- PageRedirect
- Response indicating a redirect to another URL.
-
PageResponse<
T> - Sealed class representing possible responses from a page loader.
- Parameter
- Describes a single operation parameter.
- Pattern
- Validates that a string matches the given pattern.
- Pipeline
- A helper that makes it easy to compose a set of Middleware and a Handler.
- Request
- An HTTP request to be processed by a Shelf application.
- Response
- The response returned by a Handler.
- SecurityScheme
- Defines a security scheme for the API.
- SecuritySchemeFlow
- Defines an OAuth2 flow.
- SparkEndpoint
- Abstract base class for Spark API endpoints without a request body.
-
SparkEndpointWithBody<
T> - Abstract base class for Spark API endpoints with a typed request body.
-
SparkPage<
T> - Abstract base class for Spark pages.
- SparkRequest
- Request context for page loaders.
- StaticHandlerConfig
- Configuration for the static file handler.
- Validator
- Base class for all validators.
Enums
- ContentType
- Standardized content types supported by Spark.
- SameSite
- Represents the SameSite attribute of a cookie.
Extensions
Functions
-
createStaticHandler(
String path, {StaticHandlerConfig? config}) → Handler - Creates a Shelf handler for serving static files.
-
renderPage(
{required String title, required String content, String? scriptName, List< String> additionalScripts = const [], List<String> stylesheets = const [], Object? inlineStyles, Object? headContent, String lang = 'en', String charset = 'UTF-8', String viewport = 'width=device-width, initial-scale=1', List<String> metaTags = const [], String? nonce}) → String - Renders a complete HTML page with the given options.
-
renderPageWithOptions(
PageOptions options) → String - Renders a page using PageOptions configuration.
-
simpleStaticHandler(
String path) → Handler - Simple static handler without configuration (backwards compatible).
Typedefs
-
Handler
= FutureOr<
Response> Function(Request request) - A function which handles a Request.
- Middleware = Handler Function(Handler innerHandler)
- A function which creates a new Handler by wrapping a Handler.
- PageRequest = SparkRequest
- Legacy alias for backward compatibility.
Exceptions / Errors
- ApiError
- Standard JSON Error Response DTO
- SparkHttpException
- Base HTTP Exception
- SparkValidationException
- Exception for Validation Failures