2

Using credentials in url with fetch:

fetch('https://test:test@example.com').catch(console.error)

Results in an error:

TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials

This is correct according to the specs:

If parsedURL includes credentials, then throw a TypeError.

What is the reason to put a restriction like this?

Is using credentials in url a bad practice?

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 3
    From security perspective it's a bad practice because URLs are being logged on servers, proxy servers, can be hijacked by man-in-the-middle. In HTTPS URLs are not encrypted, only request itself is encrypted. – Vlad DX Feb 23 '23 at 00:14
  • 2
    Related: https://stackoverflow.com/questions/45781924/how-to-pass-credentials-through-a-fetch-request – jarmod Feb 23 '23 at 00:15
  • 3
    https://neilmadden.blog/2019/01/16/can-you-ever-safely-include-credentials-in-a-url/, https://github.com/whatwg/fetch/issues/26, https://github.com/w3c/resource-timing/issues/368, etc. – Dave Newton Feb 23 '23 at 00:18
  • As you asked "Is using credentials in url a bad practice?" Yes, it is very very bad and risky practice. – Om Sao Feb 23 '23 at 00:58
  • 2
    Plenty of reasons why but for an answer as to why they decided to make this a hard restriction, you'd need to speak to the specification authors. And really, it all just comes down to some individual or group's opinion – Phil Feb 23 '23 at 00:59
  • 1
    These sorts of questions are really some of my least favourite to see on StackOverflow because while they might represent an interesting topic, they are very difficult to answer canonically. See [Is asking "why" on language specifications still considered as "primarily opinion-based" if it can have official answers?](https://meta.stackoverflow.com/q/323334/283366) – Phil Feb 23 '23 at 01:06
  • 2
    @VladDX "*In HTTPS URLs are not encrypted*" - [sure they are](https://stackoverflow.com/q/499591/1048572)! And the credentials [would typically be sent in a header](https://serverfault.com/q/371907/492195) anyway, not as part of the URL. – Bergi Feb 23 '23 at 01:07
  • 1
    @Bergi, today I've learnt 2 things I'll remove my comment to not confuse people. But you could keep yours – Vlad DX Feb 23 '23 at 06:57
  • Thank you all for the comments, they explain a lot :) – Konrad Feb 23 '23 at 10:32

0 Answers0