How to fetch response header data in nextjs?

172 views Asked by At

In my nextjs app, i want to fetch response headers of this http request. i can see all response headers in browser's devtools in network section like this;

devtools

However, i cannot fetch them inside the code. It only returns content-length and content-type headers.

Here is the request; (it is a client-side rendering btw.)

import axios from 'axios'

const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
})

const getProducts = async () => {
  const response = await api.get(`/all-products`)

  return {
    data: response.data,
    headers: response.headers
  }
}

export default {
  getProducts,
}

I have tried adding next.config.js this;

/** @type {import('next').NextConfig} */
const nextConfig = {
  env: {
    theme: 'DEFAULT',
    currency: 'USD',
    NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL,
  },
  publicRuntimeConfig: { theme: 'DEFAULT', currency: 'USD' },
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**',
      },
    ],
  },
  compiler: {
    styledComponents: true,
  },
  reactStrictMode: false,
  output: 'standalone',
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          { key: 'Access-Control-Expose-Headers', value: 'Date' },
        ],
      },
    ];
  },
}

module.exports = nextConfig

Any suggestion?

EDIT : When i try it at server-side rendering, it worked properly. At Client-side, response headers cannot be reached.

0

There are 0 answers