How to Compress Web Responses from F# + Giraffe Endpoints

Date: 2024-10-09 | create | tech | fsharp | giraffe | webapp |

I've recently added web response compression to several of my websites to lower bandwidth usage.

Here we'll explore how to add compression to your web responses to lower their payload size.

F# + Giraffe WebApp setup

For our example project we'll be using our minimal fullstack F# + Giraffe webapp we built previously as a foundation.

This webapp will have a single endpoint: /

  • Creates 1000 Guids
  • Creates HTML for 1000 Guids
  • Returns the HTML

Response sizes:

  • Uncompressed: 45.4 kb
  • Compressed: 21.1 kb

Savings of about 50% for our example.

How to Compress Web Responses in F# + Giraffe

Giraffe is a thin wrapper around ASP.NET which means we still have access to a lot of the goodies from one of the world's most popular and performant web frameworks.

Here we add two configurations to our F# + Giraffe setup:

  • App: UseResponseCompression
  • Services: AddResponseCompression

Together these allow our web responses to be compressed.

Configuration code: Program.fs

let configureApp (app: IApplicationBuilder) =
    app
        .UseResponseCompression() // Tell App to use Response Compression
        .UseRouting()
        .UseEndpoints(fun e -> e.MapGiraffeEndpoints(webApp))
    |> ignore

let configureServices (services: IServiceCollection) = 
    services.AddRouting() |> ignore

    // Add Giraffe dependencies
    services.AddGiraffe() |> ignore

    // Configure Response Compression
    services.AddResponseCompression(fun a -> a.EnableForHttps <- true) |> ignore 

Host
    .CreateDefaultBuilder()
    .ConfigureWebHost(fun webHost ->
        webHost
            .UseKestrel(fun c -> c.AddServerHeader <- false)
            .ConfigureServices(configureServices)
            .Configure(configureApp)
        |> ignore)
    .Build()
    .Run()

Full Source Code (github) is available to HAMINIONs Members.

Next

That should get you setup with web compression for your endpoints.

I recently rolled this out on 1000-checkboxes which has some beefy responses (HTMX and Tailwind) and was able to reduce my payloads by about 60% (100kb -> 40kb) which makes me feel a lot better about my bandwidth usage (which can get pretty pricy)

Web Compression is now on by default in CloudSeed (my F# project boilerplate).

If you liked this post you might also like:

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.