---
url: /runcobo/guide/server.md
description: >-
  Start the server, configure host, port and TLS, compose middleware handlers,
  and inject dependencies into actions.
---

# Server & Middleware

## Starting the server

```crystal
Runcobo.start
```

`Runcobo.start` binds the socket, logs the address and blocks until the process receives `SIGINT` or `SIGTERM`.

### Options

| Argument | Environment variable | Default |
| --- | --- | --- |
| `host:` | `HOST` | `"0.0.0.0"` |
| `port:` | `PORT` | `3000` |
| `reuse_port:` | `REUSE_PORT` (`true`/`false`) | `false` |
| `cert:` | `CERT` | `nil` |
| `key:` | `KEY` | `nil` |
| `handlers:` | — | `Runcobo::Server.default_handlers` |
| `proxy_config:` | — | trusts no proxies (see [Proxies](/guide/proxies)) |
| `shutdown_timeout:` | — | `30.seconds` |

Arguments override environment variables:

```crystal
Runcobo.start(host: "127.0.0.1", port: 8080)
```

### TLS

Set both a certificate chain and a private key to serve HTTPS directly:

```sh
CERT=certs/server.crt KEY=certs/server.key ./bin/server
```

Setting only one of them is an error. In most deployments TLS terminates at a load balancer instead — see [Proxies](/guide/proxies).

### Multiple processes

To run several processes on the same port — one per CPU core, say — start each with `REUSE_PORT=true`. The operating system then balances incoming connections between them.

### Graceful shutdown

On `SIGINT` or `SIGTERM`, Runcobo stops accepting connections, rejects requests that arrive on open connections with `503`, and waits up to `shutdown_timeout` for in-flight requests to finish. Requests still running after that are reported in the log.

## Handlers

Runcobo is built on Crystal's `HTTP::Server`. Each request passes through a chain of `HTTP::Handler`s. The default chain, `Runcobo::Server.default_handlers`, is:

Pass your own list to change it. Order matters — a handler only sees requests the handlers before it pass on:

```crystal
Runcobo.start(handlers: [
  Runcobo::LogHandler.new,
  Runcobo::ErrorHandler.new,
  HTTP::CompressHandler.new,                               # from Crystal's stdlib
  Runcobo::StaticFiles.new("/assets", directory: "public"),
  Runcobo::RouteHandler.new,
  Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)
```

Two handlers are always added in front of your list by the server: one that tracks in-flight requests for graceful shutdown, and one that resolves [client information](/guide/proxies).

### Custom handlers

A handler is any class that includes `HTTP::Handler`:

```crystal
class CorsHandler
  include HTTP::Handler

  def call(context)
    context.response.headers["Access-Control-Allow-Origin"] = "https://app.example.com"
    if context.request.method == "OPTIONS"
      context.response.status_code = 204
      return
    end
    call_next(context)
  end
end
```

Use handlers for cross-cutting concerns that apply to every request. Use [filters](/guide/filters) for concerns that belong to specific actions.

## Dependency injection

Dependencies — the database store, settings, clients for external services — travel on the **request context**. They're created once in `main.cr`, set on every request's `HTTP::Server::Context` by your route handler, and read back where they're needed. Nothing is global.

Declare a property on the context for each dependency:

```crystal [src/web/handlers.cr]
record Blog::Settings, public_base_url : String

class HTTP::Server::Context
  property! blog_store : Blog::Store::Queries
  property! blog_settings : Blog::Settings
end
```

Set them in `build_action`, which `Runcobo::RouteHandler` calls to create the action for each request:

```crystal [src/web/handlers.cr]
module Blog
  class RouteHandler < Runcobo::RouteHandler
    def initialize(@store : Store::Queries, @settings : Settings)
    end

    protected def build_action(action_class : Runcobo::Action.class, context : HTTP::Server::Context) : Runcobo::Action
      context.blog_store = @store
      context.blog_settings = @settings
      super
    end
  end
end
```

Give actions short accessors in the base action:

```crystal [src/actions/base_action.cr]
abstract class Blog::BaseAction < ::BaseAction
  protected def store : Blog::Store::Queries
    context.blog_store
  end

  protected def settings : Blog::Settings
    context.blog_settings
  end
end
```

Create them once in `main.cr`:

```crystal [src/main.cr]
require "./app"

settings = Blog::Settings.new(public_base_url: ENV["PUBLIC_BASE_URL"])

Blog::Store.open(ENV["DATABASE_URL"]) do |store|
  Runcobo.start(handlers: [
    Runcobo::LogHandler.new,
    Runcobo::ErrorHandler.new,
    Blog::RouteHandler.new(store, settings),
    Runcobo::RouteNotFoundHandler.new,
  ] of HTTP::Handler)
end
```

Why the context rather than the action? Everything that handles the request can reach it — actions, but also middleware that runs after the route handler and error-rendering code. Each dependency is typed, created once and visible in `main.cr`, and specs build the handler with their own values.

## Using `Runcobo::Server` directly

`Runcobo.start` is a shortcut. For more control — binding a random port in tests, for example — build the server yourself:

```crystal
server = Runcobo::Server.new(handlers: handlers, proxy_config: proxy_config)
server.port = 4000
server.listen   # blocks
```

Handlers can be replaced with `server.handlers = [...]` until the server binds its socket.
