Home App Docs Blog Github

How to manage content URL redirects (Or how to update content URLs without having broken links)

You have published content already, with other content and other websites already pointing to your Builder content by the URL. But, what if your content’s URL needs to be updated? Or this content is no longer relevant, and you want your visitors to see a different page?

One should try having working links at all costs; 404s / Broken links confuses users and makes them have a bad experience with your site. So if you need to redirect from old content/links to new ones, there are a couple of ways to accomplish this.

A simple way could be adding a bit of JS to the old content to trigger a navigation to the new content. For example, you have a page with the URL /site/questions/ and now you want this content to have the URL /faqs. We add a second page with the new URL, and in the first one, we add this bit of code:

window.location = '/faqs';

And that’s it. However there are a couple of problems with this approach:

  • It forces you to keep the old page around, because it has to be loaded for the JS code to run
  • Because the redirection happens using JS in the user’s browser, everything in the page has to be loaded and run, so the user might still see a flash of old content (or a blank page, if we clear the old page).
  • While it’s usually true, this will only work for users with Javascript enabled.

A better approach would be to use server side redirects. This prevents flashes of old contents, there’s no need for JS code to load and run and will work in any browser regardless of user configuration. The downside is that this approach is a bit more involved and requires server/backend side integration, and how to do this differs depending on your site’s tech stack. Here we are going to show how to do this for Next.js sites with Builder content.

First we need to define a new Data model where we are going to store all the redirection “rules”; we go to “Models” in the Builder App sidebar, click “+ Create Model” and select “Data”:

Next the app will ask for a name, lets use “URL Redirects”, accept and then we get this view:

It’s recommended to add a description, something like “URL redirections from old content/URLs to new content”.

Now we use the “New field” button a few times to add some fields to this model. First, urlFrom:

Then urlTo:

And finally, while not strictly necessary, the permanentRedirect field is recommended:

Now we go back up and click the “Show More Options” button right below the model description, and we get this view. We don’t need to change anything here, except just take not of the text under “Unique identifier” we will need this value later. In this example, it’s url-redirects, but if you chose a different model name, here you’ll get something different. It doesn’t matter if it’s the same, as long as you make a note of it.

Click the blue “Save” button in the top right corner and now we can start defining some redirects. In the Builder App sidebar, go to “Content” and you should now see our new model on the left, we click on it to get an empty content list.
image

We click “New” in the top right corner and then “Url redirects”:
image

Next we give this entry a name (top left corner), and fill out the fields in the form at the center of the page. These are the same fields we defined when creating the model earlier. Let’s go ahead and use the same values as the example at the beginning of this post, and finally we hit “Publish Draft”.

Now, while we can define as many redirects as we want, they still won’t take effect, as your site backend is not aware of them. This is the complex part: Server/Backend integration. In this post, we are going to show here how to with Next.js.

Luckly, Next.js does provide useful configuration options for redirecting, all we need to do is collect the data from Builder’s API, and transform it to the way the Next.js config needs it.

This is done in the file next.config.js (at the root of your Next.js site code); if it doesn’t exist, go ahead and create it, then paste this code:

module.exports = {
  async redirects() {
    return [
      {
        source: '/site/questions',
        destination: '/faqs',
      },
    ]
  },
}

If you save this file and rebuild/deploy your Next.js site, any visits to the /site/questions URL will get redirected to /faqs. However, these values are hardcoded (not very useful!) so what we need to do inside this redirects function is to pull the redirections data from Builder’s API, and build a list of redirects for Next.js to understand.

First you need to import the Builder SDK at the top of this file (most likely is already installed) and add code the query Builder data inside the redirects function:

const { builder } = require('@builder.io/sdk');

module.exports = {
  async redirects() {
    return builder
      .getAll(
        // This is the value we took note of earlier!
        'url-redirects',
        {
          // You can find this key under Organization in the Builder App.
          apiKey: '<YOUR-BUILDER-API-KEY>',
          // These two options make sure you get the latest, unfiltered data. 
          options: { noTargeting: true },
          cachebust: true,
        }
      )
      .then(
        (results) =>
          results
            // Here we filter out partially filled data; i.e. we make sure
            // we have all the fields needed for setting up redirections
            .filter((content) => {
              const data = (content || {}).data || {};
              return !!(data.urlFrom && data.urlTo);
            })
            // Here create the "redirect" object Next.js wants
            .map(({ data }) => ({
              source: data.urlFrom,
              destination: data.urlTo,
              permanent: !!data.permanentRedirect,
            })),
        (error) => {
          // We add this error handler at the end, so if there's a problem earlier
          // when looking up redirects, they are logged, but the deploy itself
          // doesn't fail.
          // If you do want to stop the deployment if there's a problem with the
          // redirects, just remove this function entirely.
          console.error("Error setting up redirects", error);
          return [];
        },
      );
  },
}

There’s one more thing to do that is specific to Next.js sites, and it is to trigger a rebuild/deploy when new redirects are created. Thing is, the next.config.js file is only evaluated once when the site is built, so any redirects added won’t take effect immediately. For example, if the site is hosted on Vercel, we can just obtain a webhook URL to trigger deploys remotely. Then, we go back to edit our “URL Redirects” model, click “Show more options”, then click “Edit Webhooks” to add a new one and paste in it the Vercel deployment URL.

Now every time a new redirect is made, a new deployment will be triggered, which will make Next.js read your redirects again.

1 Like