Mojolicious::Lite - Micro Web Framework


  # Using Mojolicious::Lite will enable "strict" and "warnings"
  use Mojolicious::Lite;

  # Route with placeholder
  get '/:foo' => sub {
    my $self = shift;
    my $foo  = $self->param('foo');
    $self->render(text => "Hello from $foo!");

  # Start the Mojolicious command system


Mojolicious::Lite is a micro web framework built around Mojolicious.


A quick example driven introduction to the wonders of Mojolicious::Lite. Most of what you'll learn here also applies to normal Mojolicious applications.

Hello World!

A simple Hello World application can look like this, strict and warnings are automatically enabled and a few functions imported when you use Mojolicious::Lite, turning your script into a full featured web application.

  #!/usr/bin/env perl
  use Mojolicious::Lite;

  get '/' => sub {
    my $self = shift;
    $self->render(text => 'Hello World!');



There is also a helper command to generate a small example application.

  % mojo generate lite_app


All the normal Mojolicious command options are available from the command line. Note that CGI, FastCGI and PSGI environments can usually be auto detected and will just work without commands.

  % ./ daemon
  Server available at

  % ./ daemon --listen http://*:8080
  Server available at

  % ./ cgi
  ...CGI output...

  % ./ fastcgi
  ...Blocking FastCGI main loop...

  % ./
  ...List of available commands (or automatically detected environment)...


The app->start call that starts the Mojolicious command system can be customized to override normal @ARGV use.



Your application will automatically reload itself if you start it with the morbo development web server, so you don't have to restart the server after every change.

  % morbo
  Server available at


Routes are basically just fancy paths that can contain different kinds of placeholders. $self is an instance of Mojolicious::Controller containing both the HTTP request and response.

  # /foo
  get '/foo' => sub {
    my $self = shift;
    $self->render(text => 'Hello World!');

GET/POST Parameters

All GET and POST parameters are accessible via param.

  # /foo?user=sri
  get '/foo' => sub {
    my $self = shift;
    my $user = $self->param('user');
    $self->render(text => "Hello $user!");


The stash is used to pass data to templates, which can be inlined in the DATA section.

  # /bar
  get '/bar' => sub {
    my $self = shift;
    $self->stash(one => 23);
    $self->render('baz', two => 24);


  @@ baz.html.ep
  The magic numbers are <%= $one %> and <%= $two %>.


Mojo::Message::Request and Mojo::Message::Response give you full access to all HTTP features and information.

  # /agent
  get '/agent' => sub {
    my $self = shift;
    $self->res->headers->header('X-Bender' => 'Bite my shiny metal ass!');
    $self->render(text => $self->req->headers->user_agent);

Route Names

All routes can have a name associated with them, this allows automatic template detection and back referencing with url_for, link_to and form_for. Nameless routes get an automatically generated one assigned that is simply equal to the route itself without non-word characters.

  # /
  get '/' => 'index';

  # /hello
  get '/hello';


  @@ index.html.ep
  <%= link_to Hello => 'hello' %>.
  <%= link_to Reload => 'index' %>.

  @@ hello.html.ep
  Hello World!


Templates can have layouts.

  # /with_layout
  get '/with_layout' => sub {
    my $self = shift;


  @@ with_layout.html.ep
  % title 'Green!';
  % layout 'green';
  We've got content!

  @@ layouts/green.html.ep
  <!doctype html><html>
    <head><title><%= title %></title></head>
    <body><%= content %></body>


Template blocks can be used like normal Perl functions and are always delimited by the begin and end keywords.

  # /with_block
  get '/with_block' => 'block';


  @@ block.html.ep
  <% my $link = begin %>
    <% my ($url, $name) = @_; %>
    Try <%= link_to $url => begin %><%= $name %><% end %>!
  <% end %>
  <!doctype html><html>
    <head><title>Sebastians Frameworks!</title></head>
      <%= $link->('', 'Mojolicious') %>
      <%= $link->('', 'Catalyst') %>

Captured Content

The content_for helper can be used to pass around blocks of captured content.

  # /captured
  get '/captured' => sub {
    my $self = shift;


  @@ captured.html.ep
  % layout 'blue', title => 'Green!';
  <% content_for header => begin %>
    <meta http-equiv="Pragma" content="no-cache">
  <% end %>
  We've got content!
  <% content_for header => begin %>
    <meta http-equiv="Expires" content="-1">
  <% end %>

  @@ layouts/blue.html.ep
  <!doctype html><html>
      <title><%= title %></title>
      <%= content_for 'header' %>
    <body><%= content %></body>


You can also extend Mojolicious with your own helpers, a list of all built in ones can be found in Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.

  # "whois" helper
  helper whois => sub {
    my $self  = shift;
    my $agent = $self->req->headers->user_agent || 'Anonymous';
    my $ip    = $self->tx->remote_address;
    return "$agent ($ip)";

  # /secret
  get '/secret' => sub {
    my $self = shift;
    my $user = $self->whois;
    $self->app->log->debug("Request from $user.");


  @@ secret.html.ep
  We know who you are <%= whois %>.


Route placeholders allow capturing parts of a request path until a / or . separator occurs, results will be stored by name in the stash and param.

  # /foo/test
  # /foo/test123
  get '/foo/:bar' => sub {
    my $self = shift;
    my $bar  = $self->stash('bar');
    $self->render(text => "Our :bar placeholder matched $bar");

  # /test/foo
  # /test123/foo
  get '/(:bar)something/foo' => sub {
    my $self = shift;
    my $bar  = $self->param('bar');
    $self->render(text => "Our :bar placeholder matched $bar");

Wildcard Placeholders

Wildcard placeholders allow matching absolutely everything, including / and ..

  # /hello/test
  # /hello/test123
  # /hello/test.123/test/123
  get '/hello/*you' => sub {


  @@ groovy.html.ep
  Your name is <%= $you %>.

HTTP Methods

Routes can be restricted to specific request methods.

  # GET /bye
  get '/bye' => sub { shift->render(text => 'Bye!') };

  # POST /bye
  post '/bye' => sub { shift->render(text => 'Bye!') };

  any [qw/get post delete/] => '/bye' => sub {
    shift->render(text => 'Bye!');

  # * /baz
  any '/baz' => sub {
    my $self   = shift;
    my $method = $self->req->method;
    $self->render(text => "You called /baz with $method");

Optional Placeholders

Routes allow default values to make placeholders optional.

  # /hello
  # /hello/Sara
  get '/hello/:name' => {name => 'Sebastian'} => sub {
    my $self = shift;
    $self->render('groovy', format => 'txt');


  @@ groovy.txt.ep
  My name is <%= $name %>.

Restrictive Placeholders

The easiest way to make placeholders more restrictive are alternatives, you just make a list of possible values.

  # /test
  # /123
  any '/:foo' => [foo => [qw/test 123/]] => sub {
    my $self = shift;
    my $foo  = $self->param('foo');
    $self->render(text => "Our :foo placeholder matched $foo");

All placeholders get compiled to a regex internally, this process can also be easily customized.

  # /1
  # /123
  any '/:bar' => [bar => qr/\d+/] => sub {
    my $self = shift;
    my $bar  = $self->param('bar');
    $self->render(text => "Our :bar placeholder matched $bar");

Just make sure not to use ^ and $ or capturing groups (...), because placeholders become part of a larger regular expression internally, (?:...) is fine though.


Formats can be automatically detected by looking at file extensions.

  # /detection.html
  # /detection.txt
  get '/detection' => sub {
    my $self = shift;


  @@ detected.html.ep
  <!doctype html><html>
    <body>HTML was detected.</body>

  @@ detected.txt.ep
  TXT was detected.

Restrictive placeholders can also be used for format detection.

  # /hello.json
  # /hello.txt
  get '/hello' => [format => [qw/json txt/]] => sub {
    my $self = shift;
    return $self->render_json({hello => 'world!'})
      if $self->stash('format') eq 'json';
    $self->render_text('hello world!');


Authentication and code shared between multiple routes can be realized easily with the under statement. All following routes are only evaluated if the under callback returned a true value.

  use Mojolicious::Lite;

  # Authenticate based on name parameter
  under sub {
    my $self = shift;

    # Authenticated
    my $name = $self->param('name') || '';
    return 1 if $name eq 'Bender';

    # Not authenticated

  # / (with authentication)
  get '/' => 'index';


  @@ denied.html.ep
  You are not Bender, permission denied!

  @@ index.html.ep
  Hi Bender!

Prefixing multiple routes is another good use for under.

  use Mojolicious::Lite;

  # /foo
  under '/foo';

  # /foo/bar
  get '/bar' => sub { shift->render(text => 'bar!') };

  # /foo/baz
  get '/baz' => sub { shift->render(text => 'baz!') };



Conditions such as agent and host from Mojolicious::Plugin::HeaderCondition allow even more powerful route constructs.

  # /foo
  get '/foo' => (agent => qr/Firefox/) => sub {
    shift->render(text => 'Congratulations, you are using a cool browser!');

  # /foo
  get '/foo' => (agent => qr/Internet Explorer/) => sub {
    shift->render(text => 'Dude, you really need to upgrade to Firefox!');

  # /bar
  get '/bar' => (host => '') => sub {
    shift->render(text => 'Hello Mojolicious!');

However you might want to disable automatic route caching in case there are routes responding to the same path without conditions attached, since those would otherwise get precedence once cached.



Signed cookie based sessions just work out of the box as soon as you start using them. The flash can be used to store values that will only be available for the next request (unlike stash, which is only available for the current request), this is very useful in combination with redirect_to.

  use Mojolicious::Lite;

  get '/login' => sub {
    my $self = shift;
    my $name = $self->param('name') || '';
    my $pass = $self->param('pass') || '';
    return $self->render unless $name eq 'sebastian' && $pass eq '1234';
    $self->session(name => $name);
    $self->flash(message => 'Thanks for logging in!');
  } => 'login';

  get '/' => sub {
    my $self = shift;
    return $self->redirect_to('login') unless $self->session('name');
  } => 'index';

  get '/logout' => sub {
    my $self = shift;
    $self->session(expires => 1);
  } => 'logout';


  @@ layouts/default.html.ep
  <!doctype html><html>
    <head><title><%= title %></title></head>
    <body><%= content %></body>

  @@ login.html.ep
  % layout 'default';
  % title 'Login';
  <%= form_for login => begin %>
    <% if (param 'name') { %>
      <b>Wrong name or password, please try again.</b><br>
    <% } %>
    <%= text_field 'name' %><br>
    <%= password_field 'pass' %><br>
    <%= submit_button 'Login' %>
  <% end %>

  @@ index.html.ep
  % layout 'default';
  % title 'Welcome';
  <% if (my $message = flash 'message' ) { %>
    <b><%= $message %></b><br>
  <% } %>
  Welcome <%= session 'name' %>!<br>
  <%= link_to logout => begin %>
  <% end %>


Note that you should use a custom secret to make signed cookies really secure.

  app->secret('My secret passphrase here!');

File Uploads

All files uploaded via multipart/form-data request are automatically available as Mojo::Upload instances. And you don't have to worry about memory usage, because all files above 250KB will be automatically streamed into a temporary file.

  use Mojolicious::Lite;

  any '/upload' => sub {
    my $self = shift;
    if (my $example = $self->req->upload('example')) {
      my $size = $example->size;
      my $name = $example->filename;
      $self->render(text => "Thanks for uploading $size byte file $name.");


  @@ upload.html.ep
  <!doctype html><html>
      <%= form_for upload =>
            (method => 'post', enctype => 'multipart/form-data') => begin %>
        <%= file_field 'example' %>
        <%= submit_button 'Upload' %>
      <% end %>

To protect you from excessively large files there is also a global limit of 5MB by default, which you can tweak with the MOJO_MAX_MESSAGE_SIZE environment variable.

  # Increase limit to 1GB
  $ENV{MOJO_MAX_MESSAGE_SIZE} = 1073741824;

User Agent

With Mojo::UserAgent there's a full featured HTTP 1.1 and WebSocket user agent built right in. Especially in combination with Mojo::JSON and Mojo::DOM this can be a very powerful tool.

  get '/test' => sub {
    my $self = shift;
    $self->render(data => $self->ua->get('')->res->body);


WebSocket applications have never been this easy before.

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

External Templates

External templates will be searched by the renderer in a templates directory.

  # /external
  any '/external' => sub {
    my $self = shift;

    # templates/foo/bar.html.ep

Static Files

Static files will be automatically served from the DATA section (even Base 64 encoded) or a public directory if it exists.

  @@ something.js

  @@ test.txt (base64)

  % mkdir public
  % mv something.js public/something.js


Testing your application is as easy as creating a t directory and filling it with normal Perl unit tests.

  use Test::More tests => 3;
  use Test::Mojo;

  use FindBin;
  require "$FindBin::Bin/../";

  my $t = Test::Mojo->new;

Run all unit tests with the test command.

  % ./ test

To make your tests more noisy and show you all log messages you can also change the application log level directly in your test files.



To disable debug messages later in a production setup you can change the Mojolicious mode, default will be development.

  % ./ --mode production


Mojo::Log messages will be automatically written to a log/$mode.log file if a log directory exists.

  % mkdir log

For more control the Mojolicious instance can be accessed directly.

  app->routes->route('/foo/:bar')->via('get')->to(cb => sub {
    my $self = shift;
    $self->app->log->debug('Got a request for "Hello Mojo!".');
    $self->render(text => 'Hello Mojo!');


In case a lite app needs to grow, lite and real Mojolicious applications can be easily mixed to make the transition process very smooth.

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

  sub index { shift->render(text => 'It works!') }

  package main;
  use Mojolicious::Lite;

  get '/bar' => sub { shift->render(text => 'This too!') };



There is also a helper command to generate a full Mojolicious example that will let you explore the astonishing similarities between Mojolicious::Lite and Mojolicious applications. Both share about 99% of the same code, so almost everything you learned in this tutorial applies there too. :)

  % mojo generate app


You can continue with Mojolicious::Guides now, and don't forget to have fun!


Mojolicious::Lite implements the following functions.


  my $route = any '/:foo' => sub {...};
  my $route = any [qw/get post/] => '/:foo' => sub {...};

Generate route matching any of the listed HTTP request methods or all. See also the tutorial above for more argument variations.


  my $app = app;

The Mojolicious::Lite application.


  my $route = del '/:foo' => sub {...};

Generate route matching only DELETE requests. See also the tutorial above for more argument variations.


  my $route = get '/:foo' => sub {...};

Generate route matching only GET requests. See also the tutorial above for more argument variations.


  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
  helper add => sub { $_[1] + $_[2] };

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

  # Template
  <%= add 2, 3 %>

Note that this function is EXPERIMENTAL and might change without warning!


  hook after_dispatch => sub {...};

Add hooks to named events, see Mojolicious for a list of all available events. Note that this function is EXPERIMENTAL and might change without warning!


  plugin 'something';
  plugin 'something', foo => 23;
  plugin 'something', {foo => 23};
  plugin 'Foo::Bar';
  plugin 'Foo::Bar', foo => 23;
  plugin 'Foo::Bar', {foo => 23};

Load plugins, see Mojolicious for a list of all included example plugins.


  my $route = post '/:foo' => sub {...};

Generate route matching only POST requests. See also the tutorial above for more argument variations.


  my $route = put '/:foo' => sub {...};

Generate route matching only PUT requests. See also the tutorial above for more argument variations.


  my $route = under sub {...};
  my $route = under '/:foo';

Generate bridge to which all following routes are automatically appended. See also the tutorial above for more argument variations.


  my $route = websocket '/:foo' => sub {...};

Generate route matching only WebSocket handshakes. See also the tutorial above for more argument variations.


Mojolicious::Lite inherits all attributes from Mojolicious.


Mojolicious::Lite inherits all methods from Mojolicious.


Mojolicious, Mojolicious::Guides,