H4.dart
Guide

App instance

The H4 App instance is the core of your server.

Core Creation API

Use the createAPP function to create an instance of the H4 App.

createApp()

final app = createApp(
  port: 3000,         // Default port
  autoStart: true,    // Automatic startup
  onRequest: myMiddleware,
  onError: errorHandler,
  afterResponse: responseLogger
);

Configuration Options

ParameterTypeDefaultDescription
portint3000HTTP listening port
autoStartbooltrueAutomatic server startup
onRequestMiddlewarenullPre-processing middleware
onErrorErrorHandlernullCustom error handling
afterResponseMiddlewarenullPost-processing middleware

Lifecycle Hooks

Request Flow

  1. onRequest middleware
  2. Route handler execution
  3. afterResponse middleware
app = createApp(
  onRequest: (request) {
    print('Incoming ${request.method} @ ${request.url}');
    return request;
  },
  afterResponse: (response) {
    print('Outgoing ${response.statusCode}');
    return response;
  }
);

Error Handling

createApp(
  onError: (error, stackTrace, event) {
    print('[ERROR] ${error.toString()}');
    if (event != null) {
      print('Failed request: ${event.request.method} ${event.request.url}');
    }
    return ErrorResponse(500, 'Custom error message');
  }
)

Manual Startup Control

When autoStart: false:

final app = createApp(
  port: 8080,
  autoStart: false
);
 
// Later in code
await app.start().then((instance) {
  print('Server running on ${instance.port}');
});

Routing Integration

final app = createApp();
final router = createRouter();
 
router.get('/api', (event) => {'status': 'ok'});
router.post('/submit', handleSubmission);
 
app.use(router); // Mount router middleware

Complete Example

import 'package:h4/create.dart';
 
void main() async {
  final app = createApp(
    port: 8080,
    onRequest: (req) {
      print('Request started: ${DateTime.now()}');
      return req;
    },
    onError: (err, stack, event) {
      print('Error: $err');
      return ErrorResponse(500, 'Server error');
    },
    afterResponse: (res) {
      print('Response sent: ${DateTime.now()}');
      return res;
    }
  );
 
  final router = createRouter()
    ..get('/', (event) => 'Welcome to H4')
    ..post('/data', handleData);
 
  app.use(router);
 
  await app.start();
}

On this page