Watch our biggest AI launch event

Announcing Visual Copilot - Figma to production in half the time

Builder.io logo
Contact Sales
Platform
Developers
Contact Sales

Blog

Home

Resources

Blog

Forum

Github

Login

Signup

×

Visual CMS

Drag-and-drop visual editor and headless CMS for any tech stack

Theme Studio for Shopify

Build and optimize your Shopify-hosted storefront, no coding required

Resources

Blog

Get StartedLogin

Popular Tutorials

>

Set Up Server-side Redirects with Next.js

Set Up Server-side Redirects with Next.js

This tutorial shows you how to create a Data model to configure server-side redirects in Builder. A server-side redirect is a technique for rerouting site traffic from one web address to another. For example, if you create a Page and later want to reroute visitors to another Page that has a different URL, you'd set up a URL redirect.

Use cases for server-side redirects include:

  • Reroute traffic to an updated Page from an outdated one.
  • Phase out an old URL without breaking links to the old URL.
  • Redirect traffic when you're updating URL naming conventions.

Skill set: Intermediate

Area: UI and code

Video Length: 2 minutes

  • Youʻll need a Builder account.
  • An evergreen browser; that is, a modern, up-to-date browser such as Google Chrome.
  1. Go to Models.
  2. Click the + Create New button.
  3. Name and describe your model. This example uses the Name URL Redirects and the Description Manage URL redirects for site content.
  4. Add a custom field by clicking on the + New Field button. Name the first new field sourceUrl with a Type of Url.
  5. Repeat the previous step for a field called destinationUrl of Type Url and a third field called redirectToPermanent of Type Boolean.
  6. Click Save.

The following video demonstrates the above process:

Tip: When you configure your codebase to use the redirect in Step 3, you'll need the name of the model you just created. The name, known as the Unique identifier in the Builder UI, in this example is url-redirects, which you can find by clicking the Show More button.

For a video pointing out the location of the name, refer to the Finding the model name section of Data Models.

The next step is to use the Data model you just made. Here you make a Data content entry to redirect a URL called /site/intro to /site/getting-started.

  1. Go to Content.
  2. Click the + New button.
  3. Select URL redirect.
  4. For the SourceUrl, enter /site/intro.
  5. For the DestinationUrl, enter /site/getting-started.
  6. Name the new content entry /site/intro -> /site/getting-started. This way, when the URL Redirects are listed in the content area of Builder, each redirect's purpose is in the name, so you don't have to open them to see the URLs that are being redirected.
  7. Click Save.

This video shows the process of making a server-side-redirect as outlined above:

The next step is to configure your codebase as in the next code snippet. Use builder.getAll() to get all the redirects from Builder. Then, create an object that Next.js can use and, optionally, add an error handler. The code snippet in this section covers each of these tasks in turn.

Tip: The next.config.js file has a 1024 entry count limit. For more context, refer to Vercel's guide, How can I increase the limit of redirects or use dynamic redirects on Vercel?.

In next.config.js, add the following code:

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

module.exports = {
  async redirects() {
    return builder
      .getAll(
        // This is the unique identifier in the model
        'url-redirects',
        {
          // Find your Public API Key in Account Settings
          apiKey: 'YOUR_API_KEY',
          // These two options make sure you get the latest, unfiltered data. 
          options: { noTargeting: true },
          cachebust: true,
        }
      )
      .then(
        (results) =>
          results
            // Filter out partially filled data to make sure
            // you have all the fields for redirects
            .filter((content) => {
              const data = (content || {}).data || {};
              return !!(data.sourceUrl && data.destinationUrl);
            })
            // Create the "redirect" object Next.js expects
            .map(({ data }) => ({
              source: data.sourceUrl,
              destination: data.destinationUrl,
              permanent: !!data.redirectToPermanent,
            })),
        (error) => {
          // Error handler to log issues looking up redirects, 
          // but the deploy itself doesn't fail.
          // To instead stop the deployment in case of issues with the
          // redirects, remove this function.
          console.error("Error setting up redirects", error);
          return [];
        },
      );
  },
}

To find your Public API Key, go to Account Settings. For more information on the Public API Key, see Using the Builder API Key.

For more information, refer to Vercel's Redirect documentation.

With Next.js sites, you need to trigger a rebuild for new redirects. Since Next.js evaluates the next.config.js only once when building an app, newly added redirects don’t take effect immediately. To cause this rebuild, use a webhook.

Tip: For this part of the tutorial, you need a webhook URL on the backend. If you're using Vercel, visit their Deploy hooks documentation.

To add a Webhook to the data model take the following steps:

  1. Go to Models.
  2. Open the URL Redirects model you made in Step 1: Create a Data model.
  3. Click the + Show More Options button.
  4. Click the Edit Webhooks button.
  5. Click + Webhook.
  6. Expand the new Webhook 1 and paste your webhook URL into the URL field.
  7. Click Done.

The following video demonstrates the above process:

To get even more out of Data models with Builder, check out Integrating CMS Data.

For more general information on Data models, refer to the Data Models documentation.

Was this article helpful?

Product

Visual CMS

Theme Studio for Shopify

Sign up

Login

Featured Integrations

React

Angular

Next.js

Gatsby

Get In Touch

Chat With Us

Twitter

Linkedin

Careers

© 2020 Builder.io, Inc.

Security

Privacy Policy

Terms of Service

Newsletter

Get the latest from Builder.io

By submitting, you agree to our Privacy Policy

Product

Platform Overview

Integrations

What's New

Open Source

Builder

Builder

Mitosis

Mitosis

Qwik

Qwik

Partytown

Partytown

Popular Guides

From Design to Code Guide

Composable Commerce Guide

Headless CMS Guide

Headless Commerce Guide

Composable DXP Guide

Design to Code

Resources

Blog

Knowledge Base

Community Forum

Partners

Templates

Success Stories

Showcase

Resource Center

Frameworks

React

React

Next

Next.js

Qwik

Qwik

Gatsby

Gatsby

Angular

Angular

Vue

Vue

Svelte

Svelte

Remix logo

Remix

Nuxt

Nuxt

Hydrogen

Hydrogen

See All

© 2024 Builder.io, Inc.

Security

Privacy Policy

SaaS Terms

Security & Compliance

Cookie Preferences