Next.js 13 - next/headers returning strange value for host

225 Views Asked by At

I have a Next.js project and I'm using next/headers to programmatically return a baseUrl for requests 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);
    }
};

This works fine on my machine, headers().get("host") returns localhost:3000 as expected.

I have another developer who is also running the project locally, but instead of localhost:3000 he is getting the value [::1]:59982, where the 5-digit port at the end changes each time.

Where is this value coming from?

2

There are 2 best solutions below

0
On BEST ANSWER

I came across with the same issue when upgrading node version. I solve it using a middleware and adding a custom header.

In the middleware:

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

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

And then get the header

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

I hope this can help you

0
On

Seems like Node version has something to do with it. I do not get this issue on v 16.20.2, but I do on v 18.18.2 and v 20.9.0.