# Let's Read the Turbo Source: What Happens When You Click a Link?

*Published on September 06, 2023*

---


> 💡If you are interested in learning more about Hotwire, check out my&nbsp;[crash-course on Hotwire's Turbo framework](/tag/hotwire). It's free, and only a preview of what's coming later this year. So stay tuned!

**If you haven't heard,**&nbsp;[**Turbo 8 is dropping TypeScript**](https://world.hey.com/dhh/turbo-8-is-dropping-typescript-70165c01)**.**

I used to love TypeScript, but now I prefer plain JavaScript, both for reading and writing. So personally, I am happy with this bold move, even though everyone on the Internet seems to be&nbsp;[pissed off](https://github.com/hotwired/turbo/pull/971).

Anyway, ever since switching to Hotwire two years ago, I've always wondered how Turbo really worked behind the scenes. For example, what really happens when you click the link, how frame-swapping works, etc.&nbsp;[Reading the source](https://blog.codinghorror.com/learn-to-read-the-source-luke/)&nbsp;is one of the best ways I've found to learn how a feature/framework/program works, so when I read David's&nbsp;[comment](https://github.com/hotwired/turbo/pull/971#issuecomment-1708430006)&nbsp;on the PR,

> The code not only reads much better, it's also freed of the type wrangling and gymnastics needed to please the TS compiler.

I decided to do a deep dive into the Turbo, and spent the last few hours reading the&nbsp;[source code](https://github.com/hotwired/turbo). It's been an absolute joy ride, full of mysteries, anticipations, and A-Ha moments, and I learned a ton of interesting things not only about Turbo, but also in JavaScript, and browser APIs, and took a ton of notes.

In this post, we'll learn exactly what happens when you click a link and the page updates without a full reload. We'll also see how to set up the sandbox repository for experimenting and debugging with breakpoints.

> **Update:**&nbsp;After I started writing, within an hour the post ballooned past 3000 words. So to keep it readable, I've decided to split it into two parts. In this first part, we'll explore (almost) everything that happens from the moment you click the link until Turbo fetches the response. In the next part, we'll see how it swaps the current body from the response and merges the head.

Sounds interesting? Let's get started. We've got a lot of ground to cover.

## Setup the Turbo Sandbox

This section explains how to download and set up the codebase so you can easily debug and step through it in the browser.

### Step 1: Get the Source Code

Before diving into the codebase, you first need to get the working source code on your development machine. For this, clone the Github repository and install dependencies as usual.

```bash
$ git clone https://github.com/hotwired/turbo.git

$ cd turbo

$ yarn install
```

### Step 2: Compile the Source

The source code is split across many JavaScript files. To compile them all into a single JavaScript file that we can include in our HTML, you have to build the source.

```bash
$ yarn build
```

After the build finishes, you'll have two files in the&nbsp;`dist`&nbsp;directory, named&nbsp;`turbo.es2017-esm.js`&nbsp;and&nbsp;`turbo.es2017-umd.js`.

> If you open the&nbsp;`package.json`&nbsp;file, you'll notice that the build script runs&nbsp;`rollup -c`&nbsp;behind the scenes. If you're curious, you can check out the rollup configuration in the&nbsp;`rollup.config.js`&nbsp;file.

### Step 3: Add HTML Pages

It's nice to step-through the code as you're reading it to inspect the variables and follow the execution. To allow debugging in Chrome Devtools, let's create a new&nbsp;`public`&nbsp;directory and add a couple of HTML pages in it.

```bash
$ mkdir public

$ touch public/index.html
$ touch public/pages.about.html
```

Here's the Home (index) page:

```html
<!-- public/index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Home</title>
    <script src="/dist/turbo.es2017-umd.js"></script>
  </head>
  <body>
    <h1>Hotwire + Stimulus</h1>

    <a href="pages/about.html">About</a>
  </body>
</html>
```

And here's the About page:

```html
<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />
    <title>About</title>
    <script src="/dist/turbo.es2017-umd.js"></script>
  </head>
  <body>
    <h1>About</h1>
  </body>
</html>
```

Note that I've used the&nbsp;`umd`&nbsp;version of the compiled JavaScript in the&nbsp;`script`&nbsp;tag.

### Step 4: Start the Server

Turbo provides a local web server to make debugging and testing easy. Start the server as follows:

```bash
$ yarn start

yarn run v1.22.17
$ node src/tests/server.mjs
Test server listening on port 9000
```

Visit the&nbsp;`localhost:9000`&nbsp;URL in the browser and open the devtools window. Under the&nbsp;`sources`&nbsp;tab, open the&nbsp;`turbo-es2017-umd.js`&nbsp;file.

![devtools.png](https://writesoftwarewell.com/media/lxjkzxsomy089m2qcunp0dnjgc0q.png "Developer Tools")

It's not a huge file, the entire source is less than 5000 lines.

Now we're all set up to explore the codebase. Let's dive in.

## What Happens When You Click a Link?

In this section, we'll try to understand the sequence of events that take place when you click a link on a Turbo-enabled web page.

If you haven't played with Hotwire, I suggest check out the following article that introduces it: [A Brief Introduction to Hotwire](/introduction-to-hotwire)

**Quick summary:**&nbsp;When you are using Hotwire, Turbo Drive intercepts all links and form submissions to the same domain. When you click a link or submit a form, Turbo Drive does the following:

1. Prevent the browser from following the link,
2. Change the browser URL using the History API,
3. Request the new page using a&nbsp;`fetch`&nbsp;request
4. Render the response HTML by replacing the current&nbsp;`<body>`&nbsp;element with the response and merging the&nbsp;`<head>`&nbsp;element’s content.

The JavaScript&nbsp;`window`&nbsp;and&nbsp;`document`&nbsp;objects as well as the&nbsp;`<html>`&nbsp;element persist from one rendering to the next.

The same goes for an HTML form. Turbo Drive converts Form submissions into fetch requests. Then it follows the redirect and renders the HTML response. As a result, your browser doesn’t have to reload, and the app feels much faster.

We will start our code exploration by following three distinct phases in the Turbo lifecycle.&nbsp;**Initialization process, intercepting the link click, and following the visit to the location.**

### Initialization Process

When your app loads in the browser, the control flow starts with the&nbsp;`src/index.js`&nbsp;file. You can verify this by putting the breakpoint on line where we set the&nbsp;`Turbo`&nbsp;object on the&nbsp;`window`.

![breakpoint-paused-devtools.png](https://writesoftwarewell.com/media/979x8cjmis5v18y2ikpowbfv7e69.png "Paused on a breakpoint in DevTools")

The control hits the above breakpoint as soon as you reload the page. We're ready to step into the initialization process.

> As you read the rest of the article, step through the code in the devtools window at the same time. This will allow you to inspect local variables and objects for a deeper understanding.

If you open&nbsp;`index.js`&nbsp;in the editor, you'll notice that it imports everything from the&nbsp;`./core`&nbsp;directory in the&nbsp;`Turbo`&nbsp;global variable and starts the main session by calling&nbsp;`Turbo.start()`&nbsp;method.

```javascript
// src/index.js

window.Turbo = Turbo
Turbo.start()
```

The&nbsp;`start`&nbsp;method in turn starts the session by calling&nbsp;`session.start()`&nbsp;method. This method starts all the relevant actors, including&nbsp;`LinkClickObserver`, and&nbsp;`FormSubmitObserver`&nbsp;which listen for link click and form submission events and act accordingly.

```javascript
// src/core/session.js

export class Session {
    
  linkClickObserver = new LinkClickObserver(this, window)
  formSubmitObserver = new FormSubmitObserver(this, document)

  start() {
    if (!this.started) {
      // ...
      this.linkClickObserver.start()
      this.formSubmitObserver.start()
      // ...
      this.history.start()
      this.started = true
      this.enabled = true
    }
  }
}
```

For this article, we're only interested in what happens when you click the link. So let's dive into the&nbsp;`LinkClickObserver`&nbsp;class.

```javascript
export class LinkClickObserver {
  started = false

  constructor(delegate, eventTarget) {
    this.delegate = delegate        // set to 'session'
    this.eventTarget = eventTarget  // set to 'window'
  }

  start() {
    if (!this.started) {
      this.eventTarget.addEventListener("click", this.clickCaptured, true)
      this.started = true
    }
  }
}
```

When&nbsp;`LinkClickObserver`&nbsp;starts, it adds an event listener for the&nbsp;`click`&nbsp;event on the&nbsp;`window`&nbsp;. However, instead of attaching a handler on event bubbling phase, it uses&nbsp;[event capturing](https://javascript.info/bubbling-and-capturing#capturing)&nbsp;by setting the third optional, boolean parameter&nbsp;`useCapture`&nbsp;to&nbsp;`true`.

**Aside: Why Capture?**  
  
Capturing phase is the inverse of the bubbling phase. Capturing happens before bubbling, and in reverse order. Instead of starting on the target element and propagating outwards (which is what bubbling does), the outermost element is notified of the event first. Then the event propagates down the hierarchy until reaching the target.  
  
The mechanics of the capturing phase make it ideal for preparing or preventing behavior that will later be applied by event delegation during the bubbling phase.  
  
Source:&nbsp;[Using event capturing to improve Basecamp page load times](https://signalvnoise.com/posts/3137-using-event-capturing-to-improve-basecamp-page-load-times)

The&nbsp;`clickBubbled`&nbsp;function ultimately handles the link clicks. To understand what's going on, I'll put a breakpoint on the first statement, and click the&nbsp;_**About**_&nbsp;link on the page.

![link_click.png](https://writesoftwarewell.com/media/kpx38o6uft33x93l8s0gl8zkvi43.png "Inspecting link click")

The&nbsp;`clickBubbled`&nbsp;handler first checks if the&nbsp;`click`&nbsp;event came from a mouse click and if&nbsp;**it's significant**, i.e. it was not triggered on an editable element, or performed by one of the special keys such as&nbsp;`Alt`,&nbsp;`Ctrl`&nbsp;or&nbsp;`Shift`&nbsp;etc.

**If it's not a significant event, it simply returns.**

If it's a significant mouse click event, it finds the link (the&nbsp;`<a>`&nbsp;element) and location (the URL) from the click target.

**Something I learned:**&nbsp;To get the target element, Turbo calls the&nbsp;`composedPath`&nbsp;method on the&nbsp;`event`. This method returns the event's path which is an array of the objects on which listeners will be invoked.

In our case, it returns the following array.

```javascript
> event.composedPath()
(5) [a, body, html, document, Window]
```

Then it delegates to the&nbsp;`Session`&nbsp;to check if the following conditions are satisfied:

1. Turbo Drive is enabled for the element
2. The location is visitable, i.e. it belongs to the same domain (location is prefixed by the root location) as your application and if it's an HTML request
3. The application allows following the link to the location by triggering the&nbsp;`turbo:click`&nbsp;event and checking if the application didn't stop the event propogation.

```javascript
/* session.ts */

willFollowLinkToLocation(link, location, event) {
  return (
    this.elementIsNavigatable(link) &&
    locationIsVisitable(location, this.snapshot.rootLocation) &&
    this.applicationAllowsFollowingLinkToLocation(link, location, event)
  )
}
```

💡 Turbo fires the&nbsp;[turbo:click](https://turbo.hotwired.dev/reference/events)&nbsp;event when you click a Turbo-enabled link. The clicked element is the event target. You can access the requested location with event.detail.url. Cancel this event to let the click fall through to the browser as normal navigation.

If your application didn't prevent the event by intercepting it, then Turbo prevents the regular browser link navigation, gets the&nbsp;[action](https://turbo.hotwired.dev/handbook/drive#page-navigation-basics)&nbsp;for the link (`advance`,&nbsp;`replace`, or&nbsp;`restore`) and delegates the task of proposing the location visit to the&nbsp;`Navigator`.

```javascript
/* session.ts */

// actually follow the link
followedLinkToLocation(link, location) {
  const action = this.getActionForLink(link)
  const acceptsStreamResponse = link.hasAttribute("data-turbo-stream")
  this.visit(location.href, { action, acceptsStreamResponse })
}

// propose visit to the location (simplified...)
visit(location, options) {
  this.navigator.proposeVisit(location, options)
} 
```

### Visiting the Location

The&nbsp;`Navigator.proposeVisit()`&nbsp;method first checks if the application allows visiting the location with given action (default:&nbsp;`advance`) by triggering the&nbsp;`turbo:before-visit`&nbsp;custom event and checking if it was prevented by the application.

💡The&nbsp;[turbo:before-visit](https://turbo.hotwired.dev/reference/events)&nbsp;event fires before visiting a location, except when navigating by history. Access the requested location with event.detail.url. Cancel this event to prevent navigation.

```javascript
export class Navigator {
  constructor(delegate) {
    this.delegate = delegate  // set to 'session'
  }

  proposeVisit(location, options = {}) {
    if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {
      if (locationIsVisitable(location, this.view.snapshot.rootLocation)) {
        this.delegate.visitProposedToLocation(location, options)
      } else {
        window.location.href = location.toString()
      }
    }
  }
}
```

If the location can be visited, then the&nbsp;`Navigator`&nbsp;checks if the location is visitable by verifying if it belongs to the same domain (location is prefixed by the root location) as your application and if it's an HTML request.

```javascript
// src/core/url.js

export function locationIsVisitable(location, rootLocation) {
  return isPrefixedBy(location, rootLocation) && isHTML(location)
}
```

**If the location is not visitable, i.e., it refers to the different origin or different content-type than HTML, Turbo simply redirects the browser to the requested location by setting the \`window.location.href\` property. This happens for non-origin or non-HTML URLs.**

If the location is visitable, Turbo uses the&nbsp;`BrowserAdapter`&nbsp;class to co-ordinate the action of visiting the location

```javascript
// src/core/session.js

export class Session {
  adapter = new BrowserAdapter(this)

  visitProposedToLocation(location, options) {
    this.adapter.visitProposedToLocation(location, options)
  }
}
```

### The BrowserAdapter Class

The&nbsp;`BrowserAdapter`&nbsp;class has two responsibilities:

1. show the progress bar
2. visit the location

It does the second by instructing the&nbsp;`Navigator`&nbsp;to start the visit, passing a&nbsp;`uuid`&nbsp;as an identifier for restoration. Lots of delegation happening, everywhere.

```javascript
export class BrowserAdapter {
  progressBar = new ProgressBar()

  constructor(session) {
    this.session = session
  }

  visitProposedToLocation(location, options) {
    this.navigator.startVisit(location, options?.restorationIdentifier || uuid(), options)
  }
}
```

The&nbsp;`startVisit`&nbsp;method instantiates the&nbsp;`Visit`&nbsp;class, which handles the actual visit by recording the timing metrics, updating the state, and delegating to&nbsp;`BrowserAdapter`&nbsp;and&nbsp;`Navigator`&nbsp;classes, passing itself to both.

```javascript
// src/core/drive/visit.js

export class Visit {
  start() {
    if (this.state == VisitState.initialized) {
      this.recordTimingMetric(TimingMetric.visitStart)
      this.state = VisitState.started
      this.adapter.visitStarted(this)
      this.delegate.visitStarted(this)
    }
  }
}
```

The&nbsp;`BrowserAdapter#visitStarted`&nbsp;method does the following:

1. Loads the cached snapshot if it exists. For the first click, there won't be any.
2. Issues the Fetch request after dispatching a&nbsp;`turbo:before-fetch-request`&nbsp;event so the application can intercept it.
3. Changes the browser history
4. Navigates to the anchor

Steps 2-4 are handled by the&nbsp;`Visit`&nbsp;class.

```javascript
// src/core/native/browser_adapter.js

export class BrowserAdapter {
  visitStarted(visit) {
    this.location = visit.location
    visit.loadCachedSnapshot()
    visit.issueRequest()
    visit.goToSamePageAnchor()
  }
}
```

The&nbsp;`Visit#issueRequest`&nbsp;method performs the actual visit by instantiating&nbsp;`FetchRequest`, which encapsulates the&nbsp;`fetch`&nbsp;call.

```javascript
// src/core/drive/visit.js

export class Visit {
  issueRequest() {
    this.request = new FetchRequest(this, FetchMethod.get, this.location)
    this.request.perform()
  }
}
```

Finally, here's the&nbsp;`perform`&nbsp;method that makes the actual&nbsp;`fetch`&nbsp;request.

```javascript
export class FetchRequest {
  async perform() {
    const response = await fetch(this.url.href, fetchOptions)
    return await this.receive(response)
  }
}
```

At this point, we've received the response from the server. However, we're not finished yet. If you remember the steps that take place when you click a link:

1. Prevent the browser from following the link -&nbsp;**Done**
2. Change the browser URL using the History API -&nbsp;**Done**
3. Request the new page using a&nbsp;`fetch`&nbsp;request -&nbsp;**Done**
4. Render the response HTML by replacing the current&nbsp;`<body>`&nbsp;element with the response and merging the&nbsp;`<head>`&nbsp;element’s content.

**We still need to complete the fourth step, i.e. update the body and merge the head,**&nbsp;which is a topic that deserves a blog post of its own.

If you're still here, I don't think both me and you have the energy or the patience to explore any further right away. So I'll stop here, and continue the exploration in the next post.

Stay tuned!

