2

I need to set a custom response header on the HTML document, and the value of that header is derived from the response body. I found out that can be done with getServerSideProps, however finding a way to access the response body within that function has so far proven to be difficult. When console logging all keys inside the context.res object, one field that stands out as potentially what I'm looking for is outputData, though the value of that when logged is always an empty array.

The NextJS docs on getServerSideProps say the res key is the HTTP response object. A boolean finished field, and its newer writableEnded counterpart both always come back with value false. So I'm wondering if there's anything that can be done in getServerSideProps to let me add

ctx.res.setHeader('x-custom-company-header', getHeader(responseBody));

Where responseBody is the stringified response representing the HTML document of the requested page. Or do I have to make use of some other NextJS optional function / middleware in order to achieve this?

I found this discussion while attempting to figure out a solution. But that appears to only be relevant to POST requests, as adding

const body = await parseBody(context.req, '1mb');
console.log('body here:');
console.dir(body);

only yielded an empty string for that value in the terminal.

Pat Needham
  • 5,698
  • 7
  • 43
  • 63
  • `getServerSideProps` is not always used to response html (for example for client side navigation it does not send html), so you won't be able to derive anything from it. Anyway, why would you need custom header in html response? – Danila Jul 27 '21 at 08:42
  • @Danila it's a requirement I don't necessarily agree with as I think there are better ways to accomplish the same thing, but our application runs within a larger platform that uses that custom header to verify the page. – Pat Needham Jul 27 '21 at 11:58
  • Well, I'm afraid there is nothing you can do here on Next.js side. Handle this stuff on your reverse-proxy server, would be much easier there. – Danila Jul 27 '21 at 12:03

1 Answers1

1

If you absolutely have to do it inside getServerSideProps, you could overwrite res.end and capture the generated HTML that Next.js passes to it.

export async function getServerSideProps({ res }) {
    const resEnd = res.end.bind(res) // Save current `res.end` into a variable to be called later
    res.end = html => {
        res.setHeader('x-custom-company-header', getHeader(html))
        resEnd(html)
        return
    }

    // Remaining code...
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146