Reveal the Content-Disposition header in NextJS

I am attempting to retrieve the Content-Disposition header from a response received via axios from an external API.

Even though I can see the header in Chrome DevTools Network Response, I am unable to access it from the server.

I came across this article discussing exposing the Content-Disposition header through Access-Control-Expose-Headers, but I am uncertain about how to implement it in Nextjs.

I tried modifying the next.config.js file as shown below, following guidance from the Nextjs Documentation page on security headers, but without success

/** @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 axios call I used for the API:

// 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: https://i.stack.imgur.com/T9xWH.png

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

Answer №1

It is highly probable, with a certainty of 99.99%, that the issue at hand is related to the backend. I encountered a similar predicament when implementing logic for downloading PDF/CSV files, where access to the content-disposition header was necessary from the response.

No matter how many attempts were made, the header only appeared in the developer tools and Postman, but not in the console. After extensive efforts and discussions with my backend team member, it became apparent that the backend was not exposing it.

I suggest examining your backend system (regardless of the technology used) as the solution likely resides there ;)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What techniques can I use to customize React Bootstrap's css?

Struggling to find a way to override React Bootstrap css without resorting to inline styles. Currently working on rendering an Alert component. https://i.stack.imgur.com/KiATb.png Tried making some CSS modifications, but they're not taking effect du ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

The implementation of the '@' import for Jest testing is crucial for enhancing the efficiency of test cases

Having an issue running tests for my React application that utilizes @ import like this import { something } from "@atoms"; I have successfully mapped it in the tsconfig.json file, and it works fine when I run the application (command: "web ...

Animated collapse with margin effect in Material-UI

I have been utilizing the MUI-Collapse component to display collapsible content within a list. I am looking to add vertical spacing between the Collapse components in the list, but I do not want the spacing to remain when the Collapse is collapsed. I am ha ...

React-built NPM website fails to compile

After successfully running my website created with ReactJS on my local machine, I encountered an error when trying to build it using npm run build. The error message received was: > react-snap � pageerror at /personal-site/: SyntaxError: Unexpected ...

Dealing with the issue of needing to include "%20" in the URL after receiving a NextJS build

Currently, I am working on a simple NextJS (v13) project utilizing TheMoviedb API. I am fetching images and titles of content with an API request in this project. The image paths can be accessed using a variable named dt, which corresponds to either backdr ...

Navigating between TextFields using InputAdornments in Material UI with tab functionality

Is there a way to prevent the "focus" event from occurring on input adornments of MaterialUI Text Fields? I have two fields with input adornments and I want to switch between them using just a single Tab press, without focusing on the input adornment. Is ...

Adding an authentication header in redux-api-middleware: steps and best practices

Procedure import { CALL_API } from 'redux-api-middleware'; export const MOVIES_GET_SUCCESS = 'MOVIES_GET_SUCCESS'; export const fetchMovies = () => { return { [CALL_API]: { endpoint: 'http://localhost:3005/api/mov ...

Ensuring TextField Validation on Material-UI is a Must

When the required TextField is filled with text, everything works fine. However, if the TextField is left blank, an error message will be displayed in the helperText field. The challenge arises when trying to determine if something has been entered into ...

Enhance the speed of filtering a large array of 4000+ objects in React for optimal performance

I am currently dealing with a component that generates an input of type text for filtering an array containing over 4000 objects. const { airports } = useContext(MainContext); const [airportListLocal, setAirportListLocal] = useState<Airport[]>(airp ...

The Typescript error message states that the type '{ onClick: () => void; }' cannot be assigned to the type 'IntrinsicAttributes'

I'm a beginner in Typescript and I'm encountering difficulties comprehending why my code isn't functioning properly. My goal is to create a carousel image gallery using React and Typescript. However, I'm facing issues when attempting t ...

Display two examples from the material-ui documentation

My goal is to merge two demos found in the material-ui documentation. Clipped under the app bar - Describes a page layout Fixed header - Illustrates a table with a fixed header. I am looking for a solution where the table occupies the entire available p ...

Bring in an asynchronous function from another file to the component

Experiencing difficulties with learning NextJs, particularly async await for fetching data from Shopify. In my file library.js, all queries are stored: const domain = process.env.API_URL const storefrontAccessToken = process.env.ACCESS_TOKEN async funct ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

The BottomNavigation fails to refresh when moving to a different screen

While working on the bottom navigation bar for my website, I encountered an issue. The problem arises when I try to toggle between three buttons: Home, Profile, and Matches. Upon clicking on the Profile button, the page switches to the profile tab but the ...

Exploring Nuxt.js: A guide to server-side caching of axios calls for universal client access

I am currently working on a project using Vue and Nuxt.js. I am wondering if there is a way to cache an axios web service call for all clients. Specifically, I need to retrieve currency reference data and it seems inefficient for every client to make this ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

The installation of npm fails due to a conflict with the peer dependency version of [email protected]

Encountered an issue while attempting to install dependencies for this project, where the command npm install failed with the following error: > npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: & ...

Switch between light and dark themes in antd using React at runtime

Despite finding a similar question on Stack Overflow, the provided answer did not solve my issue. I have attempted to follow the steps mentioned, but unfortunately, there has been no noticeable effect. I am struggling with where to place the config-overrid ...

Implementing unique union type in React: Effective ways to declare typescript type for prop value

I am currently facing an issue where I need to set a specific type for a prop value. However, the challenge lies in the fact that the types are string unions which can vary depending on the usage of the React Component. Let me provide you with the TypeScr ...