Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API.

const baseUrl = () => {
    const protocol = process?.env.NODE_ENV === "development" ? "http" : "https";
    const host = headers().get("host");
    const baseUrl = `${protocol}://${host}`;
    return baseUrl;
}
export const fetchUser = async () => {
    try {
        console.log(`${baseUrl()}/api/getUser`);
        const response = await fetch(`${baseUrl()}/api/aps/getUser`, { method: 'GET', headers: headers() });
        const data = await response.json();
        return data.data;
    } catch (error) {
        console.error("Error fetching user:", error);
    }
};

Everything is functioning correctly on my end, headers().get("host") is returning localhost:3000 as intended.

However, another developer working on this project locally is seeing a different value instead of localhost:3000. They are getting [::1]:59982, with the port number changing each time.

I am confused about where this alternate value is originating from. Any insights?

Answer №1

Encountered a similar issue while updating the node version. I resolved it by implementing a middleware and including a custom header.

Here is the middleware code snippet:

const reqHeaders = new Headers(req.headers);
reqHeaders.set('x-request-url', req.url);

return NextResponse.next({ headers: reqHeaders });

Then, access the header like this:

const host = headers().get("x-request-url");

Hopefully, this solution works for you as well.

Answer №2

It appears that the Node version may be a factor in this issue. I have not encountered this problem on version 16.20.2, but I do experience it on versions 18.18.2 and 20.9.0.

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

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

Converting a floating point number to a 4-byte hex string in JavaScript and reversing the process

I have received a hexadecimal data from the server side that is supposed to be in float format. I am trying to convert these hexadecimals into floats using JavaScript, but so far I have been unable to find a suitable method. Can anyone provide assistance ...

Determining the query count in a MongoDB collection using Node.js

Exploring the world of MongoDb, I have embarked on a project to create a small phonebook application. This application allows users to add and remove entries with a name and phone number. While I have successfully implemented the functionality to add and d ...

Differences between Next.js <a> tag and passHref

Could someone provide some insights on the distinction between using passHref and an anchor tag when creating links between pages in Next.js? For example, what separates: <Link href={`/posts/${post.id}`} passHref> <h2> {post.id} {post.ti ...

Oops! There seems to be a server error with the PDFDownloadLink API. It appears that you are trying to use this web-specific API on Node, or perhaps your bundler is not loading react-pdf properly

I have developed a Report card generator in Next.js, and I am currently experimenting with the use of @react-pdf/renderer to generate PDFs before integrating it into my main project. However, I am encountering an error that I can't seem to resolve. S ...

Prefering `window.jQuery` over the yarn version

I am currently in the process of transitioning to Vite 3 with Vite Ruby on Rails from Webpacker and Webpack. One major issue I have encountered is that my system functions as a CMS. Some of our long-standing clients have jQuery code embedded directly withi ...

Disparity in React app: Misalignment between debugger and console output

Throughout the years, I've encountered this issue in various ways, and I have finally been able to articulate it. Take a look at the code snippet below: import React, {Component} from "react"; import aFunction from "./Function"; export default class ...

Optimal strategies for initializing Knockout JS models from backend code

Upon taking over a website that utilizes knockout js and asp.net, I noticed some performance issues during the initial page load. After investigating, I found that there are approximately 20 models on the site, each making an ajax call to retrieve data fro ...

Utilizing the Kraken.com API to create a message signature with AngularJS

I'm currently tackling Angular2 and for my first project, I want to tap into the Kraken.com API. (I know, I could have chosen an easier task :) The "Public" calls are working smoothly, but I've hit a snag with the "Private" methods. (Those requi ...

Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong? var insert = function(array, rightIndex, value) { for(var j = rightIndex; j & ...

Utilizing the Express-busboy npm package to generate a new directory within the public folder of

While working on my controller, I encountered an issue when trying to readFile sent from the browser via AJAX. Unexpectedly, a directory was created in my public folder with a name like '3d6c3049-839b-40ce-9aa3-b76f08bf140b' -> file -> myfile ...

Ways to troubleshoot NPM installation issues related to gyp ERR

I have tried most of the suggestions found online, but I am still encountering an error when trying to install opencv and serialport. My current setup includes Visual Studio 2019 with C++ Desktop environment and Python 3.7. npm ERR! command C:\Windows ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Tips for implementing ajax and codeigniter to load additional comments on a web page

Is it possible to customize Codeigniter's default pagination to achieve a "viewMore" link style when loading more records using AJAX? The challenge lies in creating a div that automatically expands to handle large numbers of records, such as 10,000 a ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...