Create Simple URLs (Link Resolver)

Package versions

These docs use the following package versions:

  • prismic-reactjs: v1.3
  • @prismicio/client: v5

The docs will soon be updated to use the latest versions of these packages. If you wish to use the latest versions today, you can update your project by following the migration guides for each package.

By the end of this article you will learn how to create simple URLs for links to your Prismic documents using the Link Resolver.


Next.js 9.5.3

This document assumes you are using Next.js 9.5.3 which removes the need for the as optional decorator for dynamic routes, check the Next.js Links documentation for more info.

Your Link fields and Rich Text fields may contain a link that points to a Document in your Prismic repository. To make this link work properly within your website, you need to have a Link Resolver function that returns the appropriate path within your website. This Link Resolver function will take a Prismic Document object as an argument and return the corresponding route path of your website.


Route Resolver vs. Link Resolver?

The Link Resolver is the best option if you want to create simple links for your Prismic documents based on anything other than the document type. The Route Resolver is best for complex nested routes using Content Relationships.

If you have both the Route Resolver and the Link Resolver in your project then the link component will check if the link case exists in the Link Resolver before checking the Route Resolver if there is no matching case.


Defining a Link Resolver function

Since routing is specific to your website, you need to explicitly define your internal routing in the Link Resolver function. Below you will find all the accessible properties and an example.

Accessible properties

The Link Resolver function should pass a Prismic Document object as a parameter. Inside the function you will have access to the following properties:

doc.id

string

The document ID

doc.uid

string

The user-friendly unique identifier

doc.type

string

The Custom Type of the document

doc.tags

array

Array of the document tags

doc.lang

string

The language code of the document

doc.isBroken

boolean

Boolean that states if the link is broken or not

Example Link Resolver

The example below is what a Link Resolver might look like for a multi-page website.

  • The doc.isBroken route is set up for when a document doesn't exist.
  • The doc.uid route is set up for the home page using its unique ID.
  • The doc.type route uses the doc.uid property to create dynamic routes.
Copy
export const linkResolver = (doc) => {
  if (doc.isBroken) {
    return '/not-found'
  }
  if (doc.type === 'home') {
    return '/'
  }
  if (doc.type === 'page') {
    return `/page/${doc.uid}`
  }
  return '/'
}

Use the Link Resolver in your project

To make sure that your Link Resolver function can be used by the <Link> and Prismic <RichText/> components in your project there is some configuration to do.

1. Add the Link Resolver in the prismicConfiguration.js file

Define your Link Resolver in a global file like a prismicConfiguration.js file at the root of your project so it can be imported anywhere. Read our full documentation on how to set up a prismicConfiguration.js file.

Copy
// ~/utils/prismicConfiguration.js
// -- Prismic Repo Name
export const repoName = 'your-repo-name'

// -- Prismic API endpoint
// Determines which repository to query and fetch data from
// Configure your site's access point here
export const apiEndpoint = `https://${repoName}.prismic.io/api/v2`

// -- Link resolution rules
// Manages the url links to internal Prismic documents
export const linkResolver = (doc) => {
  if (doc.type === 'post') {
    return `/blog/${doc.uid}`
  }
  return '/'
}

2. Create a Custom Link component for Prismic Rich Text links

The Custom Link is a helper function to convert Prismic Rich Text links to Next/Link components. You define it somewhere global in your project like in a prismicHelpers.js file. Read our full documentation on how to set up a prismicHelpers.js file.

Copy
// Truncated version of ~/utils/prismicHelpers.js

import React from 'react'
import Link from 'next/link'
import { linkResolver } from "../prismicConfiguration" // or to the path where you defined this

export const CustomLink = (type, element, content, children, index) => (
  <Link key={index} href={linkResolver(element.data)}>
    <a>{content}</a>
  </Link>
)

3. Pass the Custom Link to the Rich Text field

Then wherever you use the Rich Text component, import the customLink function and pass it to the Rich Text field with the serializeHyperlink attribute. Now your Prismic Links in your Rich Text fields will resolve correctly.

The example below is how this would look in a Slice component, as we do in our blog example.

Copy
import React from 'react'
import { RichText } from 'prismic-reactjs'
import { CustomLink } from '../../.../utils/prismicHelpers' // or whatever the path to this file

/**
 * Text slice component
 */
const Text = ({ slice }) => (
  <RichText
    render={slice.primary.text}
    serializeHyperlink={CustomLink}
  />
)

export default Text

4. Create a DocLink component for the Prismic Link field

When you want to create links for the Prismic Link field then you will need to handle 3 cases:

  • Prismic document links
  • External URLs
  • Media item links

A best practice is to create a component that handles all 3 of these cases.

In the example below we import the Next/Link component as NextLink because we also import a link utility from the prismic-reactjs package as Link. This link utility will take the Link field JSON and return it as a URL.

The example works by taking the Link field as a prop and checking if it's an internal document, in this case, it passes the link through the Next Link component and the Link Resolver. If it's an external URL or media item then it returns a normal anchor element and passes the link through the prismic-reactjs Link utility.

This component also allows you to pass a linkClass and children as props.

Copy
import React from 'react'
import { default as NextLink } from 'next/link'
import { Link } from 'prismic-reactjs'
import { linkResolver } from '../prismicConfiguration'

// Main DocLink component function for generating links to other pages on this site
const DocLink = ({ children, link, linkClass }) => {
  if (link) {

    // If the link is an internal link, then return a NextLink
    if (link.link_type && link.link_type === 'Document') {
      return (
        <NextLink href={linkResolver(link)}>
          <a className={linkClass}>{children}</a>
        </NextLink>
      )
    }

    // Otherwise return a normal anchor element
    return (
      <a className={linkClass} href={Link.url(link)}>{children}</a>
    )
  }
  return null
}

export default DocLink

5. Use the Doc Link component

To use the component import it in a page or component, then you can pass it the props link, linkClass and in this case a label using the Prismic Rich Text field which will be passed as the children prop.

Below is a truncated example based on the Banner component of our website sample project.

Copy
// Trucated ~/components/HomeBanner.js example

import React from 'react'
import { RichText } from 'prismic-reactjs'
import { DocLink } from 'components'

const HomeBanner = ({ banner }) => (
  <section>
    <DocLink link={banner.button_link} > // you can also pass the linkClass prop e.g. linkClass="banner-button"
      {RichText.asText(banner.button_label)}
    </DocLink>
  </section>
)

export default HomeBanner

Related articles


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.