Dancer2...tending(3)

πŸ“¦
version 2.2.1 Β· 3 versions
, in fedora 44

🌸 NAME

Dancer2::Manual::Extending β€” a whole guide to extending Dancer2 via engines and plugins. Bestie, we're building custom stuff. πŸ’…

(It's the manual page for Dancer2...tending(3) β€” the User Contributed Perl Documentation one, iykyk.)


πŸ’– VERSION

version 2.2.1


✨ Name

Dancer2::Extending β€” How to Extend Dancer2 by Writing Your Own Engines, Handlers, and Plugins πŸŽ€


🌸 Introduction

Dancer2 was literally designed to be flexible and extensible. Like, that's the whole vibe. Need a custom template engine? A session engine? A serializer? A file handler? Dancer2 hands you a clean API so extending the core functionality is genuinely easy, no cap. πŸ¦‹

In this doc we're covering how to write your own engines, handlers, and plugins for Dancer2. The goal: giving you the tools to build custom components that slot seamlessly into your Dancer2 apps. Main character energy, but for modules. πŸ‘‘


πŸ’… Writing Your Own Engine

So in Dancer2, engines handle all the various aspects of your app β€” templates, sessions, serializers, loggers, all of it. Every engine follows a standard interface, which is why plugging in a new implementation is so easy. Slay.

Engines can live in the Dancer2 namespace:

set serializer => 'JSON';
set template => 'Mason';

(those resolve to Dancer2::Serializer::JSON and Dancer2::Template::Mason respectively, in case you were wondering 🧚)

Or you can hand over the fully qualified namespace using the "+" indicator:

set serializer => `+My::Awesome::Serializer`;
set template => `+My::Template::DWIM`;

The latter is lowkey similar to how Plack handles this. 🫢

πŸŽ€ Writing a Template Engine

A custom template engine has to implement the Dancer2::Core::Role::Template role. That role defines the basic methods every template engine needs to implement. Periodt.

Example: Custom Template Engine

package Dancer2::Template::MyTemplateEngine;
use Moo;
with 'Dancer2::Core::Role::Template';

# Define the required methods
# ...

sub render {
    my ($self, $template, $tokens) = @_;

    # Your rendering logic here
    return "<html><body>Welcome to Danceyland, $tokens->{'visitor_name'}!</body></html>";
}

1;

In this example, render is the method responsible for processing the template and returning the final output. She's the one doing the work. πŸ’ͺ

To use your custom engine, configure it in your config.yml file:

template: "MyTemplateEngine"

🌈 Writing a Session Engine

Session engines handle storing and retrieving session data. All session engines must implement the Dancer2::Core::Role::SessionFactory role.

Example: Custom Session Engine

package Dancer2::Session::MySessionEngine;
use Moo;
with 'Dancer2::Core::Role::SessionFactory';

sub retrieve {
    my ($self, $id) = @_;
    # Fetch session data based on session ID
}

sub create {
    my ($self, $data) = @_;
    # Create a new session
}

sub destroy {
    my ($self, $id) = @_;
    # Destroy the session identified by $id
}

sub flush {
    my ($self, $id, $data) = @_;
    # Save session data
}

1;

This engine defines the basic methods to manage session data. Four little methods, one big job. πŸ“

⭐ Writing a Serializer Engine

Serializer engines handle serializing and deserializing data between Perl data structures and different formats like JSON, YAML, or XML. The translators of the Dancer2 world, fr fr.

All serializer engines must implement the Dancer2::Core::Role::Serializer role.

Example: Custom Serializer Engine

package Dancer2::Serializer::MySerializer;
use Moo;
with 'Dancer2::Core::Role::Serializer';

sub serialize {
    my ($self, $content) = @_;
    # Convert $content to a custom format
}

sub deserialize {
    my ($self, $content) = @_;
    # Convert custom format back to Perl data structure
}

sub content_type {
    return 'application/custom';
}

1;

This engine defines the methods needed to serialize and deserialize data. Back and forth, back and forth. πŸ¦‹

πŸ’œ Writing a Logger Engine

Logger engines are responsible for handling log messages in your application. All logger engines must implement the Dancer2::Core::Role::Logger role.

Example: Custom Logger Engine

package Dancer2::Logger::MyLogger;
use Moo;
with 'Dancer2::Core::Role::Logger';

sub log {
    my ($self, $level, $message) = @_;
    # Custom logging logic here
    warn "[$level] $message";
}

1;

This logger will output log messages to warn, and you can configure it in your config.yml file:

logger: "MyLogger"

🧚 Writing Your Own File Handler

File handlers in Dancer2 are responsible for serving static files from disk. If you need custom logic for serving files β€” like restricting access or adding dynamic features β€” you can create your own file handler by consuming the Dancer2::Core::Role::Handler role. It's giving very DIY, very iconic. ✨

πŸŽ€ Example: Custom File Handler

package Dancer2::Handler::MyFileHandler;
use Moo;
with 'Dancer2::Core::Role::Handler';

sub methods { qw(GET) }

sub regexp { '/static/:file' }

sub code {
    return sub {
        my $app = shift;
        my $file = $app->request->params->{file};

        # Add custom logic for serving files
        my $file_path = "/path/to/static/files/$file";
        if (-e $file_path) {
            $app->send_file($file_path);
        } else {
            $app->send_error('File not found', 404);
        }
    };
}

sub register {
    my ($self, $app) = @_;
    $app->add_route(
        method => $_,
        regexp => $self->regexp,
        code   => $self->code,
    ) for $self->methods;
}

1;

This handler will serve static files from the specified directory, but it also checks if the file exists before serving it. Safety first, bestie. πŸ™ˆ


πŸ‘‘ Writing A Dancer2 Plugin

Plugins in Dancer2 are reusable components that extend your app's functionality. They're often used for stuff like authentication, database management, or form validation. Little helpers that carry the whole app. 🫢

All plugins must consume the Dancer2::Core::Role::Plugin role.

🌸 Example: Custom Dancer2 Plugin

package Dancer2::Plugin::MyPlugin;
use Dancer2::Plugin;

register 'greet' => sub {
    my ($dsl, $name) = @_;
    return "Hello, $name! Welcome to Danceyland!";
};

register_plugin;

In this example, a greet keyword is created, and it can be called within any Dancer2 route to display a greeting. To use the plugin, just include it in your app:

use Dancer2::Plugin::MyPlugin;

get '/hello/:name' => sub {
    return greet( route_parameters->get('name') );
};

πŸ”₯ Custom Session Storage Mechanisms

Dancer2 lets you define your own custom session storage mechanism by implementing the Dancer2::Core::Role::SessionFactory role. Super useful if you need to store session data in a format or storage medium that isn't supported out-of-the-box β€” like a proprietary database or an external service. Go off. πŸ’…

πŸ’– Example: Custom Session Storage

Here's how you can create a custom session storage engine that stores session data in a simple hash in memory. In practice, you'd likely store data in a more robust medium like a database or external cache. (Like, genuinely. The hash is cute but that's it. 😭)

package Dancer2::Session::MySessionStorage;
use Moo;
with 'Dancer2::Core::Role::SessionFactory';

# Simple in-memory session store (not suitable for production use)
my %session_store;

sub retrieve {
    my ($self, $id) = @_;
    return $session_store{$id};
}

sub create {
    my ($self, $data) = @_;
    my $session_id = $self->generate_session_id;
    $session_store{$session_id} = $data;
    return $session_id;
}

sub destroy {
    my ($self, $id) = @_;
    delete $session_store{$id};
}

sub flush {
    my ($self, $id, $data) = @_;
    $session_store{$id} = $data;
}

1;

⭐ Using the Custom Session Storage

To use your custom session storage mechanism, configure it in your config.yml file:

session: "MySessionStorage"

This simple example uses an in-memory hash to store sessions, but you can adapt it to any storage medium, such as Redis, MongoDB, or a relational database. Be sure to implement locking mechanisms and persistence for production usage. 🫢

⚠️ Real talk: that in-memory hash is not suitable for production use. Locking mechanisms and persistence are non-negotiable for the real thing, bestie. Don't skip that step. πŸ’€

πŸ¦‹ Custom Middleware πŸ¦‹

Okay bestie, this is the part where you get to ✨intercept✨ stuff. Middleware is code that runs before or after the core request handler in Dancer2. It lets you intercept, modify, or even short-circuit the request/response cycle before it ever reaches your app's route handlers β€” or after they hand back a response. It's giving bouncer at the club, but make it code. πŸ’…

🌸 How Middleware Works 🌸

When a request comes in, middleware runs in a predefined order:

  1. Before the app handler is executed (the "before" stage).
  2. The app's route handlers process the request.
  3. After the app handler processes the request and returns a response (the "after" stage).

Middleware gives you the power to modify the request before it gets passed to the app handler, or to change the response after it's been generated. You can also stop the app handler from running at all and return a custom response straight from the middleware. Iconic behavior, honestly. πŸ‘‘


πŸŽ€ Example: Custom Middleware πŸŽ€

Here's an example of custom middleware that runs before and after the app handler. It logs the incoming request, processes the app's routes, and then modifies the response by appending a footer message:

package Dancer2::Middleware::MyCustomMiddleware;
use Plack::Middleware;
use parent 'Plack::Middleware';

sub call {
    my ($self, $env) = @_;

    # BEFORE the app handler: Log the request method and path
    warn "Incoming request: $env->{REQUEST_METHOD} $env->{PATH_INFO}";

    # Call the app handler (if you want the app to continue processing)
    my $res = $self->app->($env);

    # AFTER the app handler: Modify the response (e.g., add a footer)
    return sub {
        my $respond = shift;
        my $writer = $respond->(
            [
                $res->[0],    # HTTP status code
                $res->[1],    # HTTP headers
                $res->[2],    # HTTP body
            ]
        );

        # Append a footer to the response body
        $writer->write("\n-- Thank you for visiting Danceyland!");
        $writer->close;
    };
}

1;

🌈 Using the Custom Middleware 🌈

To enable this middleware, modify your app.psgi file to use it with Dancer2's built-in support for Plack middleware:

use Dancer2;
use MyApp;

builder {
    enable 'Dancer2::Middleware::MyCustomMiddleware';
    MyApp->to_app;
};

πŸ’œ How Middleware Can Control the Flow πŸ’œ

In the example above, the middleware logs the request before it reaches the app and modifies the response after the app handler runs. But however, if you don't want to call the app handler β€” say, to short-circuit the request and return a custom response β€” you can skip the call to "$self->app->($env)" and return a response directly from the middleware:

sub call {
    my ($self, $env) = @_;

    # If the request matches a certain condition, bypass the app handler
    if ($env->{PATH_INFO} =~ m{/secret}) {
        return [403, ['Content-Type' => 'text/plain'], ["Forbidden"]];
    }

    # Otherwise, continue to the app handler
    my $res = $self->app->($env);

    # Modify the response as needed
    ...
}

In this case, if the request path contains "/secret", the middleware returns a 403 Forbidden response, skipping the app handler entirely. No notes. 🚫✨

🧚 Order of Operations 🧚

Middleware executes in this order, bestie:

  • Any code in the "before" stage is executed before your app processes the request. You can modify or reject the request here.
  • Your app processes the request and generates a response.
  • Any code in the "after" stage is executed after the response has been generated. You can modify or append to the response here before it's sent to the client.

Custom middleware provides great flexibility for pre- and post-processing requests and responses in your Dancer2 app. Slay. 🫢


πŸ‘‘ AUTHOR πŸ‘‘

Dancer Core Developers


This software is copyright (c) 2026 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


And that's a wrap on the whole page, bestie! πŸŽ‰ This was part two of two, and the footer says it all: perl v5.42.3, dated 2026-09-20, straight from the Dancer2...tending(3) page in the User Contributed Perl Documentation collection. Go build something cute. πŸ’…πŸŒΈ
πŸ“¦ where this page comes from