Skip to main content
Back to Blog

URL Anatomy: Parsing and Building Robust Links

Scheme, host, path, query, and fragment explained, plus how to parse and build URLs safely in code and APIs.

Kashyap Thakar
7 min
WebURLHTTP
URL Anatomy: Parsing and Building Robust Links

The Uniform Resource Locator (URL) is the address system of the web. While we type them daily, their internal structure is more complex than it appears. Understanding this anatomy is crucial for frontend routing, API design, and SEO.

The Components

Let's dissect a typical URL:
https://api.example.com:8080/v1/users?sort=desc#profile

  • Protocol (Scheme): https - Defines how to communicate (HTTP, FTP, Mailto).
  • Subdomain: api - A subset of the main domain.
  • Domain: example.com - The unique address of the server.
  • Port: 8080 - The TCP port on the server (the defaults are 80 for HTTP and 443 for HTTPS).
  • Path: /v1/users - The specific resource or page being requested.
  • Query String: ?sort=desc - Key-value pairs for filtering or tracking.
  • Fragment (Hash): #profile - A specific section within the resource (client-side only).

The Danger of String Concatenation

A common mistake is building URLs like this:

const url = "https://api.com/search?q=" + query;

If query contains &, #, or +, the value is cut off or changes meaning, and spaces and non-ASCII characters are left for the parser to guess at. Use URL and URLSearchParams, or at least encodeURIComponent on the value.

URL Components Deep Dive

Protocol (Scheme)

The protocol determines how the browser communicates with the server:

  • http:// - Hypertext Transfer Protocol (unencrypted)
  • https:// - HTTP over TLS (encrypted)
  • ftp:// - File Transfer Protocol
  • mailto: - Opens email client
  • file:// - Local file system

Domain Hierarchy

Domains are hierarchical, read from right to left:

api.v2.example.com
└─ com (Top-Level Domain)
   └─ example (Second-Level Domain)
      └─ v2 (Subdomain)
         └─ api (Subdomain)

Query Parameters

By convention, query strings use key=value pairs separated by &. RFC 3986 itself only defines the query as non-hierarchical data. The pair format comes from HTML forms:

?category=electronics&sort=price&page=2
└─ category = "electronics"
└─ sort = "price"
└─ page = "2"

Values must be URL-encoded if they contain special characters. For example, "hello world" becomes "hello%20world".

Fragment (Hash)

The fragment (everything after #) is never sent to the server. It's used for:

  • Linking to specific sections of a page (anchor links)
  • Client-side routing in Single Page Applications (SPAs)
  • JavaScript state management

URL Encoding Requirements

Certain characters have special meanings in URLs and must be encoded:

CharacterEncodedReason
Space%20 or +Not allowed in URLs
&%26Parameter separator
#%23Fragment identifier
=%3DKey-value separator

The + form of a space is only valid inside query strings that follow the application/x-www-form-urlencoded convention (HTML forms, URLSearchParams). In a path, + is a literal plus sign, so a space there must be %20.

Relative vs. Absolute URLs

URLs can be absolute (complete) or relative (partial):

  • Absolute: https://example.com/path/to/page - Contains everything needed
  • Relative: /path/to/page - Resolved relative to current domain
  • Protocol-relative: //example.com/path - Uses current protocol (http or https)

Authority, Origin, and Host: Three Different Things

The list above treats the part between // and the first / as separate pieces, but the URL Standard groups them. The authority is the optional userinfo@, the host, and the optional :port. The origin that browsers use for the same-origin policy and CORS is only the scheme, host, and port, so https://example.com and https://example.com:8443 are different origins, as are http and https versions of the same host. Paths, queries, and fragments never affect origin. See CORS Explained for what that means in practice.

Note also that "subdomain" and "domain" are conventions, not parts of the URL grammar. A parser sees one host string such as api.example.com. Deciding where the registrable domain ends (example.com versus example.co.uk) requires the Public Suffix List, not string splitting.

Parsing a URL in JavaScript

Instead of splitting strings or writing regular expressions, use the built-in URL class, which implements the WHATWG URL Standard in browsers and Node.js. Parsing the example URL with a username and password added:

const u = new URL("https://user:pass@api.example.com:8080/v1/users?sort=desc&sort=asc#profile");

u.protocol  // "https:"
u.username  // "user"
u.password  // "pass"
u.host      // "api.example.com:8080"
u.hostname  // "api.example.com"
u.port      // "8080"
u.pathname  // "/v1/users"
u.search    // "?sort=desc&sort=asc"
u.hash      // "#profile"
u.origin    // "https://api.example.com:8080"

Three details trip people up. protocol includes the trailing colon, search and hash include their leading ? and # (and are empty strings when absent), and host includes the port while hostname does not. The port is also empty when it equals the scheme's default, so new URL("https://example.com:443/a").href returns https://example.com/a and port is "".

The constructor throws a TypeError on input it cannot parse, for example a relative string with no base. Wrap it in try/catch, or use URL.canParse(input, base), which returns a boolean in current Node.js and modern browsers. Paste any URL into the URL Parser to see the same breakdown without writing code.

How Relative References Are Resolved

A relative reference is resolved against a base URL, usually the page's own address. The result depends on the base's path, in particular on whether it ends with a slash. With the base https://example.com/docs/guide/intro, these are the actual results from new URL(reference, base):

ReferenceResolves to
setuphttps://example.com/docs/guide/setup
../setuphttps://example.com/docs/setup
/setuphttps://example.com/setup
//cdn.example.com/x.jshttps://cdn.example.com/x.js
?page=2https://example.com/docs/guide/intro?page=2
#tophttps://example.com/docs/guide/intro#top

The first row is the classic trailing-slash trap: because the base path is /docs/guide/intro, the last segment (intro) is replaced. Had the base been /docs/guide/intro/, setup would resolve to /docs/guide/intro/setup. This is why a missing trailing slash makes relative image and link paths "break" on some pages.

What the Parser Normalizes for You

Parsing is not just splitting. The URL Standard defines normalization steps that can change the string you passed in:

  • Case: scheme and host are lowercased, but the path is not. HTTPS://EXAMPLE.com/Path becomes https://example.com/Path.
  • Dot segments: /a/./b/../c collapses to /a/c.
  • Default ports: removed, as shown above.
  • Empty path: an HTTP URL with no path gets /, so https://example.com serializes as https://example.com/.
  • Unsafe characters: spaces and non-ASCII characters in the path, query, and fragment are percent-encoded (/a b becomes /a%20b).
  • Internationalized hosts: converted to Punycode, so bücher.example becomes xn--bcher-kva.example.

Normalization matters when you compare URLs. Comparing raw strings will treat https://example.com and https://example.com/ as different, while comparing new URL(a).href === new URL(b).href will not. Note that a trailing slash on a non-empty path (/a versus /a/) is never normalized away, since servers may treat them as different resources.

Fragments Are Not Part of the Request

Browsers strip the fragment before sending a request, so your server logs, analytics on the server side, and redirects never see it. That has practical consequences. Server-side code cannot read #section, and a redirect that drops the fragment is a browser decision, not a server bug. Single-page apps that use hash routing store the route in the fragment for exactly this reason: changing it does not trigger a page load. Be aware that everything after the first # is the fragment, including any ?. For https://example.com/#/route?x=1, search is the empty string and hash is #/route?x=1, so searchParams will not find x.

Security: Reading the Host Correctly

Most URL-based attacks depend on someone misreading the authority component. Two cases are worth memorizing:

  • Userinfo tricks: in https://app.example.com@evil.com/ everything before the @ is a username, and the host is evil.com. Browsers and new URL() agree on this, but a human skimming the link may not. Never validate with startsWith("https://app.example.com") or a substring check.
  • Lookalike hosts: https://app.example.com.evil.com starts with your hostname but belongs to someone else. Compare the parsed hostname (or origin) for exact equality or against an allowlist.

Embedding credentials in URLs is also a bad idea: RFC 3986 deprecates the user:password format, and URLs get copied into logs, browser history, and shared links. Use headers or request bodies for secrets. For the redirect-specific version of this problem, see The Art of URL Building and Understanding URL Redirects.

Tools for the Job

These tools cover the same ground interactively:

  • URL Parser: Break a long link into scheme, host, path, query parameters, and fragment.
  • URL Builder: Assemble a link from its parts, with each query key and value percent-encoded for you.
  • URL Validator: A quick format and reachability check. It uses a regular expression, so see the limits discussed in URL Validation Best Practices.
  • URL Encoder: Percent-encode text for use in a URL component.
  • URL Decoder: Decode percent-encoded text, for example to spot double encoding.

Frequently Asked Questions

What are the parts of a URL?

A full URL can contain a scheme, userinfo, host, port, path, query, and fragment, in that order: scheme://userinfo@host:port/path?query#fragment. Only the scheme and (for most schemes) the host are required. Everything else is optional.

What is the difference between a URL and a URI?

A URI is the general term for an identifier that follows the generic syntax in RFC 3986. A URL is a URI that also tells you how to locate a resource. In everyday web development the two words are used interchangeably, and the WHATWG URL Standard that browsers implement simply calls everything a URL.

Is the part after the # sent to the server?

No. The fragment is handled entirely by the browser, which is why server code and server logs never see it. If the server needs that value, move it into the query string or a request body.

Do URLs have to be encoded?

Any character that is not allowed in a component, or that has a reserved meaning there, has to be percent-encoded before it is placed in that component. The URL class encodes spaces and non-ASCII characters automatically, but it will not encode a literal & inside a value you concatenate yourself. See URL Encoding & Decoding for the details.

Written by

Spotted a mistake? Let me know