# How to Route an Incoming URL to a Rack Application in Rails

*Published on July 29, 2024*

Tags: Router

---


This post is part of my&nbsp;[handbook on the Rails Router](/tag/router).

**TL;DR:**&nbsp;You can route an incoming HTTP request to a valid Rack endpoint using the following syntax:

```ruby
match '/url', to: RackApp

# OR

mount RackApp, at: "/url"

# OR

mount RackApp => "/url"
```

Let's dig in to learn why, what, and how. This is what we'll learn in this post:

- **Why You Want to Route to a Rack App**
- **How to Route to a Rack Application**
- **Receiving Requests at Root of Rack App**
- **Standard Rails Routes are Rack-Compliant**
- **You can Use a Lambda as a Route Handler**

* * *

> 💡 This post won't make much sense if you don't know what Rack interface (or protocol) is, what problem it's designed to solve, and what a Rack-compliant application looks like.&nbsp;[This post](/definitive-guide-to-rack)&nbsp;is a good starting point: [The Definitive Guide to Rack for Rails Developers](/definitive-guide-to-rack)

## Why You Want to Route to a Rack App

We know that the Rails router can send an incoming HTTP request to an action method on a controller class. For example, the following route dispatches the request to&nbsp;`/profile`&nbsp;to the&nbsp;`profile`&nbsp;action on the&nbsp;`PagesController`&nbsp;class.

```ruby
# config/routes.rb
get "profile" => "pages#profile"
```

Sometimes, you may want to route a particular URL (or a set of URLs) to a separate application within your project. A typical use-case for this application is to build a simple UI that provides functionality separate from your core Rails application. This sub-application is well-isolated from the rest of the codebase, designed specifically to accept web requests.

For example, imagine you're writing a gem and you want to expose a web UI for the users of your gem. In this case, you could create a simple Sinatra app in your gem and ask the users to mount this Sinatra application (which is valid Rack app) on a particular URL.

**Hmm... Does that remind you of something?**&nbsp;Something that you use everyday in your Rails applications to process background jobs and view the job status in a web UI that looks nothing like your application?

Yes! The Sidekiq gem uses this exact pattern to display the&nbsp;[Sidekiq web UI](https://github.com/sidekiq/sidekiq/wiki/Monitoring#web-ui), which shows the information about the background jobs in the browser. It's a&nbsp;[Sinatra](https://github.com/sidekiq/sidekiq/blob/main/lib/sidekiq/web.rb)&nbsp;application within the Sidekiq gem, and contains code that's well-isolated and separate from the core Sidekiq functionality. Hence, it makes sense to mount this web UI as a separate application.

Here're the&nbsp;[instructions](https://github.com/sidekiq/sidekiq/wiki/Monitoring#rails)&nbsp;on mounting Sidekiq web UI in your Rails application.

```ruby
# config/routes.rb
require 'sidekiq/web'

Rails.application.routes.draw do
  # mount Sidekiq::Web in your Rails app
  mount Sidekiq::Web => "/sidekiq"
end
```

We're instructing the Rails router to dispatch all requests to the URL&nbsp;`/sidekiq`&nbsp;to the&nbsp;`Sidekiq::Web`&nbsp;class, which is a valid Rack application, because it satisfies the&nbsp;[Rack interface](/definitive-guide-to-rack):&nbsp;**a**&nbsp;**`call`**&nbsp;**method that accepts the HTTP request environment and returns an array containing status, headers, and the body of the response.**

```ruby
# lib/sidekiq/web.rb

module Sidekiq
  class Web
    def self.call(env)
      # [status, headers, body]
    end
  end
end
```

## **How to Route to a Rack Application / Endpoint**

The most basic way to route an incoming HTTP request to a Rack application is to use the&nbsp;`match`&nbsp;method on the Router.

```ruby
# config/routes.rb
match '/url', to: RackApp, via: :all
```

Here,&nbsp;`RackApp`&nbsp;is a valid Rack application class. Typically, you'd create this class in the&nbsp;`lib`&nbsp;directory of your Rails project. The&nbsp;`via: :all`&nbsp;option tells the Router to match all verbs like&nbsp;`GET, POST, etc.`&nbsp;to this route, and the Rack application decides which route to handle.

Let's try this out to build our own fake Sidekiq web UI. In a fresh Rails project that's not using Sidekiq, add the following route in the&nbsp;`config/routes.rb`&nbsp;file.

```ruby
# config/routes.rb
match '/sidekiq', to: Sidekiq::Web, via: :all
```

Next, create a&nbsp;`sidekiq/web.rb`&nbsp;file in the&nbsp;`lib`&nbsp;directory, with the following code.

```ruby
# lib/sidekiq/web.rb
module Sidekiq
  module Web
    def self.call(env)
      [200, {}, ["Sidekiq Web UI"]]
    end
  end
end
```

Verify the route is pointing to your Rails application by running the following command in the terminal:

```bash
$ bin/rails routes -g sidekiq
 Prefix   Verb  URI Pattern          Controller#Action
sidekiq         /sidekiq(.:format)   Sidekiq::Web
```

Launch your Rails application and visit&nbsp;`http://localhost:3000/sidekiq`&nbsp;URL. You should see this screen.

![routing-to-rack.png](https://writesoftwarewell.com/media/bnx1sjgrfuwuiw2zwx6l8siarar0.png "routing to a rack app")

It means Rails is routing requests to&nbsp;`/sidekiq`&nbsp;to our rack application.

## **Receiving Requests at Root of Rack App**

With the above route syntax, the route remains unchanged in the receiving Rack application. That is, the&nbsp;`Sidekiq::Web`&nbsp;class receives the request at&nbsp;`/sidekiq`, and not&nbsp;`/`.

**What if you want to receive all the requests at the root path on your Rack application?**

To have your Rack app receive requests at the root path, use the&nbsp;`mount`&nbsp;method. Check this out.

```ruby
mount Sidekiq::Admin, at: "/admin"

# OR

mount Sidekiq::Admin => "/admin"
```

Let's find the route it created:

```bash
$ bin/rails routes -g admin  
Prefix    Verb    URI Pattern     Controller#Action
                  /admin          Sidekiq::Admin
```

Finally, add the Rack endpoint:

```ruby
# lib/sidekiq/admin.rb
module Sidekiq
  module Admin
    def self.call(env)
      [200, {}, ["Sidekiq Admin UI"]]
    end
  end
end
```

Launch your Rails application and visit&nbsp;`http://localhost:3000/admin`&nbsp;URL. You'll be greeted with the text: "Sidekiq Admin UI".

![receive-requests-at-root.png](https://writesoftwarewell.com/media/z1abyzel27wkclhsj4uiv8ap0mty.png "receiving requests at the root of the rack app")

**The main difference in this example vs. the previous one is that the Rack application receives the incoming request at**&nbsp;**`/`****, not**&nbsp;**`/admin`****.**&nbsp;You can verify this by inspecting the&nbsp;`env["PATH_INFO"]`&nbsp;value in the&nbsp;`call`&nbsp;method. I'll leave this as an exercise to you.

One last thing. As with all convenience methods,&nbsp;`mount`&nbsp;uses&nbsp;`match`&nbsp;internally, so you can use all the options you can with&nbsp;`match`. For example, if you want to name the route, pass the&nbsp;`:as`&nbsp;option.

```ruby
# config/routes.rb
mount Sidekiq::Admin, at: "/admin", as: "sidekiq_admin"
```

This will generate the&nbsp;`sidekiq_admin_path`&nbsp;and&nbsp;`sidekiq_admin_url`&nbsp;helpers which can be used to navigate to this mounted app.

## **Standard Rails Routes are Rack-Compliant**

Did you know that a typical Rails route, which points to&nbsp;`controller#action`&nbsp;also expands to a valid Rack application? (P.S. I didn't know this until yesterday.)

```ruby
# config/routes.rb

get "about" => "pages#about"
```

Don't believe me? Open the Rails console and run the following code (assumes you have a&nbsp;`PagesController`&nbsp;class with the&nbsp;`profile`&nbsp;action).

```javascript
> PagesController.action :profile
#<Proc:0x00000001284b7d68 .../lib/action_controller/metal.rb:290 (lambda)>
```

To learn more, check out this post:&nbsp;[How a Ruby Method Becomes a Rails Action](/ruby-method-to-rails-action-metal)

## You can Use a Lambda as a Route Handler

> 💡 Since a simple proc or a lambda object is a valid Rack application, you can also use it to handle incoming HTTP request.

Following route will invoke the provided lambda whenever the application receives a request on the&nbsp;`/up`&nbsp;endpoint.

```javascript
# config/routes.rb
get '/up', to: ->(env) { [204, {}, ["success"]] }
```

To learn more, check out this post:&nbsp;[Inline Routes in Rails](/rails-inline-routes)

