Webinar

“Digging into Gatsby 5’s Slice API” Register now

Gatsby Link API

For internal navigation, Gatsby includes a built-in <Link> component for creating links between internal pages and a navigate function for programmatic navigation.

The <Link> component drives a powerful performance feature called preloading. Preloading is used to prefetch page resources so that the resources are available by the time the user navigates to the page. We use the browser’s Intersection Observer API to observe when a <Link> component enters the user viewport and then start a low-priority request for the linked page’s resources. Then when a user moves their mouse over a link and the onMouseOver event is triggered, we upgrade the fetches to high-priority.

This two stage preloading helps ensure the page is ready to be rendered as soon as the user clicks to navigate.

Intelligent preloading like this eliminates the latency users experience when clicking on links in sites built in most other frameworks.

In any situation where you want to link between pages on the same site, use the Link component instead of an a tag. The two elements work much the same except href is now to.

A full example:

Gatsby’s Link component extends the Link component from Reach Router to add useful enhancements specific to Gatsby.

The to, replace, ref, innerRef, getProps and state properties originate from Reach Router’s Link component, so you should refer to the Reach Router Link API reference documentation as the source of truth for those properties.

In addition, Gatsby adds the following properties:

ArgumentTypeRequiredDescription
activeStyleObjectNoA style object that will be applied when the current item is active.
activeClassNameStringNoA class name that will be applied the current item is active.
partiallyActiveBooleanNoWhether partial URLs are considered active (e.g. /blog#hello-world matches <Link to="/blog"> if partiallyActive is true).

Here’s an example of how to use these additional properties:

How to use the navigate helper function

Sometimes you need to navigate to pages programmatically, such as during form submissions. In these cases, Link won’t work. By default, navigate operates the same way as a clicked Link component.

Gatsby re-exports the navigate helper function from Reach Router for convenience.

Gatsby does not add extra surface area to this API, so you should refer to Reach Router’s navigate API reference documentation as the source of truth.

You can use navigate(-1) to go to a previously visited route. This is Reach Router’s way of using history.back(). You can use any number as it uses history.go() under the hood. The delta parameter will be the number you pass in to navigate().

Add the path prefix to paths using withPrefix

It is common to host sites in a sub-directory of a site. Gatsby lets you set the path prefix for your site. After doing so, Gatsby’s <Link> component will automatically handle constructing the correct URL in development and production.

For pathnames you construct manually, there’s a helper function, withPrefix that prepends your path prefix in production (but doesn’t during development where paths don’t need to be prefixed).

This component is intended only for links to pages handled by Gatsby. For links to pages on other domains or pages on the same domain not handled by the current Gatsby site, use the normal <a> element.

Sometimes you won’t know ahead of time whether a link will be internal or not, such as when the data is coming from a CMS. In these cases you may find it useful to make a component which inspects the link and renders either with Gatsby’s <Link> or with a regular <a> tag accordingly.

Since deciding whether a link is internal or not depends on the site in question, you may need to customize the heuristic to your environment, but the following may be a good starting point:

The <Link /> component follows the behavior of Reach Router by ignoring trailing slashes and treating each page as if it were a directory when resolving relative links. For example if you are on either /blog/my-great-page or /blog/my-great-page/ (note the trailing slash), a link to ../second-page will take you to /blog/second-page.

File Downloads

You can similarly check for file downloads:

Recommendations for programmatic, in-app navigation

If you need this behavior, you should either use an anchor tag or import the navigate helper from gatsby, like so:

Handling stale client-side pages

Gatsby’s <Link> component will only fetch each page’s resources once. Updates to pages on the site are not reflected in the browser as they are effectively “locked in time”. This can have the undesirable impact of different users having different views of the content.

In order to prevent this staleness, Gatsby requests an additional resource on each new page load: app-data.json. This contains a hash generated when the site is built; if anything in the src directory changes, the hash will change. During page loads, if Gatsby sees a different hash in the app-data.json than the hash it initially retrieved when the site first loaded, the browser will navigate using window.location. The browser fetches the new page and starts over again, so any cached resources are lost.

However, if the page has previously loaded, it will not re-request app-data.json. In that case, the hash comparison will not occur and the previously loaded content will be used.

Note: Any state will be lost during the window.location transition. This can have an impact if there is a reliance on state management, e.g. tracking state in wrapPageElement or via a library like Redux.

Additional resources

Edit this page on GitHub
© 2022 Gatsby, Inc.