Sub topic 1
Anatomy of a URL
A URL (Uniform Resource Locator) is the string that tells a browser what to fetch and how to fetch it. Every later stage of a page load, from DNS to TLS to HTTP, takes its inputs from the parts of this string. This chapter splits a URL into those parts and covers the edge cases that cause real bugs.
Prerequisites
This chapter assumes you can:
- Use a web browser and read a simple address such as
https://example.com/. - Recognize that pages are built from HTML, CSS and JavaScript.
- Say roughly what an IP address is (a numeric address for a machine on a network).
- Read short JavaScript snippets. The examples run in a browser console or in Node.js 10 and later.
The parts of a URL
Take this URL:
https://example.com:8443/docs/intro?lang=en&ref=home#setupIt breaks down into six components.
| Component | Example | What it tells the browser |
|---|---|---|
| Scheme | `https` | Which protocol to speak |
| Host | `example.com` | Which machine to contact |
| Port | `8443` | Which service on that machine |
| Path | `/docs/intro` | Which resource on the server |
| Query | `?lang=en&ref=home` | Extra parameters for the resource |
| Fragment | `#setup` | A location inside the document |
The scheme ends at the first :. The text // that follows introduces the authority, which holds the host and the optional port. Some URLs also carry credentials in the authority (user:pass@host). Browsers still parse these, but you should avoid them because the credentials end up in history and logs.
Parsing a URL in code
JavaScript has a standard URL class. It performs the same split the browser does before it touches the network.
const url = new URL('https://example.com:8443/docs/intro?lang=en&ref=home#setup');
console.log(url.protocol); // 'https:'
console.log(url.hostname); // 'example.com'
console.log(url.port); // '8443'
console.log(url.pathname); // '/docs/intro'
console.log(url.search); // '?lang=en&ref=home'
console.log(url.hash); // '#setup'Note the details in the output. protocol includes the trailing colon. search includes the leading ?. hash includes the #. Code that compares these values against bare strings such as 'https' fails for this reason.
Scheme
The scheme selects the protocol and the default port. Common schemes are https, http, file, data and mailto. For a page load, the two that matter are:
http: unencrypted HTTP, default port 80.https: HTTP over TLS, default port 443.
The scheme is case-insensitive, and the parser lowercases it. A typo such as htps:// is not a web URL at all, so the browser cannot treat it as a navigation.
Host
The host names the server. It is either a domain name such as www.example.com or an IP address such as 93.184.216.34. IPv6 addresses go in square brackets so their colons are not confused with the port separator: http://[2001:db8::1]:8080/.
A domain name is a series of labels separated by dots, read from right to left in order of specificity:
comis the top-level domain.exampleis the registered domain under it.wwwis a subdomain chosen by the owner.
Host names are case-insensitive. Browsers lowercase them, so EXAMPLE.com and example.com reach the same server. The host is the input to DNS resolution, covered in a later chapter. It also becomes the Host header in the HTTP request.
Internationalized domain names
Domain names on the wire are ASCII only. A name with other characters is converted to Punycode, which prefixes each non-ASCII label with xn--. The URL class does this for you:
const u = new URL('https://münchen.example/');
console.log(u.hostname); // 'xn--mnchen-3ya.example'This conversion is also why look-alike attacks exist. A domain that uses a Cyrillic а in place of a Latin a looks the same on screen but resolves to a different server. Browsers show the Punycode form in some cases to expose this.
Port
The port selects a service on the host, so one machine can run many servers. If the URL leaves it out, the scheme supplies the default.
The URL class hides default ports. It reports an empty string instead of the number:
console.log(new URL('https://example.com:443/').port); // ''
console.log(new URL('https://example.com/').port); // ''
console.log(new URL('https://example.com:8443/').port); // '8443'Use url.host rather than url.hostname when you need the host and port together. It includes the port only when the port is not the default.
Path
The path identifies a resource on the server. It begins with / and uses / as a separator, which looks like a file system. This resemblance is only a convention. The server decides what a path means. It may map to a file, to a database lookup, or to application code.
Two details cause trouble:
- Paths are usually case-sensitive on the server, even though the host is not.
/Docsand/docscan be different resources. - Dot segments are resolved by the client before the request is sent.
/docs/../aboutbecomes/about.
A trailing slash can also matter. /docs and /docs/ are different paths, and servers often redirect one to the other. This affects how relative links resolve, as shown below.
Query
The query starts after ? and holds parameters. By convention it is a list of name=value pairs joined by &. The URL standard does not require that format, but nearly every site uses it. The URLSearchParams class reads and writes it:
const url = new URL('https://example.com/search?q=cats&page=2');
const params = url.searchParams;
console.log(params.get('q')); // 'cats'
console.log(params.get('page')); // '2'
params.set('page', '3');
params.append('sort', 'new');
console.log(url.href);
// 'https://example.com/search?q=cats&page=3&sort=new'get always returns a string, so '2' is not the number 2. Convert it yourself.
Fragment
The fragment starts at #. It refers to a place inside the document, usually the element whose id matches, such as <h2 id="setup">.
The browser never sends the fragment to the server. The HTTP request line for the example URL contains only the path and the query:
GET /docs/intro?lang=en HTTP/1.1
Host: example.com
Accept: text/html
User-Agent: example-client
Connection: keep-aliveThe Host header carries the host (plus the port if it is not the default). The fragment appears nowhere. Two consequences follow:
- Changing only the fragment does not reload the page. The browser scrolls to the new target.
- Server code can never read the fragment. Do not put data there that the server needs.
Single-page applications sometimes use the fragment for client-side routing for this reason.
Percent-encoding
Some characters have a reserved meaning in a URL, such as ?, #, &, / and =. Others, such as spaces, are not allowed at all. To include them as data, you write each byte as % followed by two hexadecimal digits. A space becomes %20. A non-ASCII character is first encoded as UTF-8 bytes, and each byte is then escaped.
console.log(encodeURIComponent('a&b=c d')); // 'a%26b%3Dc%20d'
console.log(encodeURIComponent('é')); // '%C3%A9'
const url = new URL('https://example.com/search');
url.searchParams.set('q', 'fish & chips');
console.log(url.href);
// 'https://example.com/search?q=fish+%26+chips'In the last example, URLSearchParams writes a space as +. That form is valid only inside the query. In a path, a space must be %20.
The most common bug is double encoding. If you encode a string that is already encoded, %20 becomes %2520, and the server receives literal %20 text. Encode each value exactly once, at the point where you build the URL, and preferably let URLSearchParams do it.
Relative URLs
A link in a page does not have to be a full URL. The browser resolves it against a base URL, normally the address of the current page.
const base = 'https://example.com/docs/intro';
console.log(new URL('setup', base).href); // 'https://example.com/docs/setup'
console.log(new URL('/about', base).href); // 'https://example.com/about'
console.log(new URL('../img/a.png', base).href); // 'https://example.com/img/a.png'
console.log(new URL('//cdn.example.net/x.js', base).href); // 'https://cdn.example.net/x.js'
console.log(new URL('?lang=fr', base).href); // 'https://example.com/docs/intro?lang=fr'
console.log(new URL('#top', base).href); // 'https://example.com/docs/intro#top'Each form follows a rule:
- A bare name replaces the last segment of the base path.
- A leading
/starts from the root of the same host. - A leading
//keeps the scheme and replaces the host. - A leading
?or#keeps the whole path and replaces the query or fragment.
Because a bare name replaces the last segment, the trailing slash matters. With the base https://example.com/docs/, the link setup resolves to /docs/setup. With the base https://example.com/docs, the same link resolves to /setup.
Origin and why it matters
The scheme, host and port together form the origin. Browsers use it as a security boundary. The page at https://example.com cannot freely read responses from https://example.com:8443 or from http://example.com, because each has a different origin.
const a = new URL('https://example.com/a');
const b = new URL('https://example.com:8443/b');
console.log(a.origin === b.origin); // falseThe path, query and fragment are not part of the origin.
Common errors
- Missing scheme. Writing
example.com/pagein code produces a relative URL, not a web address. In the address bar, the browser guesses the scheme for you, which is the topic of the next chapter. - Comparing
url.portwith443as a number. It is a string, and it is empty for the default port. - Building URLs by string concatenation. Unescaped
&or#in a value silently truncates or corrupts the query. UseURLandURLSearchParams. - Expecting the server to see the fragment.
- Treating the path as case-insensitive.
Summary
A URL gives the browser everything it needs to start. The scheme picks the protocol and default port. The host feeds DNS. The port feeds the TCP connection. The path and query go into the HTTP request line. The fragment stays in the browser.
Exercise
Given the base URL https://example.com/docs/guide/start and the link ../api?v=2#top, what absolute URL does the browser produce, and which of its parts are sent to the server?
Show answer
The result is https://example.com/docs/api?v=2#top. The bare-name rule drops the last segment "start", leaving /docs/guide/, and ".." then removes "guide", so "api" resolves to /docs/api. The server receives the path and query (GET /docs/api?v=2) and the host in the Host header. The fragment #top is never sent.
Exercise
A developer builds a search link with the string 'https://example.com/search?q=' + 'R&D #1'. What does the server receive for q, and how should the code be fixed?
Show answer
The server receives q=R only. The unescaped & starts a new parameter named D and the # starts a fragment, which is not sent at all. Build the URL with URLSearchParams, for example url.searchParams.set('q', 'R&D #1'), so the value is percent-encoded as R%26D+%231.