Dancer - lightweight yet powerful web application framework


    use Dancer;

    get '/hello/:name' => sub {
        return "Why, hello there " . param('name');


The above is a basic but functional web app created with Dancer. If you want to see more examples and get up and running quickly, check out the Dancer::Introduction and the Dancer::Cookbook. For examples on deploying your Dancer applications, see Dancer::Deployment.


Dancer is a web application framework designed to be as effortless as possible for the developer, taking care of the boring bits as easily as possible, yet staying out of your way and letting you get on with writing your code.

Dancer aims to provide the simplest way for writing web applications, and offers the flexibility to scale between a very simple lightweight web service consisting of a few lines of code in a single file, all the way up to a more complex fully-fledged web application with session support, templates for views and layouts, etc.

If you don't want to write CGI scripts by hand, and find Catalyst too big or cumbersome for your project, Dancer is what you need.

Dancer has few pre-requisites, so your Dancer webapps will be easy to deploy.

Dancer apps can be used with a an embedded web server (great for easy testing), and can run under PSGI/Plack for easy deployment in a variety of webserver environments.


This documentation describes all the exported symbols of Dancer. If you want a quick start guide to discover the framework, you should look at Dancer::Introduction, or Dancer::Tutorial to learn by example.

If you want to have specific examples of code for real-life problems, see the Dancer::Cookbook.

If you want to see configuration examples of different deployment solutions involving Dancer and Plack, see Dancer::Deployment.

You can find out more about the many useful plugins available for Dancer in Dancer::Plugins.


By default, use Dancer exports all the functions below plus sets up your app. You can control the exporting through the normal Exporter mechanism. For example:

    # Just export the route controllers
    use Dancer qw(before after get post);

    # Export everything but pass to avoid clashing with Test::More
    use Test::More;
    use Dancer qw(!pass);

There are also some special tags to control exports and behaviour.


This will export everything except functions which clash with Moose. Currently these are after and before.


This tells Dancer to just export symbols and not set up your app. This is most useful for writing Dancer code outside of your main route handler.


This will export everything except functions which clash with commonly used testing modules. Currently these are pass.

It can be combined with other export pragmas. For example, while testing...

    use Test::More;
    use Dancer qw(:syntax :tests);

    # Test::Most also exports "set" and "any"
    use Test::Most;
    use Dancer qw(:syntax :tests !set !any);

    # Alternatively, if you want to use Dancer's set and any...
    use Test::Most qw(!set !any);
    use Dancer qw(:syntax :tests);


This will export all the keywords, and will also load the configuration.

This is useful when you want to use your Dancer application from a script.

    use MyApp;
    use Dancer ':script';

By default, the warnings pragma will also be exported, meaning your app/script will be running under use warnings. If you do not want this, set the import_warnings setting to a false value.



Add a hook at the after position:

    after sub {
        my $response = shift;
        # do something with request

The anonymous function which is given to after will be executed after having executed a route.

You can define multiple after filters, using the after helper as many times as you wish; each filter will be executed, in the order you added them.


Defines a route for multiple HTTP methods at once:

    any ['get', 'post'] => '/myaction' => sub {
        # code

Or even, a route handler that would match any HTTP methods:

    any '/myaction' => sub {
        # code


Defines a before filter:

    before sub {
        # do something with request, vars or params

The anonymous function given to before will be executed before executing a route handler to handle the request.

If the function modifies the request's path_info or method, a new search for a matching route is performed and the filter is re-executed. Considering that this can lead to an infinite loop, this mechanism is stopped after 10 times with an exception.

The before filter can set a response with a redirection code (either 301 or 302): in this case the matched route (if any) will be ignored and the redirection will be performed immediately.

You can define multiple before filters, using the before helper as many times as you wish; each filter will be executed in the order you added them.


Defines a before_template filter:

    before_template sub {
        my $tokens = shift;
        # do something with request, vars or params
        # for example, adding a token to the template
        $tokens->{token_name} = "some value";

The anonymous function which is given to before_template will be executed before sending data and tokens to the template. Receives a HashRef of the tokens that will be inserted into the template.

This filter works as the before and after filter.

Now the preferred way for this is to use hooks (namely, the before_template one). Check hook documentation below.


Accesses cookies values, it returns a HashRef of Dancer::Cookie objects:

    get '/some_action' => sub {
        my $cookie = cookies->{name};
        return $cookie->value;

In the case you have stored something else than a Scalar in your cookie:

    get '/some_action' => sub {
        my $cookie = cookies->{oauth};
        my %values = $cookie->value;
        return ($values{token}, $values{token_secret});

Accesses a cookie value (or sets it). Note that this method will eventually be preferred over set_cookie.

    cookie lang => "fr-FR";              # set a cookie and return its value
    cookie lang => "fr-FR", expires => "2 hours";   # extra cookie info
    cookie "lang"                        # return a cookie value

If your cookie value is a key/value URI string, like


cookie will only return the first part (token=ABC) if called in scalar context. Use list context to fetch them all:

    my @values = cookie "name";


Accesses the configuration of the application:

    get '/appname' => sub {
        return "This is " . config->{appname};


Sets the content-type rendered, for the current route handler:

    get '/cat/:txtfile' => sub {
        content_type 'text/plain';

        # here we can dump the contents of param('txtfile')

You can use abbreviations for content types. For instance:

    get '/svg/:id' => sub {
        content_type 'svg';

        # here we can dump the image with id param('id')

Note that if you want to change the default content-type for every route, you have to change the content_type setting instead.


Alias for the start keyword.


Logs a message of debug level:

    debug "This is a debug message";

See Dancer::Logger for details on how to configure where log messages go.


Returns the dirname of the path given:

    my $dir = dirname($some_path);


Given a namespace, returns the current engine object

    my $template_engine = engine 'template';
    my $html = $template_engine->apply_renderer(...);


Logs a message of error level:

    error "This is an error message";

See Dancer::Logger for details on how to configure where log messages go.


Constant that returns a false value (0).


Runs an internal redirect of the current request to another request. This helps you avoid having to redirect the user using HTTP and set another request to your application.

It effectively lets you chain routes together in a clean manner.

    get qr{ /demo/articles/(.+) }x => sub {
        my ($article_id) = splat;

        # you'll have to implement this next sub yourself :)

        forward '/articles/$article_id';

In the above example, the users that reach /demo/articles/30 will actually reach /articles/30 but we've changed the database to demo before.

This is pretty cool because it lets us retain our paths and offer a demo database by merely going to /demo/....

You'll notice that in the example we didn't indicate whether it was GET or POST. That is because forward chains the same type of route the user reached. If it was a GET, it will remain a GET.

Broader functionality might be added in the future.

It is important to note that issuing a forward by itself does not exit and forward immediately, forwarding is deferred until after the current route or filter has been processed. To exit and forward immediately, use the return function, e.g.

    get '/some/path => sub {
        if ($condition) {
            return forward '/articles/$article_id';


You probably always want to use return with forward.

Note that forward doesn't parse GET arguments. So, you can't use something like:

     return forward '/home?authorized=1';

But forward supports an optional HashRef with parameters to be added to the actual parameters:

     return forward '/home', { authorized => 1 };

Finally, you can add some more options to the forward method, in a third argument, also as a HashRef. That option is currently only used to change the method of your request. Use with caution.

    return forward '/home', { auth => 1 }, { method => 'POST' };

from_dumper ($structure)

Deserializes a Data::Dumper structure.

from_json ($structure, %options)

Deserializes a JSON structure. Can receive optional arguments. Those arguments are valid JSON arguments to change the behaviour of the default JSON::from_json function.

from_yaml ($structure)

Deserializes a YAML structure.

from_xml ($structure, %options)

Deserializes a XML structure. Can receive optional arguments. These arguments are valid XML::Simple arguments to change the behaviour of the default XML::Simple::XMLin function.


Defines a route for HTTP GET requests to the given path:

    get '/' => sub {
        return "Hello world";

Note that a route to match HEAD requests is automatically created as well.


Sets a response object with the content given.

When used as a return value from a filter, this breaks the execution flow and renders the response immediately:

    before sub {
        if ($some_condition) {
            return halt("Unauthorized");

    get '/' => sub {
        "hello there";


Adds custom headers to responses:

    get '/send/headers', sub {
        headers 'X-Foo' => 'bar', X-Bar => 'foo';

adds a custom header to response:

    get '/send/header', sub {
        header 'x-my-header' => 'shazam!';

Note that it will overwrite the old value of the header, if any. To avoid that, see "push_header".


Do the same as header, but allow for multiple headers with the same name.

    get '/send/header', sub {
        push_header 'x-my-header' => '1';
        push_header 'x-my-header' => '2';
        will result in two headers "x-my-header" in the response


Adds a hook at some position. For example :

  hook before_serializer => sub {
    my $response = shift;
    $response->content->{generated_at} = localtime();

There can be multiple hooks assigned to a given position, and each will be executed in order.

(For details on how to register new hooks from within plugins, see Dancer::Hook.) Supported before hooks (in order of execution):


This hook receives no arguments.

  hook before_deserializer => sub {

This hook receives as argument the path of the file to render.

  hook before_file_render => sub {
    my $path = shift;

This hook receives as argument a Dancer::Error object.

  hook before_error_init => sub {
    my $error = shift;

This hook receives as argument a Dancer::Error object.

  hook before_error_render => sub {
    my $error = shift;

This is an alias to before.

This hook receives no arguments.

  before sub {

is equivalent to

  hook before => sub {

This is an alias to 'before_template'.

This hook receives as argument a HashRef, containing the tokens that will be passed to the template. You can use it to add more tokens, or delete some specific token.

  hook before_template_render => sub {
    my $tokens = shift;
    delete $tokens->{user};
    $tokens->{time} = localtime;

is equivalent to

  hook before_template => sub {
    my $tokens = shift;
    delete $tokens->{user};
    $tokens->{time} = localtime;

This hook receives two arguments. The first one is a HashRef containing the tokens. The second is a ScalarRef representing the content of the template.

  hook before_layout_render => sub {
    my ($tokens, $html_ref) = @_;

This hook receives as argument a Dancer::Response object.

  hook before_serializer => sub {
    my $response = shift;
    $response->content->{start_time} = time();

Supported after hooks (in order of execution):


This hook receives no arguments.

  hook after_deserializer => sub {

This hook receives as argument a Dancer::Response object.

  hook after_file_render => sub {
    my $response = shift;

This hook receives as argument a ScalarRef representing the content generated by the template.

  hook after_template_render => sub {
    my $html_ref = shift;

This hook receives as argument a ScalarRef representing the content generated by the layout

  hook after_layout_render => sub {
    my $html_ref = shift;

This is an alias for 'after'.

This hook receives as argument a Dancer::Response object.

  hook after => sub {
    my $response = shift;

This is equivalent to

  after sub {
    my $response = shift;

This hook receives as argument a Dancer::Response object.

  hook after_error_render => sub {
    my $response = shift;


This method is deprecated. Use set:

    set layout => 'user';


Deprecated. Use <set logger = 'console'>> to change current logger engine.


Loads one or more perl scripts in the current application's namespace. Syntactic sugar around Perl's require:

    load '', '';


Loads a Dancer package. This method sets the libdir to the current ./lib directory:

    # if we have lib/, we can load it like:
    load_app 'Webapp';
    # or with options
    load_app 'Forum', prefix => '/forum', settings => {foo => 'bar'};

Note that the package loaded using load_app must import Dancer with the :syntax option.

To load multiple apps repeat load_app:

    load_app 'one';
    load_app 'two';

The old way of loading multiple apps in one go (load_app 'one', 'two';) is deprecated.


Deprecated. See "mime".


Shortcut to access the instance object of Dancer::MIME. You should read the Dancer::MIME documentation for full details, but the most commonly-used methods are summarized below:

    # set a new mime type
    mime->add_type( foo => 'text/foo' );

    # set a mime type alias
    mime->add_alias( f => 'foo' );

    # get mime type for an alias
    my $m = mime->for_name( 'f' );

    # get mime type for a file (based on extension)
    my $m = mime->for_file( "" );

    # get current defined default mime type
    my $d = mime->default;

    # set the default mime type using config.yml
    # or using the set keyword
    set default_mime_type => 'text/plain';


This method should be called from a route handler. It's an alias for the Dancer::Request params accessor. It returns an hash reference to all defined parameters. Check param bellow to access quickly to a single parameter value.


This method should be called from a route handler. This method is an accessor to the parameters hash table.

   post '/login' => sub {
       my $username = param "user";
       my $password = param "pass";
       # ...


This method should be called from a route handler. Tells Dancer to pass the processing of the request to the next matching route.

You should always return after calling pass:

    get '/some/route' => sub {
        if (...) {
            # we want to let the next matching route handler process this one
            return pass();


Concatenates multiple paths together, without worrying about the underlying operating system:

    my $path = path(dirname($0), 'lib', '');

It also normalizes (cleans) the path aesthetically. It does not verify the path exists.


Defines a route for HTTP POST requests to the given URL:

    post '/' => sub {
        return "Hello world";


Defines a prefix for each route handler, like this:

    prefix '/home';

From here, any route handler is defined to /home/*:

    get '/page1' => sub {}; # will match '/home/page1'

You can unset the prefix value:

    prefix undef;
    get '/page1' => sub {}; will match /page1

For a safer alternative you can use lexical prefix like this:

    prefix '/home' => sub {
        ## Prefix is set to '/home' here

        get ...;
        get ...;
    ## prefix reset to the previous version here

This makes it possible to nest prefixes:

   prefix '/home' => sub {
       ## some routes
      prefix '/private' => sub {
         ## here we are under /home/private...

         ## some more routes
      ## back to /home
   ## back to the root

Notice: once you have a prefix set, do not add a caret to the regex:

    prefix '/foo';
    get qr{^/bar} => sub { ... } # BAD BAD BAD
    get qr{/bar}  => sub { ... } # Good!


Defines a route for HTTP DELETE requests to the given URL:

    del '/resource' => sub { ... };


Defines a route for HTTP OPTIONS requests to the given URL:

    options '/resource' => sub { ... };


Defines a route for HTTP PUT requests to the given URL:

    put '/resource' => sub { ... };


Generates a HTTP redirect (302). You can either redirect to a complete different site or within the application:

    get '/twitter', sub {
        redirect '';

You can also force Dancer to return a specific 300-ish HTTP response code:

    get '/old/:resource', sub {
        redirect '/new/'.params->{resource}, 301;

It is important to note that issuing a redirect by itself does not exit and redirect immediately, redirection is deferred until after the current route or filter has been processed. To exit and redirect immediately, use the return function, e.g.

    get '/restricted', sub {
        return redirect '/login' if accessDenied();
        return 'Welcome to the restricted section';


Allows a handler to provide plain HTML (or other content), but have it rendered within the layout still.

This method is DEPRECATED, and will be removed soon. Instead, you should be using the engine keyword:

    get '/foo' => sub {
        # Do something which generates HTML directly (maybe using
        # HTML::Table::FromDatabase or something)
        my $content = ...;

        # get the template engine
        my $template_engine = engine 'template';

        # apply the layout (not the renderer), and return the result

It works very similarly to template in that you can pass tokens to be used in the layout, and/or options to control the way the layout is rendered. For instance, to use a custom layout:

    render_with_layout $content, {}, { layout => 'layoutname' };


Returns a Dancer::Request object representing the current request.

See the Dancer::Request documention for the methods you can call, for example:

    request->referer;         # value of the HTTP referer header
    request->remote_address;  # user's IP address
    request->user_agent;      # User-Agent header value


Returns a HTTP error. By default the HTTP code returned is 500:

    get '/photo/:id' => sub {
        if (...) {
            send_error("Not allowed", 403);
        } else {
           # return content

This will not cause your route handler to return immediately, so be careful that your route handler doesn't then override the error. You can avoid that by saying return send_error(...) instead.


Lets the current route handler send a file to the client. Note that the path of the file must be relative to the public directory unless you use the system_path option (see below).

    get '/download/:file' => sub {
        return send_file(params->{file});

The content-type will be set depending on the current MIME types definition (see mime if you want to define your own).

If your filename does not have an extension, or you need to force a specific mime type, you can pass it to send_file as follows:

    return send_file(params->{file}, content_type => 'image/png');

Also, you can use your aliases or file extension names on content_type, like this:

    return send_file(params->{file}, content_type => 'png');

For files outside your public folder, you can use the system_path switch. Just bear in mind that its use needs caution as it can be dangerous.

   return send_file('/etc/passwd', system_path => 1);

If you have your data in a scalar variable, send_file can be useful as well. Pass a reference to that scalar, and send_file will behave as if there was a file with that contents:

   return send_file( \$data, content_type => 'image/png' );

Note that Dancer is unable to guess the content type from the data contents. Therefore you might need to set the content_type properly. For this kind of usage an attribute named filename can be useful. It is used as the Content-Disposition header, to hint the brower about the filename it should use.

   return send_file( \$data, content_type => 'image/png'
                             filename     => 'onion.png' );

Note that you should always use return send_file ... to stop execution of your route handler at that point.


Defines a setting:

    set something => 'value';

You can set more than one value at once:

    set something => 'value', otherthing => 'othervalue';


Returns the value of a given setting:

    setting('something'); # 'value'

Creates or updates cookie values:

    get '/some_action' => sub {
        set_cookie name => 'value',
                   expires => (time + 3600),
                   domain  => '';

In the example above, only 'name' and 'value' are mandatory.

You can also store more complex structure in your cookies:

    get '/some_auth' => sub {
        set_cookie oauth => {
            token        => $twitter->request_token,
            token_secret => $twitter->secret_token,

You can't store more complex structure than this. All keys in the HashRef should be Scalars; storing references will not work.

See Dancer::Cookie for further options when creating your cookie.

Note that this method will be eventually deprecated in favor of the new cookie method.


Provides access to all data stored in the user's session (if any).

It can also be used as a setter to store data in the session:

    # getter example
    get '/user' => sub {
        if (session('user')) {
            return "Hello, ".session('user')->name;

    # setter example
    post '/user/login' => sub {
        if ($logged_in) {
            session user => $user;

You may also need to clear a session:

    # destroy session
    get '/logout' => sub {

If you need to fetch the session ID being used for any reason:

    my $id = session->id;


Returns the list of captures made from a route handler with a route pattern which includes wildcards:

    get '/file/*.*' => sub {
        my ($file, $extension) = splat;

There is also the extensive splat (A.K.A. "megasplat"), which allows extensive greedier matching, available using two asterisks. The additional path is broken down and returned as an ArrayRef:

    get '/entry/*/tags/**' => sub {
        my ( $entry_id, $tags ) = splat;
        my @tags = @{$tags};

This helps with chained actions:

    get '/team/*/**' => sub {
        my ($team) = splat;
        var team => $team;

    prefix '/team/*';

    get '/player/*' => sub {
        my ($player) = splat;

        # etc...

    get '/score' => sub {
        return score_for( vars->{'team'} );


Starts the application or the standalone server (depending on the deployment choices).

This keyword should be called at the very end of the script, once all routes are defined. At this point, Dancer takes over control.


Changes the status code provided by an action. By default, an action will produce an HTTP 200 OK status code, meaning everything is OK:

    get '/download/:file' => {
        if (! -f params->{file}) {
            status 'not_found';
            return "File does not exist, unable to download";
        # serving the file...

In that example, Dancer will notice that the status has changed, and will render the response accordingly.

The status keyword receives either a numeric status code or its name in lower case, with underscores as a separator for blanks - see the list in "HTTP CODES" in Dancer::HTTP.


Tells the route handler to build a response with the current template engine:

    get '/' => sub {
        template 'some_view', { token => 'value'};

The first parameter should be a template available in the views directory, the second one (optional) is a HashRef of tokens to interpolate, and the third (again optional) is a HashRef of options.

For example, to disable the layout for a specific request:

    get '/' => sub {
        template '', {}, { layout => undef };

Some tokens are automatically added to your template (perl_version, dancer_version, settings, request, params, vars and, if you have sessions enabled, session). Check Dancer::Template::Abstract for further details.

to_dumper ($structure)

Serializes a structure with Data::Dumper.

to_json ($structure, %options)

Serializes a structure to JSON. Can receive optional arguments. Thoses arguments are valid JSON arguments to change the behaviour of the default JSON::to_json function.

to_yaml ($structure)

Serializes a structure to YAML.

to_xml ($structure, %options)

Serializes a structure to XML. Can receive optional arguments. Thoses arguments are valid XML::Simple arguments to change the behaviour of the default XML::Simple::XMLout function.


Constant that returns a true value (1).


Provides access to file uploads. Any uploaded file is accessible as a Dancer::Request::Upload object. You can access all parsed uploads via:

    post '/some/route' => sub {
        my $file = upload('file_input_foo');
        # file is a Dancer::Request::Upload object

If you named multiple input of type "file" with the same name, the upload keyword will return an Array of Dancer::Request::Upload objects:

    post '/some/route' => sub {
        my ($file1, $file2) = upload('files_input');
        # $file1 and $file2 are Dancer::Request::Upload objects

You can also access the raw HashRef of parsed uploads via the current request object:

    post '/some/route' => sub {
        my $all_uploads = request->uploads;
        # $all_uploads->{'file_input_foo'} is a Dancer::Request::Upload object
        # $all_uploads->{'files_input'} is an ArrayRef of Dancer::Request::Upload objects

Note that you can also access the filename of the upload received via the params keyword:

    post '/some/route' => sub {
        # params->{'files_input'} is the filename of the file uploaded

See Dancer::Request::Upload for details about the interface provided.


Returns a fully-qualified URI for the given path:

    get '/' => sub {
        redirect uri_for('/path');
        # can be something like: http://localhost:3000/path


Returns a reference to a copy of %+, if there are named captures in the route Regexp.

Named captures are a feature of Perl 5.10, and are not supported in earlier versions:

    get qr{
        / (?<object> user   | ticket | comment )
        / (?<action> delete | find )
        / (?<id> \d+ )
    , sub {
        my $value_for = captures;
        "i don't want to $$value_for{action} the $$value_for{object} $$value_for{id} !"


Defines a variable shared between filters and route handlers.

    before sub {
        var foo => 42;

Route handlers and other filters will be able to read that variable with the vars keyword.


Returns the HashRef of all shared variables set during the filter/route chain:

    get '/path' => sub {
        if (vars->{foo} eq 42) {


Logs a warning message through the current logger engine:

    warning "This is a warning";

See Dancer::Logger for details on how to configure where log messages go.


This module has been written by Alexis Sukrieh <> and others, see the AUTHORS file that comes with this distribution for details.


The source code for this module is hosted on GitHub Feel free to fork the repository and submit pull requests! (See Dancer::Development for details on how to contribute).

Also, why not watch the repo to keep up to date with the latest upcoming changes?


The Dancer development team can be found on #dancer on irc://

If you don't have an IRC client installed/configured, there is a simple web chat client at for you.

There is also a Dancer users mailing list available - subscribe at:

If you'd like to contribute to the Dancer project, please see for all the ways you can help!


The following modules are mandatory (Dancer cannot run without them):


The following modules are optional:

JSON : needed to use JSON serializer
Plack : in order to use PSGI
Template : in order to use TT for rendering views
XML::Simple and XML:SAX or XML:Parser for XML serialization
YAML : needed for configuration file support


This module is free software and is published under the same terms as Perl itself.


Main Dancer web site:

The concept behind this module comes from the Sinatra ruby project, see for details.