routingkit 5.1.1 copy "routingkit: ^5.1.1" to clipboard
routingkit: ^5.1.1 copied to clipboard

A lightweight, high-performance router for Dart with elegant API support for static, parameterized, and wildcard routes. Perfect for HTTP servers, API gateways, and application routing.

RoutingKit

Pub Version Test License Sponsors X (formerly Twitter) Follow

RoutingKit - A lightweight, high-performance router for Dart with an elegant object-oriented API.

Features #

  • 🚀 High Performance: Optimized route matching using a trie-based structure
  • 🧩 Flexible Routes: Support for static, parameterized, and wildcard routes
  • 💪 Type Safety: Generic typing for your route handlers
  • 🔍 Comprehensive Matching: Find single or all matching routes
  • 🧰 Object-Oriented API: Clean, chainable methods for route management
  • 🔠 Case Sensitivity Options: Configure whether path matching is case sensitive or not

Installation #

Run this command:

dart pub add routingkit

With Flutter:

flutter pub add routingkit

Usage #

Creating a Router #

import 'package:routingkit/routingkit.dart';

// Create a typed router (recommended)
final router = createRouter<String>();

// For handling different data types
final dynamicRouter = createRouter<dynamic>();

// Create a case-insensitive router
final caseInsensitiveRouter = createRouter<String>(caseSensitive: false);

// Configure both case sensitivity and custom anyMethodToken
final customRouter = createRouter<String>(
  caseSensitive: false,
  anyMethodToken: 'ANY_METHOD',
);

Adding Routes #

RoutingKit supports various route patterns:

// Static routes
router.add('GET', '/users', 'Users list handler');

// Parameter routes (with named parameters)
router.add('GET', '/users/:id', 'User details handler');

// Multiple parameters
router.add('GET', '/users/:id/posts/:postId', 'User post handler');

// Optional format parameter
router.add('GET', '/files/:filename.:format?', 'File handler');

// Wildcard routes
router.add('GET', '/assets/**', 'Static assets handler');

// Named wildcard segments
router.add('GET', '/docs/**:path', 'Documentation handler');

// Method-specific routes
router.add('POST', '/users', 'Create user handler');
router.add('PUT', '/users/:id', 'Update user handler');
router.add('DELETE', '/users/:id', 'Delete user handler');

Matching Routes #

Find the first matching route:

final match = router.find('GET', '/users/123');

if (match != null) {
  print('Handler: ${match.data}');
  print('Parameters: ${match.params}'); // {id: 123}
}

Find all matching routes (useful for middleware):

final matches = router.findAll('GET', '/users/123/settings');

for (final match in matches) {
  print('Handler: ${match.data}');
  print('Parameters: ${match.params}');
}

Removing Routes #

// Remove a specific route
router.remove('GET', '/users/:id');

// Remove all routes for a specific method
router.remove('POST', null);

HTTP Method Handling #

RoutingKit automatically normalizes HTTP methods to uppercase. This means that methods like 'get', 'GET', or 'Get' are all treated as 'GET'. This follows the HTTP specification and makes the router more robust.

router.add('get', '/users', 'get-users');  // Will be normalized to 'GET'
router.add('POST', '/users', 'post-users'); // Will be normalized to 'POST'

// All these will match the same route
router.find('get', '/users');   // Matches
router.find('GET', '/users');   // Matches
router.find('Get', '/users');   // Matches

Advanced Configuration #

Case Sensitivity

By default, RoutingKit performs case-sensitive path matching. You can make path matching case-insensitive:

// Create a case-insensitive router
final router = createRouter<String>(caseSensitive: false);

// Add a route with mixed case
router.add('GET', '/Users/:ID', 'user handler');

// All these will match the same route
final match1 = router.find('GET', '/users/123');    // Matches
final match2 = router.find('GET', '/Users/456');    // Matches
final match3 = router.find('GET', '/USERS/789');    // Matches

// Parameter names preserve their original case
print(match1.params);  // {ID: 123}

Custom Method Tokens

You can customize the token used to represent any HTTP method:

final router = createRouter<String>(anyMethodToken: 'ANY_METHOD');

// Add routes with different methods
router.add('GET', '/api', 'get handler');
router.add(null, '/api', 'any handler');  // Uses custom token

router.find('POST', '/api')?.data;  // Returns 'any handler'

Example Applications #

HTTP Server Routing #

import 'dart:io';
import 'package:routingkit/routingkit.dart';

void main() async {
  final router = createRouter<Function>();
  
  // Define routes with handler functions
  router.add('GET', '/', (req, res) => res.write('Home page'));
  router.add('GET', '/users', (req, res) => res.write('Users list'));
  router.add('GET', '/users/:id', (req, res) => res.write('User ${req.params['id']}'));
  
  final server = await HttpServer.bind('localhost', 8080);
  print('Server running on http://localhost:8080');
  
  await for (final request in server) {
    final response = request.response;
    final path = request.uri.path;
    final method = request.method;
    
    final match = router.find(method, path);
    
    if (match != null) {
      final handler = match.data;
      // Add params to request for handler access
      (request as dynamic).params = match.params;
      handler(request, response);
    } else {
      response.statusCode = HttpStatus.notFound;
      response.write('404 Not Found');
    }
    
    await response.close();
  }
}

For AI Assistance #

RoutingKit includes an llms.txt file at the root of the repository. This file is specifically designed to help Large Language Models (LLMs) understand the project structure and functionality.

If you're using AI tools like GitHub Copilot, Claude, or ChatGPT to work with this codebase, you can point them to the llms.txt file for better context and more accurate assistance.

// Example: Asking an AI about the project
"Please read the llms.txt file in this repository to understand the RoutingKit structure"

The file provides AI-friendly documentation including:

  • Project overview and core concepts
  • Code structure explanation
  • API reference and examples
  • Links to relevant implementation files

Migration from v4.x #

See the Migration Guide in the changelog.

License #

RoutingKit is open-sourced software licensed under the MIT license.

4
likes
150
points
1.39k
downloads

Publisher

verified publisherodroe.dev

Weekly Downloads

A lightweight, high-performance router for Dart with elegant API support for static, parameterized, and wildcard routes. Perfect for HTTP servers, API gateways, and application routing.

Repository (GitHub)

Topics

#router #http #path-matching #trie #performance

Documentation

API reference

Funding

Consider supporting this project:

github.com

License

MIT (license)

More

Packages that depend on routingkit