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

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

Differences between Next.js Image and regular img tag regarding image quality

I am currently using Next.js and have noticed that my images appear slightly blurry when utilizing Next/Image. Below is a snippet of my code: <img src={url} width={articleWidth} /> <Image className="text-center" src={url} ...

Can terminating a POST XHR request be trusted?

Running an apache server with PHP 5.4. I've set up a form that sends an asynchronous request to the server and stops any previous requests if the button is clicked again before the current request is completed. If I repeatedly click the button quick ...

The process of generating a querystring from a form using jQuery is not functioning as expected

I am attempting to send an AJAX request, but I am facing an issue where the query string I am trying to construct turns out to be empty. <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>This project dem ...

Tips for disabling autofocus on Mui Menu Items

Incorporating a search functionality within a custom Mui Select component where the user can input a city or country to filter down the options list. The current issue is that when a user types a letter that matches the first letter of an option, the opt ...

Having trouble posting data in node.js using MongoDB and EJS

Hey everyone, I'm currently working on creating a page with a form and text input fields. However, I'm encountering an error that says "Cannot Post". Here is my code, any help would be greatly appreciated. Why isn't it working? This is app. ...

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

Adding an external JavaScript file to an HTML document by importing an array

Having trouble loading an array from an external JS file into my HTML. Snippet from js.js: var temp_max = [4,9,2,5,8,4,2,10]; In the HTML: Note: Be sure to download DateJS and place it in "DATE-JS"!! <!doctype html> <html> ... (HTML c ...

How can I trigger the opening of an iframe without relying on jQuery when the user clicks on it?

I'm looking to create a UI where the user can click on an image and have an iframe appear on top of the image. Instead of using JQuery, I want to stick with pure JavaScript for this functionality. ...

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...

Setting up a custom function for the cancel button in Angular X-editable

Can this be done? I've got a code snippet that resembles the following: <div class="popover-wrapper"> <a class="glyphicon glyphicon-time" ng-if="activity.type === 'continuous'" ng-style=" { 'border': 'none', ...

Securing User Profiles in Firebase

I am currently working on a coding issue that involves the security of user profiles. While it doesn't involve sensitive information like payment details or personal data, it does pertain to the ownership of a profile. Currently, I store users' ...

Having difficulty deleting cookies in a Next.js production environment

I'm currently building an application using NextJs and I've implemented cookie authorization when a user logs in: res.setHeader("Set-Cookie", [ cookie.serialize("authorization", `Bearer ${jwtGenerated}`, { ht ...

The useFormState function in Next.js fails to retrieve messages from server actions

When it comes to receiving a message back from the server action, I need to ensure that both validation and authentication were successful. The login method is functioning correctly as I have tested it. However, the issue lies in the fact that the message ...

What is the Best Way to Enable Tooltips to Function from External Elements?

I am currently designing a map that features points with tooltips. When hovered over, the tooltips function correctly. I am interested in exploring the possibility of making the tooltips interact with an external navigation bar. My goal is to have specifi ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

Serious issue: a dependency request is an expression (Warning from Angular CLI)

I am currently exploring the dynamic loading of lazy child routes within a lazy routing module. For example: const serverResponse = [ { path: "transaction", children: [ { path: "finance", modulePath: &qu ...

`Incorporating dynamic link filtering in vis.js`

Can links and nodes be filtered in a vis.js network? I have configured a DataSet for both nodes and edges as follows: function drawNetwork(container){ var nodes = new vis.DataSet(); populateNodes(nodes); // implementation details skipped ...

Encountering an issue with locating 'react-firebase-hooks'

I've been working on a project using Next.js and recently added the package called react-firebase-hooks to it. Here is an excerpt from my Package.json file: { "name": "whatsapp", "version": "0.1.0", " ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...