Expose Content-Disposition header on NextJS

Viewed 481

I'm trying to get the Content-Disposition header in a response from an external API using axios.

Despite the header being present in Chrome DevTools Network Response, I can't seem to have access to that specific header from server.

I found this article talking about exposing the Content-Disposition header through Access-Control-Expose-Headers but I'm not quite sure how to implement it in Nextjs.

I tried editing the next.config.js file like below, by following directions from this Nextjs Documentation page, regarding security headers, but had no luck

/** @type {import('next').NextConfig} */
module.exports = {
  reactStrictMode: true,
  async headers() {
    // to allow specific headers to appear in requests
    // https://nextjs.org/docs/advanced-features/security-headers
    const securityHeaders = [
      // important
      { key: "Access-Control-Expose-Headers", value: "Content-Disposition" },
    ]
    return [
      {
        source: '/:path*', // req path
        headers: securityHeaders
      }
    ]
  }
}

This is the API call I made using axios:

// lib/utils.js

export async function downloadFile(collectionName: string, documentId: string) {
  const res = await axios.get(
    `https://api.myapiendpoint.com/file/${collectionName}/${documentId}`
  );
  console.log(res.headers);
}

Chrome DevTools log: Chrome DevTools

console.log output:

// these are the only headers I receive
{
    "content-length": "195687",
    "content-type": "text/csv; charset=utf-8",
    "last-modified": "Thu, 10 Feb 2022 16:00:05 GMT"
}

1 Answers

I am 99.99% sure and I believe this is most probably backend issue. I had the exact same problem when i needed to implement download pdf/csv logic (with file name) which required content-disposition header to be accessed from response.

Now, no matter what I tried I always got to see that header in dev tools and also in postman but not in my console. After lots of efforts and convincing my backend team member, it turned out that backend didn't expose it.

Check your backend (whatever technology it uses), the problem lies there ;)

Related