Mojolicious - The Web In A Box!


  # Mojolicious application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Routes
    my $r = $self->routes;

    # Default route

  # Mojolicious controller
  package MyApp::Foo;
  use Mojo::Base 'Mojolicious::Controller';

  # Say hello
  sub welcome {
    my $self = shift;
    $self->render(text => 'Hi there!');

  # Say goodbye from a template (foo/bye.html.ep)
  sub bye { shift->render }


Back in the early days of the web there was this wonderful Perl library called CGI, many people only learned Perl because of it. It was simple enough to get started without knowing much about the language and powerful enough to keep you going, learning by doing was much fun. While most of the techniques used are outdated now, the idea behind it is not. Mojolicious is a new attempt at implementing this idea using state of the art technology.


  • An amazing MVC web framework supporting a simplified single file mode through Mojolicious::Lite.

      Powerful out of the box with RESTful routes, plugins, Perl-ish templates, session management, signed cookies, testing framework, static file server, I18N, first class unicode support and much more for you to discover.

  • Very clean, portable and Object Oriented pure Perl API without any hidden magic and no requirements besides Perl 5.8.7.

  • Full stack HTTP 1.1 and WebSocket client/server implementation with IPv6, TLS, Bonjour, IDNA, Comet (long polling), chunking and multipart support.

  • Builtin async IO web server supporting epoll, kqueue, UNIX domain sockets and hot deployment, perfect for embedding.

  • Automatic CGI, FastCGI and PSGI detection.

  • JSON and XML/HTML5 parser with CSS3 selector support.

  • Fresh code based upon years of experience developing Catalyst.

Duct Tape For The HTML5 Web

Web development for humans, making hard things possible and everything fun.

  use Mojolicious::Lite;

  # Simple route with plain text response
  get '/hello' => sub { shift->render(text => 'Hello World!') };

  # Route to template in DATA section
  get '/time' => 'clock';

  # RESTful web service sending JSON responses
  get '/:offset' => sub {
    my $self   = shift;
    my $offset = $self->param('offset') || 23;
    $self->render(json => {list => [0 .. $offset]});

  # Scrape information from remote sites
  post '/title' => sub {
    my $self = shift;
    my $url  = $self->param('url') || '';
    $self->render(text =>
      $self->ua->get($url)->res->dom->at('head > title')->text);

  # WebSocket echo service
  websocket '/echo' => sub {
    my $self = shift;
    $self->on_message(sub {
      my ($self, $message) = @_;
      $self->send_message("echo: $message");


  @@ clock.html.ep
  % my ($second, $minute, $hour) = (localtime(time))[0, 1, 2];
  <%= link_to clock => begin %>
    The time is <%= $hour %>:<%= $minute %>:<%= $second %>.
  <% end %>

To run this example with the built in development server just put the code into a file and execute it with perl.

  % perl daemon
  Server available at


Single file prototypes like the one above can easily grow into well structured applications.

  package MyApp;
  use Mojo::Base 'Mojolicious';

  # Runs once on application startup
  sub startup {
    my $self = shift;
    my $r    = $self->routes;

    # Route prefix for "MyApp::Example" controller
    my $example = $r->route('/example')->to('example#');

    # GET routes connecting the controller prefix with actions

    # All common verbs are supported

    # And much more


Bigger applications are a lot easier to maintain once routing information has been separated from action code, especially when working in teams.

  package MyApp::Example;
  use Mojo::Base 'Mojolicious::Controller';

  # Plain text response
  sub hello { shift->render(text => 'Hello World!') }

  # Render external template "templates/example/clock.html.ep"
  sub clock { shift->render }

  # RESTful web service sending JSON responses
  sub restful {
    my $self   = shift;
    my $offset = $self->param('offset') || 23;
    $self->render(json => {list => [0 .. $offset]});

  # Scrape information from remote sites
  sub title {
    my $self = shift;
    my $url  = $self->param('url') || '';
    $self->render(text =>
      $self->ua->get($url)->res->dom->at('head > title')->text);


While the application class is unique, you can have as many controllers as you like.

  package MyApp::Realtime;
  use Mojo::Base 'Mojolicious::Controller';

  # WebSocket echo service
  sub echo {
    my $self = shift;
    $self->on_message(sub {
      my ($self, $message) = @_;
      $self->send_message("echo: $message");


Action code and templates can stay almost exactly the same, everything was designed from the ground up for this very unique and fun workflow.

  % my ($second, $minute, $hour) = (localtime(time))[0, 1, 2];
  <%= link_to clock => begin %>
    The time is <%= $hour %>:<%= $minute %>:<%= $second %>.
  <% end %>

Have Some Cake

Loosely coupled building blocks, use what you like and just ignore the rest.

  |                                                               |
  |                .----------------------------------------------'
  |                | .--------------------------------------------.
  |   Application  | |              Mojolicious::Lite             |
  |                | '--------------------------------------------'
  |                | .--------------------------------------------.
  |                | |                 Mojolicious                |
  '----------------' '--------------------------------------------'
  |                             Mojo                              |
  .-------. .-----------. .--------. .------------. .-------------.
  |  CGI  | |  FastCGI  | |  PSGI  | |  HTTP 1.1  | |  WebSocket  |
  '-------' '-----------' '--------' '------------' '-------------'

For more documentation see Mojolicious::Guides and the tutorial in Mojolicious::Lite!


Mojolicious inherits all attributes from Mojo and implements the following new ones.


  my $class = $app->controller_class;
  $app      = $app->controller_class('Mojolicious::Controller');

Class to be used for the default controller, defaults to Mojolicious::Controller.


  my $mode = $app->mode;
  $app     = $app->mode('production');

The operating mode for your application. It defaults to the value of the environment variable MOJO_MODE or development. Mojo will name the log file after the current mode and modes other than development will result in limited log output.

If you want to add per mode logic to your application, you can add a sub to your application named $mode_mode.

  sub development_mode {
    my $self = shift;

  sub production_mode {
    my $self = shift;


  my $process = $app->on_process;
  $app        = $app->on_process(sub {...});

Request processing callback, defaults to calling the dispatch method. Generally you will use a plugin or controller instead of this, consider it the sledgehammer in your toolbox.

  $app->on_process(sub {
    my ($self, $c) = @_;


  my $plugins = $app->plugins;
  $app        = $app->plugins(Mojolicious::Plugins->new);

The plugin loader, by default a Mojolicious::Plugins object. You can usually leave this alone, see Mojolicious::Plugin if you want to write a plugin.


  my $renderer = $app->renderer;
  $app         = $app->renderer(Mojolicious::Renderer->new);

Used in your application to render content, by default a Mojolicious::Renderer object. The two main renderer plugins Mojolicious::Plugin::EpRenderer and Mojolicious::Plugin::EplRenderer contain more specific information.


  my $routes = $app->routes;
  $app       = $app->routes(Mojolicious::Routes->new);

The routes dispatcher, by default a Mojolicious::Routes object. You use this in your startup method to define the url endpoints for your application.

  sub startup {
    my $self = shift;

    my $r = $self->routes;


  my $secret = $app->secret;
  $app       = $app->secret('passw0rd');

A secret passphrase used for signed cookies and the like, defaults to the application name which is not very secure, so you should change it!!! As long as you are using the unsecure default there will be debug messages in the log file reminding you to change your passphrase.


  my $sessions = $app->sessions;
  $app         = $app->sessions(Mojolicious::Sessions->new);

Simple singed cookie based sessions, by default a Mojolicious::Sessions object.


  my $static = $app->static;
  $app       = $app->static(Mojolicious::Static->new);

For serving static assets from your public directory, by default a Mojolicious::Static object.


  my $types = $app->types;
  $app      = $app->types(Mojolicious::Types->new);

Responsible for tracking the types of content you want to serve in your application, by default a Mojolicious::Types object. You can easily register new types.

  $app->types->type(twitter => 'text/tweet');


Mojolicious inherits all methods from Mojo and implements the following new ones.


  my $app = Mojolicious->new;

Construct a new Mojolicious application. Will automatically detect your home directory and set up logging based on your current operating mode. Also sets up the renderer, static dispatcher and a default set of plugins.


  my $defaults = $app->defaults;
  my $foo      = $app->defaults('foo');
  $app         = $app->defaults({foo => 'bar'});
  $app         = $app->defaults(foo => 'bar');

Default values for the stash, assigned for every new request.

  $app->defaults->{foo} = 'bar';
  my $foo = $app->defaults->{foo};
  delete $app->defaults->{foo};



The heart of every Mojolicious application, calls the static and routes dispatchers for every request and passes them a Mojolicious::Controller object.


  $tx = $app->handler($tx);

Sets up the default controller and calls process for every request.


  $app->helper(foo => sub {...});

Add a new helper that will be available as a method of the controller object and the application object, as well as a function in ep templates.

  # Helper
  $app->helper(add => sub { $_[1] + $_[2] });

  # Controller/Application
  my $result = $self->add(2, 3);

  # Template
  <%= add 2, 3 %>


  $app->hook(after_dispatch => sub {...});

Extend Mojolicious by adding hooks to named events.

The following events are available and run in the listed order.


Triggered right after the transaction is built and before the HTTP request gets parsed. One use case would be upload progress bars. (Passed the transaction and application instances)

  $app->hook(after_build_tx => sub {
    my ($tx, $app) = @_;

Triggered right before the static and routes dispatchers start their work. Very useful for rewriting incoming requests and other preprocessing tasks. (Passed the default controller instance)

  $app->hook(before_dispatch => sub {
    my $self = shift;

Triggered after the static dispatcher determined if a static file should be served and before the routes dispatcher starts its work, the callbacks of this hook run in reverse order. Mostly used for custom dispatchers and postprocessing static file responses. (Passed the default controller instance)

  $app->hook(after_static_dispatch => sub {
    my $self = shift;

Triggered after a response has been rendered, the callbacks of this hook run in reverse order. Note that this hook can trigger before after_static_dispatch due to its dynamic nature. Useful for all kinds of postprocessing tasks. (Passed the current controller instance)

  $app->hook(after_dispatch => sub {
    my $self = shift;


  $app->plugin('something', foo => 23);
  $app->plugin('something', {foo => 23});
  $app->plugin('Foo::Bar', foo => 23);
  $app->plugin('Foo::Bar', {foo => 23});

Load a plugin.

The following plugins are included in the Mojolicious distribution as examples.


Route condition for User-Agent headers.


Change the application charset.


Perl-ish configuration files.


General purpose helper collection.


Renderer for plain embedded Perl templates.


Renderer for more sophisiticated embedded Perl templates.


Route condition for all kinds of headers.


Internationalization helpers.


JSON configuration files.


Renderer for POD files and documentation browser.


Add an X-Powered-By header to outgoing responses.


Log timing information.


Template specific helper collection.



Start the Mojolicious::Commands command line interface for your application.



This is your main hook into the application, it will be called at application startup.

  sub startup {
    my $self = shift;




  #mojo on





Mojolicious ships with a few popular static files bundled in the public directory.

Mojolicious Artwork

  Copyright (C) 2010-2011, Sebastian Riedel.

Licensed under the CC-SA License, Version 3.0


  Version 1.5.2

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

  Copyright 2011, John Resig.

Licensed under the MIT License,


  Version 21-Jul-2010

A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page.

  Copyright (C) 2006, Google Inc.

Licensed under the Apache License, Version 2.0


Every major release of Mojolicious has a code name, these are the ones that have been used in the past.

1.1, Smiling Cat Face With Heart-Shaped Eyes (u1F63B)

1.0, Snowflake (u2744)

0.999930, Hot Beverage (u2615)

0.999927, Comet (u2604)

0.999920, Snowman (u2603)


Sebastian Riedel,


Retired members of the core team, we thank you dearly for your service.

    Viacheslav Tykhanovskyi,


In alphabetical order.

    Abhijit Menon-Sen

    Adam Kennedy

    Adriano Ferreira

    Alex Salimon

    Alexey Likhatskiy

    Anatoly Sharifulin

    Andre Vieth

    Andrew Fresh

    Andreas Koenig

    Andy Grundman

    Aristotle Pagaltzis

    Ashley Dev

    Ask Bjoern Hansen

    Audrey Tang

    Ben van Staveren

    Breno G. de Oliveira

    Brian Duggan

    Burak Gursoy

    Ch Lamprecht

    Charlie Brady

    Chas. J. Owens IV

    Christian Hansen

    Curt Tilmes

    Daniel Kimsey

    Danijel Tasov

    David Davis

    Dmitriy Shalashov

    Dmitry Konstantinov

    Eugene Toropov

    Gisle Aas

    Glen Hinkle

    Graham Barr

    Hideki Yamamura

    James Duncan

    Jan Jona Javorsek

    Jaroslav Muhin

    Jesse Vincent

    John Kingsley

    Jonathan Yu

    Kazuhiro Shibuya

    Kevin Old

    KITAMURA Akatsuki

    Lars Balker Rasmussen

    Leon Brocard

    Maik Fischer

    Marcus Ramberg

    Mark Stosberg

    Matthew Lineen

    Maksym Komar

    Maxim Vuets

    Mirko Westermeier

    Mons Anderson

    Moritz Lenz

    Oleg Zhelo

    Pascal Gaudette

    Paul Tomlin

    Pedro Melo

    Peter Edwards

    Pierre-Yves Ritschard

    Quentin Carbonneaux

    Rafal Pocztarski

    Randal Schwartz

    Robert Hicks

    Ryan Jendoubi

    Sascha Kiefer

    Sergey Zasenko

    Simon Bertrang

    Shu Cho

    Stanis Trendelenburg

    Tatsuhiko Miyagawa

    The Perl Foundation

    Tomas Znamenacek

    Ulrich Habel

    Ulrich Kautz

    Uwe Voelker

    Victor Engmark

    Yaroslav Korshak

    Yuki Kimoto

    Zak B. Elep


Copyright (C) 2008-2011, Sebastian Riedel.

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.