Skip to content

Commit

Permalink
Avoid infinite recursion from window.fetch name collision
Browse files Browse the repository at this point in the history
Closes [hotwired#526][]

Prevent naming collisions between the new `Turbo.fetch` function and the
built-in `window.fetch` function.

To do so, create a module-local reference to `window.fetch`, and define
the exported function as `fetchWithTurboHeaders`. At export-time, rename
to `fetch` so that consumers can continue to import it as `Turbo.fetch`.

[hotwired#526]: hotwired/turbo-rails#526
  • Loading branch information
seanpdoyle committed Nov 27, 2023
1 parent 1aa7a87 commit 9a4c994
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/http/fetch.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { uuid } from "../util"

export function fetch(url, options = {}) {
const nativeFetch = window.fetch

function fetchWithTurboHeaders(url, options = {}) {
const modifiedHeaders = new Headers(options.headers || {})
const requestUID = uuid()
window.Turbo.session.recentRequests.add(requestUID)
modifiedHeaders.append("X-Turbo-Request-Id", requestUID)

return window.fetch(url, {
return nativeFetch(url, {
...options,
headers: modifiedHeaders
})
}

export { fetchWithTurboHeaders as fetch }
1 change: 1 addition & 0 deletions src/tests/unit/export_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ test("Turbo interface", () => {
assert.equal(typeof Turbo.cache.clear, "function")
assert.equal(typeof Turbo.navigator, "object")
assert.equal(typeof Turbo.session, "object")
assert.equal(typeof Turbo.fetch, "function")
})

test("StreamActions interface", () => {
Expand Down

0 comments on commit 9a4c994

Please sign in to comment.