On this page
URL fragments in analytics can be surprising: the part of a URL after # is not sent as part of the browser’s HTTP request for a page, but JavaScript running on that page can read it and send it in a separate analytics event. This distinction matters for client-side routers and for sites that put search terms or identifiers in fragments.
Key Takeaways
- A browser does not include the fragment in the HTTP request target when it requests a page.
- Client-side code can read the fragment through
window.location.hashand transmit it in an event payload. - Analytics implementations differ: a page URL, route event, custom property, or session recording may expose fragment data depending on the configuration.
- Avoid putting sensitive values in fragments. If you use hash-based routing, send approved route labels rather than raw fragments.
What the server receives versus what JavaScript can read
Consider a visitor opening http://127.0.0.1:8765/#/search?term=example. The fragment begins at #; the ?term=example text is part of the fragment, not the request’s query string. The page request is for /, while JavaScript in the loaded page can read #/search?term=example from location.hash.
A script can then put that value into a JSON body and send it to a collector. The collector receives the value because the script explicitly transmitted it—not because the browser included the original fragment in the page request.
This article uses a simulated collector rather than a named analytics platform. The WHATWG URL Standard and platform documentation were not available for consultation here, so check the applicable documentation before relying on vendor-specific behavior.
Advertisement
Try a local comparison
This example uses Python’s standard library and fictional data. It starts a server on the local loopback interface, serves a page, and has that page send its fragment to a simulated analytics endpoint. The code has not been executed for this article.
Save the following as fragment_demo.py:
from http.server import BaseHTTPRequestHandler, HTTPServer
PAGE = b"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Fragment demo</title></head>
<body>
<p>Sending a simulated page-view event to the local server.</p>
<script>
fetch('/collect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
event: 'page_view',
fragment: window.location.hash
})
}).catch(error => console.error('Event failed:', error));
</script>
</body>
</html>
"""
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
print('GET request target:', repr(self.path), flush=True)
if self.path != '/':
self.send_error(404)
return
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
def do_POST(self):
print('POST request target:', repr(self.path), flush=True)
if self.path != '/collect':
self.send_error(404)
return
try:
length = int(self.headers.get('Content-Length', '0'))
except ValueError:
self.send_error(400)
return
if length < 0 or length > 8192:
self.send_error(413)
return
body = self.rfile.read(length)
print('Event body:', body.decode('utf-8', errors='replace'), flush=True)
self.send_response(204)
self.end_headers()
if __name__ == '__main__':
server = HTTPServer(('127.0.0.1', 8765), Handler)
print('Open http://127.0.0.1:8765/#/search?term=example', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
Run python3 fragment_demo.py, then open http://127.0.0.1:8765/#/search?term=example in a browser. Use only fictional values. If the port is already in use, stop the conflicting local process or change the port in both the code and the URL.
Compare the terminal entries: the page’s GET request target should be /, without the fragment. The separate POST targets /collect; its JSON body should contain the fragment. A browser may also request a favicon, producing an additional GET. In developer tools, inspect the document request and the /collect request payload to see the same distinction. Stop the server with Ctrl+C.
This is a demonstration, not a production collector: it prints event bodies and has no authentication or production logging safeguards. Keep it local and do not use visitor data.
How fragments reach analytics
A hash-based router might represent pages as #/pricing or #/search?term=example. Changing the hash can update the displayed view without a new document request. An analytics integration might send a page-view event on that change, attach the full browser URL, or include a custom route property. Other integrations may omit or sanitize the fragment, and automatic tracking may not detect every hash change.
Inspect your own implementation rather than assuming a platform default:
- In a test environment, open developer tools and enable the network request view.
- Load a page with a fictional fragment, then navigate between hash-based routes.
- Inspect analytics requests and their payloads for the fragment, full URL, page title, and custom properties. Check whether route changes produce events or duplicates.
- Compare what arrives in your analytics interface or debug view with the request payload. Vendor processing and display may differ from what the browser sent.
- Review the documentation for your actual analytics library, version, and configuration, including any automatic page-view and session-recording features.
A clean server access log does not prove the data was never transmitted: it may have traveled in a request body or another event field instead.
Advertisement
Reduce fragment exposure
Fragments may contain search terms, account identifiers, tokens, or other sensitive values. Treat percent-encoding or hashing a route into a URL as a representation choice, not a privacy control. Even if analytics excludes a fragment, browser history, copied links, page scripts, or extensions may still expose it.
For hash-based routing, prefer a small allowlist of analytics labels. For example, this function produces a limited event object rather than sending the full URL or hash:
function makePageView() {
const labels = {
'#/pricing': 'pricing',
'#/help': 'help'
};
const hash = window.location.hash;
const route = Object.prototype.hasOwnProperty.call(labels, hash)
? labels[hash]
: 'other';
return { event: 'page_view', route };
}
Integrate the returned object with your analytics library’s documented event API; the example does not send an event by itself. Call it for the initial view and, if appropriate, on hashchange. Coordinate this with automatic tracking to avoid duplicate page views. Exact matches deliberately map routes with extra parameters to other.
Also inspect page titles, query strings, custom event properties, error reports, and session recordings: sanitizing one field does not sanitize the others. Apply your organization’s consent, retention, access-control, and deletion policies to collected data. If sensitive values have already been collected, follow your incident and deletion procedures; changing future instrumentation does not remove existing records.
Common Mistakes
- Equating “not in the page request” with “never transmitted.” A later script can send the fragment separately.
- Assuming every analytics product handles hashes the same way. Check the actual requests and vendor configuration.
- Sending the full URL as a convenient page identifier. It can include both a query string and a fragment with sensitive data.
- Tracking only the initial load in a single-page application. Route changes may need explicit tracking, but adding it without checking automatic tracking can create duplicates.
- Testing with real search terms or credentials. Use fictional values, including in local logs and screenshots.
Best Practices
Keep sensitive values out of URLs where possible. Define approved route labels, minimize event fields, and test the actual network payload after analytics or router changes. Review third-party scripts and recording tools as well as your own page-view code; each can have a different collection path.
Conclusion
A fragment is omitted from the page’s HTTP request, but it remains available to client-side code. Test what your implementation sends, and use sanitized route labels when analytics needs to distinguish client-side views.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.