Getting response header data in Next.js is a piece of cake!

In my nextjs application, I am trying to access the response headers of an HTTP request. While I can view all the response headers in the browser's devtools under the network section, I am unable to fetch them within the actual code. The only headers that are being returned are the content-length and content-type headers.

You can see the response headers in the devtools here.

Below is the code snippet for the request (client-side rendering):

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 attempted to add the following to my next.config.js file:

/** @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 suggestions or solutions to this issue?

EDIT: The code works correctly with server-side rendering, but the response headers are not accessible on the client-side.

Answer №1

Dealing with a similar problem, I encountered difficulties retrieving the location header in my project. Despite adding the 'Access-Control-Expose-Headers' header and ensuring that it is present in the server-side component, I found that the location header did not make it to the client side. It seemed to disappear without a trace when transitioning from server to client.

I'm curious if you've managed to find a solution to this issue?

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

I'm looking for some help with creating a visualization using JavaScript or Python. Can anyone offer some guidance?

// Defining the dimensions and margins of the graph var width = 460 var height = 460 // Appending the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width) .attr("height", height) // Reading ...

Using the jQuery before() method to manipulate form fields

Is it possible to utilize the jQuery before method to insert a form? An example scenario could be as shown below: <script> $(document).ready(function() { $("button").click(function() { $("button").before('<form><input type="text ...

Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox. However, I'm facing an issue ...

What is the best way to pass the values of two interlinked drop-down menus through an AJAX post request to a Django view?

Presently, I am encountering an issue with sending the values of two dropdowns to a django view. My code would have functioned correctly if the dropdowns were independent. Unfortunately, this is not the case as the first one updates the second one. Therefo ...

Arranging an Array Object in Javascript by Date

Although similar questions have been addressed in other posts, my specific situation appears to be unique due to the data I am receiving from Twitter. Here is the logic I am currently using to sort the JavaScript Array object. However, the issue seems to ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

Enhance the axis functionality in c3.js

My goal is to display a user's financial data for the previous week, but sometimes they may not have data for all seven days. When using c3.js, I noticed that it automatically extends the 'endpoint-value' to the end of the axis. Is there a w ...

Is it possible to incorporate two ng-repeat directives within a single td element in a table?

The results so far Expected outcome Please advise me on how to incorporate two ng-repeats within one td. When I use a span tag afterwards, the expected result is not achieved. I have used one ng-repeat in the td and the other in a span tag, which is why t ...

Javascript provides the ability to return a JSON object containing a specific function name

Currently, I am in the process of mastering AngularJS, and recently came across this code snippet: .factory('cribs',function(){ var data = [{ name: "jack", last: 'doe' },{ name: 'hazel&apos ...

Sending all form input data to Ajax for GET request

Today, my goal is to iterate through each textbox with an ID of setting_value, set its name and value to a key-value array, and then send that data in an Ajax request. The problem I'm facing is that it only seems to be inspecting the first instance o ...

Invoking a HTTP request in a web service using the link method

Upon the initial page load, a successful RESTful call is made to retrieve data. However, when clicking on the left navigation links that display this data, another RESTful call needs to be made. I am attempting to achieve this functionality within the link ...

Why is my IEDriverServer typing so slow? Seeking JavaScript solutions

While working with Selenium and IEDriverServer, I have encountered an issue where the keys are being sent to the input at a very slow pace. After conducting some research, many websites recommend ensuring that the Browser and IEDriverServer are of the sam ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Leveraging environment variables in a 'use client' module within a Next.js application

I am facing the issue of not being able to access my .env variables such as GraphQL URL and access token in a 'use client' Apollo context wrapper component that is rendered client-side. Is there any solution for this in Next.js v13? Here is the ...

Using MEAN.JS to Define Query Parameters for Mongo from the Client Controller

I am currently developing an application using the MEAN stack - MongoDB, Angular, Express, and Node.js. To kickstart my project, I utilized the MEAN.JS generator to set up the initial structure of my application. The articles module within my application ...

Experiencing difficulty retrieving the variable within a NodeJs function

Currently, I am utilizing the NodeJS postgresql client to retrieve data, iterate through it and provide an output. To accomplish this, I have integrated ExpressJS with the postgresql client. This is a snippet of my code var main_data = an array conta ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

Challenges arising from updating the size and position of a div element during a mouse move event

As I work on creating a basic horizontal split pane using HTML, CSS, and JavaScript, I have drawn inspiration from this post. While the vertical split pane functions smoothly, the horizontal version seems to be glitchy. The sizes and positions of the div ...

Click on a designated button to choose a specific file on an HTML page

I need to be able to select a specific file by clicking on another button. A helpful solution that utilizes JavaScript to trigger the selection of a hidden file can be found in this answer. You can view the implementation here. In my scenario, I alre ...

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...