Search code examples
swifthttpresponsecontent-typevapor

How to set the Content-Type response header in Vapor 4?


My application uses Vapor 4.3 and has a simple route that sends an HTML snippet as a response:

import Vapor

func routes(_ app: Application) throws {
  app.get("hello") { _ -> String in
    "<html><body>Hello, world!</body></html>"
  }
}

Unfortunately, this response doesn't have a correct Content-Type HTTP header set on it, so it doesn't render as proper HTML when this route is opened in a browser. What's the best way to set the Content-Type header on this response?


Solution

  • You need to return Response like this

    app.get("hello") { _ -> Response in
        var headers = HTTPHeaders()
        headers.add(name: .contentType, value: "text/html")
        let html = "<html><body>Hello, world!</body></html>"
        return Response(status: .ok, headers: headers, body: .init(string: html))
    }