How to properly handle URL slug changes in Next.js

If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.

Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

Rate this content
Bookmark
Video Summary and Transcription
Handling URL slug changes in Next.js is essential to avoid 404 errors and maintain SEO rankings. In the video, the process of managing URL slugs, including both current and historical ones, is explained using Next.js methods like getStaticPaths and getStaticProps. These methods help in redirecting old slugs to the current ones, preventing broken links. The video emphasizes the importance of tracking URL slug history in a headless CMS like Content by Kentico using the urlslug-history custom element. This allows developers to manage slugs effectively, ensuring that when a URL slug is altered, the old URL is redirected to the new one without user intervention. The talk also covers how to get slug from URL in Next.js, a crucial step for implementing redirects and maintaining seamless user navigation. Understanding what is slug in Next.js and how to handle it can significantly improve user experience and SEO performance. The video provides practical steps to implement these changes, making it easier for developers to manage URL slugs in their Next.js projects.

This talk has been presented at TypeScript Congress 2022, check out the latest edition of this JavaScript Conference.

FAQ

Not handling URL slug changes properly can lead to 404 errors, loss of SEO ranking, and a poor user experience as visitors may encounter broken links, especially if they follow links from external sources or outdated marketing materials.

In a headless CMS like Content by Kentico, you can track URL slug history using a custom element such as 'urlslug-history'. This element records every change made to a URL slug and stores these changes within the content item, allowing for an accessible history of slugs.

To manage URL slug changes in Next.js, first track the history of URL slugs for each content item. Then, use the Next.js functions 'getStaticPaths' to generate pages for all historical and current slugs, and 'getStaticProps' to implement redirects from old slugs to the current slug.

In Next.js, redirects for historical URL slugs are implemented in 'getStaticProps'. By checking if a requested slug is historical, the function can return a redirect object pointing to the current slug, ensuring users are directed to the correct page.

The 'getStaticPaths' function in Next.js is used to define which paths should be pre-rendered based on URL slugs. It should include all historic and current slugs to ensure that each one corresponds to a valid page, preventing 404 errors for outdated URLs.

Handling URL slug changes is crucial because when a URL slug is altered, the old URL ceases to exist, potentially causing 404 errors. This can negatively affect SEO and disrupt visitors who use the old URL, especially if it was used in marketing campaigns or had a good search engine rank.

1. Handling URL Slack Changes in Next.js#

Short description:

Hello, everyone. I'm Andrey, developer evangelist at Content by Kentico. Today, I'll explain how to handle URL Slack changes in Next.js. Every content item in the headless CMS contains a URL slag, and when the editor changes it, the old URL slag ceases to exist, resulting in 404 errors for visitors. To properly handle this, we need to know the URL slag history and use the getstaticpaths and getstaticprops methods in Next.js to issue redirects. Let's start with the content side, where we can use the urlslug-history custom element to track URL slag changes.

Hello, everyone. I'm Andrey, developer evangelist at Content by Kentico. And today, I want to tell you how to properly handle URL Slack changes in Next.js.

Now, first of all, why should we care about the URL slags? Every content item that is stored in the headless CMS and you are actually storing it or displaying it as a page in your site implementation contains a URL slag. Now, the problem is when editor comes into that content item, changes the URL slag, and your site implementation just takes the change, rebuilds the page, and the old page, the old URL slag just ceases to exist. The problem is if that page used to have a good page rank on search engines, or you used that page in your marketing campaigns, all those visitors that are using that URL will now get 404 errors. And these days we cannot really afford confused visitors, right?

So, what we need to do is, first, we need to know for every page, every content item, we need to know the URL slag history. You see here, the example is that the current page has a URL slug, hello-typescript-congress, but in the past it used to have a URL slug, typescript-congress and hello-conference, we need to know the history in order to be able to issue the redirects properly. Next thing is for the Next.js, now we're going to be using Next.js and content in this example, but if you're using a different framework, you can apply the same principles there. Here we're just talking about Next.js, so we have two methods. We have getstaticpaths and getstaticprops. In getstaticpaths, we need to provide all the URL slugs where there is a page for us to generate. In that case, we need to provide all the three URL slugs. So, that's the history ones and the current ones as well. And the last step, the third step is to add a proper redirect in getstaticprops. There we need to find out based on the slug, whether this is a current slug, like the hello-typescript-congress, which is the target page, or whether the slug that we're using is a historic one, and we should redirect the visitor to a current page. In this case, that would be the typescript-congress, hello-conferences, which will issue redirects. So how can we do this in Next.js? Let's take a look. Let's start in content first. On the content side of things, I prepared one content type called conference. And when you look at the content item, that's already using that content type. You see in content we have a special urlslug-history custom element that you can use on your project. It's available open source, so we can just deploy it to Netlify or Vercel and use it just like I'm using it here. It actually tracks all the changes you do to a urlslug. So you see here, now the urlslug is typescript-congress-2022. If I change it to typescript-congress, it automatically registers the change. And when I publish the page, it's going to store the change within the content item. So you see this is in the history. Now, we can do this as many times as we want. We're just going to get a list of strings out of the API, but this is the first step.

2. Implementation of URL Slug Changes in Next.js#

Short description:

In Next.js, you need to provide all the paths to getStaticPaths or as a result to Next.js. In getStaticProps, you need to issue the redirect if it's a page that should be redirected. We create a list of all the slugs and all the current slugs that they should redirect to. We store all the paths in the cache and provide all the slugs, historic ones and current ones, back to Next.js. We issue a proper redirect if we find out we should.

You need to know all the urlslugs, the historic ones and the current ones. Now let's take a look at the implementation. In Next.js, I have a simple page, slug-tsx. Now this whole thing is based on a Next.js content boilerplate, so there is not a ton of functionality. But here you see there are two methods, getStaticPaths, getStaticProps. And as I mentioned in the presentation at the start, you need to provide all the paths to getStaticPaths or as a result, to Next.js.

In getStaticProps, you need to issue the redirect if it's a page that should be redirected. So here we just need to do one simple change and add to the elements parameter the history as well. So before, we were only using the URL slug, but now we want to use the URL slug history as well to get really all the paths. And now we need to get all the paths in a simple list.

Now the thing is, if we only get the paths in getStaticProps, we would have to do one additional API check with the content API to see if the slug is a historic one or a current one. So what I'm going to do is I'm going to create a list of all the slugs and all the current slugs that they should redirect to. Now, I'm going to do the implementation here, I'm going to fast forward and then I'm going to explain the code in a second.

Right, so what I implemented here is we're getting all paths from the content CMS, and we're actually providing all those paths back as an IPagePath structure, which you can see contains just two properties path and redirectsTo. Path is the URL slug, the current one, and redirectsTo is, in case we're working with the historic path, here we're going to hold the current path of any page. So you see that for the actual item coming from content, we're providing a path that is the current path of the item, the one of the published version of the page. And then we're creating a structure of the historic paths, historic slugs, and they redirect all to the current page path.

Now the problem is, we cannot really take the whole structure and provide it to Next.js so that we get it in getStaticProps. The reason is, Next.js will only allow us to transfer the slug, because it's in the filename, it's the variable on the way to the page. So we're not going to be able to transfer this to getStaticProps and avoid the performance problems. So what we're going to do is, we're going to do a workaround suggested by Versal, where we're just going to take all the paths, we're going to serialize them into a physical file, and then we're going to take that file back in getStaticProps. I'm just going to again do the implementation and fast forward.

Now you see here that I'm storing all the paths in the cache. The last thing I need to do here is to provide all the slugs, right, this is the second point from the presentation. We need to get all the paths, historic ones and current ones, and return it back to Next.js here. Because we're just telling Next.js, on this path, there is not a 404, there is a page here. And now we need to do the third step, and that is issue a proper redirect if we find out we should. So, in this case, we're just taking the path from cache and if there is a page that should be redirected, it will have the redirects.to field. Because these are all the historic URLs slugs, and we need to redirect them to this path. So, we can do a simple condition here, if path.redirects.to exists.

3. Implementing Redirects and Final Thoughts#

Short description:

In order to perform the redirect, we need to return a redirect object that includes the destination and permanent fields. The destination should be set from the root of the site, and the permanent field determines whether a 307 or 308 redirect is used. After implementing the solution, we can test it by refreshing the page. The current URL slack should display the corresponding page, and appending the previous slack should redirect to the correct page. While the implementation may not be ideal, it eliminates the need for editors to perform any additional steps. If you have any questions or want to share your experience with handling URL slacks, feel free to reach out to me on Twitter.

In that case, we want to do the redirect. So, we're going to return a redirect object, and the redirect object only needs to contain a destination and a permanent. So, permanent, if you want to do 307 or 308 redirect, based on that, set the permanent field. I want permanent to be true. And in the destination, just remember if you're in the subfolder or if you're in the root, this is going to be destination from the root of your site. So in my case it's just a slash and path it redirects to. So let's save this.

There is still a problem here under get static paths. Right. I forgot. Yes there is path dot path, because here we're getting just the object, so we want the slack in there. Now, this is fine. So let's try to run the site. And let's go back to the browser and refresh this page. Now, the current URL slack is TypeScript Congress. So on that page on the URL slack we should have TypeScript Congress page. So you see this is working. And the previous slack was TypeScript Congress 2022. So if we append here 2022 we should get redirected to TypeScript Congress. So it works as expected.

Now, the implementation isn't ideal to be honest, but it works this way and lets us put everything in order. And it does not, that's the most important thing, it does not require editors to do any extra steps. It just works. And that's all from me. If you want to get more information about this solution or you want to share your experience handling URL slacks, then definitely reach out to me. You can find me on Twitter.

Ondrej Polesny
Ondrej Polesny
10 min
29 Apr, 2022

Comments

Sign in or register to post your comment.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced 2022React Advanced 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
A Practical Guide for Migrating to Server Components
React Advanced 2023React Advanced 2023
28 min
A Practical Guide for Migrating to Server Components
Top Content
Watch video: A Practical Guide for Migrating to Server Components
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
The New Next.js App Router
React Summit 2023React Summit 2023
27 min
The New Next.js App Router
Top Content
Watch video: The New Next.js App Router
Today's Talk is about the Next.js App Router, which has evolved over the years and is now a core feature of Next.js. The Talk covers topics such as adding components, fetching remote data, and exploring layouts. It also discusses submitting form data, simplifying code, and reusing components. The App Router allows for coexistence with the existing pages router and enables data fetching at the layout level using React Server Components.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced 2022React Advanced 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
AI for React Developers
React Advanced 2024React Advanced 2024
142 min
AI for React Developers
Featured Workshop
Eve Porcello
Eve Porcello
Knowledge of AI tooling is critical for future-proofing the careers of React developers, and the Vercel suite of AI tools is an approachable on-ramp. In this course, we’ll take a closer look at the Vercel AI SDK and how this can help React developers build streaming interfaces with JavaScript and Next.js. We’ll also incorporate additional 3rd party APIs to build and deploy a music visualization app.
Topics:- Creating a React Project with Next.js- Choosing a LLM- Customizing Streaming Interfaces- Building Routes- Creating and Generating Components - Using Hooks (useChat, useCompletion, useActions, etc)
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side.