How to add more content types in worker for customizing http headers?

I am using the code provieded here for customizing my http headers. In this code, we are using the function for content type “text/html” only. How can we add other types like “text/xml” and “image/x-icon” etc ?

Within the addHeaders() function, replace the .includes("text/html") to .match(/(text\/html)|(text\/xml)|(image\/x-icon)/g).

The code snippet becomes like this:

async function addHeaders(req) {
    let response = await fetch(req)
    let newHeaders = new Headers(response.headers)

    const tlsVersion = req.cf.tlsVersion
    // This sets the headers for HTML responses: 
    if (newHeaders.has("Content-Type") && !newHeaders.get("Content-Type").match(/(text\/html)|(text\/xml)|(image\/x-icon)/g)) {
        return new Response(response.body, {
            status: response.status,
            statusText: response.statusText,
            headers: newHeaders
        })
    }

    etc......
1 Like

Thank you very much @erictung…! It is now working correctly and adding the intended headers for those content types.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.