javascriptnext.jsrequest-headers

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


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?


Solution

  • 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