1

I am fetching some data from WP REST API in Next.js with Isomorphic unfetch, how can I get response headers?

import fetch from 'isomorphic-unfetch';

class Blog extends React.Component {
    static async getInitialProps() {
        const res = await fetch('https://wordpress.org/news/wp-json/wp/v2/posts');
        const data = await res.json();
        return { 
            res: res,
            data: data
        };
    }

    render() {
        console.log(this.props.res)
        console.log(this.props.data)
        return (
            <h1>Blog</h1>
        )
    }
}

I don't see anything available in the console enter image description here

but headers are there when I just open url in browser enter image description here

1 Answer 1

2

res.headers will returns all headers according to this. You can use res.headers.get('x-wp-total') to get value, then return it inside getInialProps function.

import fetch from 'isomorphic-unfetch';

class Blog extends React.Component {
    static async getInitialProps() {
        const res = await fetch('https://wordpress.org/news/wp-json/wp/v2/posts');
        const data = await res.json();
        return { 
            res: res,
            data: data,
            wpTotal: res.headers.get('x-wp-total')
        };
    }

    render() {
        console.log(this.props.wpTotal)
        console.log(this.props.data)
        return (
            <h1>Blog</h1>
        )
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately I get undefined, I can only access size and timeout inside this.props.res
I didn't see your edited post until now. Thank you, this way I do get the values!
I am getting error as response.headers.get is not a function. In my case, I need to get the response before deleting, and GET response headers contains the tag value.
@Marko getting a related issue, I have to pass headers in further API call. Can you please look in to it here stackoverflow.com/questions/69678380/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.