Pool and Client don't follow redirects to a different host
Bug Description
When a request is made for a URL that returns a redirect to another host, Pool and Client do follow the redirect but do not change the destination host. The request goes to the same base host as the Pool, but with the path changed.
Reproducible By
import http from 'node:http';
import { promisify } from 'node:util'
import { Pool, request } from "undici";
// Server that does the work
const requestListener1 = function (req, res) {
res.writeHead(200);
res.end('Hello, World!');
}
const server1 = http.createServer(requestListener1);
const listen1 = promisify(server1.listen.bind(server1))
await listen1(5100)
// Server that redirects to server1
const requestListener2 = function (req, res) {
if (req.url === "/redirect") {
res.writeHeader(303, {
'location': 'http://localhost:5100/newpath'
})
res.end();
} else {
console.log("Path", req.url)
res.writeHead(200);
res.end('Should never happen');
}
}
const server2 = http.createServer(requestListener2);
const listen2 = promisify(server2.listen.bind(server2))
await listen2(5101)
// Using request everything works as expected
const { body: bodyRequest } = await request("http://localhost:5101/redirect", { method: "GET", maxRedirections: 1 })
const textFromRequest = await bodyRequest.text()
// This line prints "Hello, World!"
console.log(`Request: ${textFromRequest}`)
// Using Pool or Client it does not update the host
const pool = new Pool("http://localhost:5101")
const { body: bodyPool } = await pool.request({ method: "GET", path: "/redirect", maxRedirections: 1 })
const textFromPool = await bodyPool.text()
// This line prints "Should never happen"
console.log(`Pool: ${textFromPool}`)
server1.close()
server2.close()
Expected Behavior
Calls made with Pool or Client returns the same result as request.
Environment
macOS - node v18.12.0
Additional context
I don't know if it's a bug or this behavior is expected.
My scenario is that I have an API that returns a redirect to an AWS S3 url, and I use maxRedirections to directly receive the file stream.
If this is an expected behavior, is there any way to use a Pool in cases like this?
Thanks!
Pool and Client are single-origin objects, they only maintain the connection to a single destination. In order to support redirects cross-origin, you'd need to use an Agent.
Thee is still a bug here, as it should not redirect to the same host. If the host differs, the redirect should stop.
You are right. This behavior is clear in the documentation. It was my inattention when reading the documentation.
Should I leave the issue open because of the redirect? For me everything is ok.
Yes, leave it open!