Search

How to determine if a link is internal or external in Contentful

By the end of this article, you'll have a simple solution to find out if links in Contentful entries are internal or external.


Knowing if a link is internal or external can be really useful for a couple of reasons:

  1. A developer needs internal URLs to point to a particular QA environment.

  2. Content authors and web marketers want to ensure external links open in a new tab so they don't lose site visitors.

  3. Advanced SEO treatments for links.


Setting this up in Contentful isn't so obvious, however. The linking options Contentful provides in Rich Text fields don't include marking them as internal or external.



One option is to use entry links rather than hyperlinks for internal linking. But, if you have site pages under your domain that don't exist in Contentful, creating internal links to these won't be possible.


Another option that I've implemented involves some front end code to determine if a link is external or not. The logic for that looks something like:



const baseURLS = [
  'https://www.yoursitedomain.com',
  'https://yoursitedomain.com'
];

const linkIsExternal = (link) => {
  // If you want all of your PDFs to open in a new tab
  if (link && link.includes('.pdf')) {
    return true
  }
    
  // Wrap in a try/catch in case the URL is invalid.
  try {
    const formattedURL = new URL(link);
    if (formattedURL.origin) { 
      if (baseURLS.includes(formattedURL.origin)){
        // If the base of the URL matches one of your site's base URLs, it is an external link.
        return false
      } else {
        return true
      }
    }
  } catch (e) {
    // If URL is just a relative link to the root page, it isn't external.
    if (link && link.charAt(0) === '/') {
      return false
    } else {
      return true
    }
  }
}
  

Circling back to the use cases mentioned, you can use this function to:

  1. Conditionally apply the relative environment URLs upon rendering HTML from a Contentful response.

  2. Automatically apply a target="_blank" to your <a> tags when links are external.

  3. Add a rel=”nofollow” tag to <a> tags with external URLs.


What if there was a process you could follow to make Contentful successful for your team specifically?


It's called the Waterfall method.


Teams I've worked with that follow this process were far more likely to set up a successful Contentful project than those who didn't.


Why? Because the process uses your current challenges to inform a vision their entire team can work towards, and make Contentful the tool to pull it all together.