Serving web applications over HTTPSΒΆ

This short recipe shows how one can serve a servant application over HTTPS, by simply using warp-tls instead of warp to provide us a run function for running the Application that we get by calling serve.

As usual, we start by clearing our throat of a few language extensions and imports.

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Handler.WarpTLS
import Servant

No need to work with a complicated API here, let’s make it as simple as it gets:

type API = Get '[JSON] Int

api :: Proxy API
api = Proxy

server :: Server API
server = return 10

app :: Application
app = serve api server

It’s now time to actually run the Application. The warp-tls package provides two functions for running an Application, called runTLS and runTLSSocket. We will be using the first one.

It takes two arguments, the TLS settings (certificates, keys, ciphers, etc) and the warp settings (port, logger, etc).

We will be using very simple settings for this example but you are of course invited to read the documentation for those types to find out about all the knobs that you can play with.

main :: IO ()
main = runTLS tlsOpts warpOpts app

  where tlsOpts = tlsSettings "cert.pem" "secret-key.pem"
        warpOpts = setPort 8080 defaultSettings

This program is available as a cabal project here.