question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

httpLink/httpBatchLink on fetch redirect

See original GitHub issue

Provide environment information

  System:
    OS: macOS 11.6.8
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 610.94 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 18.11.0 - ~/.nvm/versions/node/v18.11.0/bin/node
    npm: 8.19.2 - ~/.nvm/versions/node/v18.11.0/bin/npm
  Browsers:
    Brave Browser: 107.1.45.113
    Chrome: 106.0.5249.119
    Firefox: 105.0.3
    Safari: 15.6.1
  npmPackages:
    @tanstack/react-query: 4.10.0 => 4.10.0 
    @trpc/client: 10.0.0-proxy-beta.17 => 10.0.0-proxy-beta.17 
    @trpc/next: 10.0.0-proxy-beta.17 => 10.0.0-proxy-beta.17 
    @trpc/react: 10.0.0-proxy-beta.17 => 10.0.0-proxy-beta.17 
    @trpc/server: 10.0.0-proxy-beta.17 => 10.0.0-proxy-beta.17 
    next: 12.3.1 => 12.3.1 
    react: 18.2.0 => 18.2.0 
    typescript: 4.8.4 => 4.8.4 

Describe the bug

Im trying to utilise NextJs middleware in order to protect all my pages/api routes but I have a problem with api/trpc route. After lurking around I found out that the problem lies in httpLink/httpBatchLink due to fetch being used by those. Nextjs middleware doing a redirect makes that the api/trpc/... request will be text/html response instead of application/json which in turn makes httpLink/httpBatchLink throw an error due it expecting an json response.

Flow: Incoming request -> NextJs Middleware pick up /api/trpc/… -> NextJs Middleware redirects /api/trpc request to say /xyz -> httpLink/httpBatchLink retrieves request for /api/trpc/… making a fetch to it -> fetch response here is text/html instead of application/json and it throws

So Could text/html response be handled within httpLink/httpBatchLink so It would be possible to get back redirect url from such redirected route??

Something like ex. https://github.com/trpc/trpc/blob/013c2f281be7eb0e268a59b978509cce7102935f/packages/client/src/links/internals/httpUtils.ts#L141

.then((_res) => {
        // ----------------------------------------------
        const contentType = _res.headers.get("content-type");

        if (contentType === 'text/html' && _res.ok && _res.redirected) {
          // either
          // throw relevat error type with _res.url so then It can be retreived for making redirect
          // handle this somehow for trpc as a valid response and also pass the _res.url so it can be retreived for making redirect
        }

        meta.response = _res;
        return _res.json();
      })

Link to reproduction

https://stackblitz.com/edit/github-bbi6vz-nfthcr?file=pages/xyz.tsx

To reproduce

Open stackblitz example. There is a middleware which redirects trpc/api requests to /xyz page. In the console you would see TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON because redirect makes the trpc/api response as text/html not application/json

Additional information

Simply put, the browser won’t do document follow on a redirect originated from a fetch request.

So I would expect to be able to somehow retrieve the redirect url from within the httpLink/httpBatchLink because thats the one responsible to making that fetch call.

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I’d be down to file a PR fixing this bug!

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
stychucommented, Oct 28, 2022

Why? If someone redirects a tRPC query, we have to support that. We’re not going to override the default fetch but feel free to do so yourself.

For tRPC, you could special case the /api/trpc route and use a tRPC middleware for your auth check. This way you can return a TRPCError and properly handle that on the client.

Yeah you are right. It was late at night when I was playing with fetch queries and though this can be a good idea:P

1reaction
KATTcommented, Oct 27, 2022

Fair, we should probably have some try/catch in our observer implementation and make it a tRPC error if something goes wrong.

Read more comments on GitHub >

github_iconTop Results From Across the Web

redirect after a fetch post call - reactjs - Stack Overflow
I am creating an social login page with an Access Management (AM) server. When user click on the login button then I make...
Read more >
Response.redirected - Web APIs - MDN Web Docs
The read-only redirected property of the Response interface indicates whether or not the response is the result of a request you made which...
Read more >
Won't redirect after fetch post request · Issue #843 - GitHub
I've a login form in an island: // islands/Login.tsx export default function Login() { const [username, setUsername] = useState(""); ...
Read more >
522873 - Change the fetch API request flags (mode ... - Monorail
Issue 522873: Change the fetch API request flags (mode, credentials and redirect) for navigation requests. Reported by schedule horo@chromium.
Read more >
Fetch API - The Modern JavaScript Tutorial
You may skip this chapter and still use fetch well. ... no-store, reload, no-cache, force-cache, or only-if-cached redirect: "follow", ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found