Jay Wilson developer. creator. coffee drinker.

How to access custom headers in Hummingbird 2

A quick example of how to access custom headers in the Swift Server platform Hummingbird.

Hummingbird is a server framework written in Swift. I'm using it at work and for a few personal projects. It's small and quick to build, so it checks the boxes for what I'm trying to do.

The Hummingbird project is quickly moving to v2.0 (as of writing this RC 2 is out 🎉), and that brought a change with accessing custom headers. In v1 it looked something like request.headers["custom-header-name"]. In v2 it now requires a bit more work thanks to the reliance on Swift-HTTP-Types, but ultimately I think it's a cleaner call site.

First, you need to extend HTTPField.name and add the new header name in there.

// don't forget to import HTTPTypes
import HTTPTypes

extension HTTPField.Name {
  // if you don't force unwrap here, you'll need to account for the optional in the next step
	static let customHeaderName = Self("custom-header-name")!
}

Then you can call it in a very similar way to v1.

let headerValue = request.headers[.customHeaderName]

If you liked this post, consider buying me a coffee.

Or donate to Lambda Legal to help fight for trans and LGBTQIA+ rights.

Subscribe to my posts via your favorite feed reader.