Search code examples
javascriptdjangohttphttp-referer

Make browser submit additional HTTP-Header if click on hyperlink


Is there a way to make the webbrowser submit additional HTTP header if the user clicks on a link?

Background: In our environment every http-request has a unique ID on the server side. See https://serverfault.com/questions/797609/apache-x-request-id-like-in-heroku

If your web application receives a http-request, I would like to know which page was the page before. The http referrer is not enough, since the user could use several tabs in his browser.

I would like to avoid to put the ugly request-id into every GET request which gets send from the browser to the server. Up to now our URLs are nice.

My prefered solution would be some JavaScript magic which adds the request-id of the current page into the next http request.

Steps in detail:

  1. browser access URL http://example.com/search
  2. web server receives http request with request ID 123
  3. web server sends content of the URL to the browser (a search page). The page includes the request ID 123 somewhere
  4. the user searches for "foobar".
  5. the web browser submits a http request to the server and includes the previous request id somehow.
  6. web server receives second http request (ID 456) and can access the value of the first request (ID 123) somehow.
  7. Web server can store the relation "123 --> 456" in a database for later analysis.

My goal is to track the relations "123 --> 456". Above solution is just a strategy to get to the goal. Other strategies are welcome.

We use the web framework django. But AFAIK this does matter in this context.

the user could use several tabs in his browser

I elaborate what that means for a matching solution. The sequence of requests which come from one user does not solve the issue.

One use with several tabs:

  1. user looks at page A in tab1
  2. user looks at page B in tab2
  3. user follows a link on page A to page C
  4. user follows a link on page C to page D
  5. user follows a link on page B (tab2) to page E.

I want to know see two sequences:

A -> C -> D

And

B -> E

Solution

  • The only modern 'sane' option here is to use a ServiceWorker.

    A ServiceWorker can intercept HTTP requests for a domain you control and decorate it with more headers.

    A ServiceWorker works 'outside' of a browser tab, and if multiple tabs are open with the same website, the same serviceworker will be used for all of them.

    A full tutorial on how to accomplish that is definitely too much for this answer box, but intercepting and doing stuff with HTTP requests is a big use-case, so off-site sources will usually have this as an example.

    I would say that this is kind of a bad idea. If you think you need this, maybe you can handle this in a different way. A common way to do this might be using cookies instead.