Link Resolver

The Link Resolver will help you build your project URL routes and manage links in field types such as a Link or a Rich Text in a Gatsby project.


The Link Resolver helps you build the URLs for your site. Now let's take a look at how to create one and use it in your project.

1. Create a Link Resolver

Start by creating a linkResolver.js file. Our example resolves page routes for three documents Custom Types (category, product, and page). Adapt it or write your own depending on the routes on your website.

Copy
exports.linkResolver = (doc) => {
  // URL for a category type
  if (doc.type === 'category') {
    return `/category/${doc.uid}`
  }

  // URL for a product type
  if (doc.type === 'product') {
    return `/product/${doc.uid}`
  }

  // URL for a page type
  if (doc.type === 'page') {
    return `/${doc.uid}`
  }

  // Backup for all other types
  return '/'
}

2. Add it to the plugin

After you've created the Link Resolver file, add it to the plugin configuration in the gatsby-config.js file. See how we do it in the following example. Remember to update the path to your Link Resolver:

Copy
// Truncated example gatsby-config.js file

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  // ... 
  plugins: [
    {
      resolve: 'gatsby-source-prismic',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
        linkResolver: require('./path-to-your-linkResolver').linkResolver,
        // ...
      },
    },
  ],
}

3. Usage

Now that the Link Resolver is created and registered in the plugin, the routes become available in the queries with the url field of the document's metadata to create internal links and URLs.

URLs

Use the URLs to create dynamic pages. You can use Gatsby Node APIs or the File System Route API.

For instance, say we have documents of the type Blog. With the File System Route API, we create a file such as 〜/src/pages/{PrismicBlog.url}.js. The Link Resolver will create a unique URL path using each document's UID, like so: /blog/${doc.uid}.

Links

To resolve internal links add the <PrismicProvider> with an internalLinkComponent prop to the gatsby-browser.js and gatsby-ssr.js. Learn more in the Template Links and Content Relationships section


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.