links

The links function defines which <link> elements to add to the page when the user visits a route.

  1. import type { LinksFunction } from "@remix-run/node"; // or cloudflare/deno
  2. export const links: LinksFunction = () => {
  3. return [
  4. {
  5. rel: "icon",
  6. href: "/favicon.png",
  7. type: "image/png",
  8. },
  9. {
  10. rel: "stylesheet",
  11. href: "https://example.com/some/styles.css",
  12. },
  13. { page: "/users/123" },
  14. {
  15. rel: "preload",
  16. href: "/images/banner.jpg",
  17. as: "image",
  18. },
  19. ];
  20. };

There are two types of link descriptors you can return:

HtmlLinkDescriptor

This is an object representation of a normal <link {...props} /> element. View the MDN docs for the link API.

The links export from a route should return an array of HtmlLinkDescriptor objects.

Examples:

  1. import type { LinksFunction } from "@remix-run/node"; // or cloudflare/deno
  2. import stylesHref from "../styles/something.css";
  3. export const links: LinksFunction = () => {
  4. return [
  5. // add a favicon
  6. {
  7. rel: "icon",
  8. href: "/favicon.png",
  9. type: "image/png",
  10. },
  11. // add an external stylesheet
  12. {
  13. rel: "stylesheet",
  14. href: "https://example.com/some/styles.css",
  15. crossOrigin: "true",
  16. },
  17. // add a local stylesheet, remix will fingerprint the file name for
  18. // production caching
  19. { rel: "stylesheet", href: stylesHref },
  20. // prefetch an image into the browser cache that the user is likely to see
  21. // as they interact with this page, perhaps they click a button to reveal in
  22. // a summary/details element
  23. {
  24. rel: "prefetch",
  25. as: "image",
  26. href: "/img/bunny.jpg",
  27. },
  28. // only prefetch it if they're on a bigger screen
  29. {
  30. rel: "prefetch",
  31. as: "image",
  32. href: "/img/bunny.jpg",
  33. media: "(min-width: 1000px)",
  34. },
  35. ];
  36. };

PageLinkDescriptor

These descriptors allow you to prefetch the resources for a page the user is likely to navigate to. While this API is useful, you might get more mileage out of <Link prefetch="render"> instead. But if you’d like, you can get the same behavior with this API.

  1. export const links: LinksFunction = () => {
  2. return [{ page: "/posts/public" }];
  3. };

This loads up the JavaScript modules, loader data, and the stylesheets (defined in the links exports of the next routes) into the browser cache before the user even navigates there.

Be careful with this feature. You don’t want to download 10MB of JavaScript and data for pages the user probably won’t ever visit.