简体   繁体   中英

How to access the NextJS response body from getServerSideProps?

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 theHTTP 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.

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM