javascript|May 02, 2021|2 min read

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

TL;DR

Add a slug field to the Strapi Article content type and configure a lifecycle hook to auto-generate URL-friendly slugs from article titles for better SEO.

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

Introduction

In our previous posts, we have seen How to Create Article in Strapi by REST APIs.

For SEO purpose, you would want that the article URL will have some nice english characters, like title.

In this post, we will configure article content type to have a slug field based on the title.

Add the field in Article Content Type

  • Goto your content type -> Article
  • Add another field
  • Text field, give it name: slug
  • in Advance setting of this field, you can write in default value as Auto generated slug
  • Save it
  • Click on Collection types -> Add new article
  • Click Configure the view
  • Click on Slug field, a popup will open
  • Click on “Editable field”. It should be OFF.
  • Click on Done, Save.

Generate Unique Slug for Article

After this, we need to write little code to generate slug.

Edit /api/article/models/article.js, and put below code:

'use strict';

/**
 * Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#lifecycle-hooks)
 * to customize this model
 */

const slugify = require('slugify');

const getUniqueSlug = async (title, num=0) => {
  let input = `${title}`;
  if (num > 0) {
    input = `${title}-${num}`;
  }
  const slug = slugify(input, {
    lower: true
   });
  const [article] = await strapi.services.article.find({
    slug: slug
  });
  if (!article){
    return slug;
  }
  else {
    return getUniqueSlug(title, num+1);
  }
}

module.exports = {
  lifecycles: {
    beforeCreate: async (data) => {
      data.slug = await getUniqueSlug(data.title);
    },
  },
};

In above code, we are using a new module: slugify. Install it via: npm i slugify

Also, I have written a custom function getUniqueSlug to get a unique slug. Otherwise, if two users write the same title. My slug will have same string. And, I did not want to give error to users to have unique title across.

Lets look at the examples below:

# title = How to do Exercise
# Slug will be
how-to-do-exercise

# Another user write same title,
# Now the slug will be
how-to-do-exercise-1

# Another user write same title,
# Now the slug will be
how-to-do-exercise-2

What Next

Note: Till now we have just populated the slug field. You would not see this slug in the actual URL. For this, now we will need to look at the frontend part.

See out next post for a dive into the frontend with Next.js

Related Posts

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

Introduction In this post, we will see: create a test user Authenticate it via…

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Introduction In this post, we will see how we can create a content type. And…

Tutorial - How to Setup Strapi Backend with Mongodb

Tutorial - How to Setup Strapi Backend with Mongodb

Introduction In this step-by-step tutorial, we will setup strapi headless CMS…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

Introduction In this post, we will use in Next.js with strapi. And, we will…

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

Introduction In this post, we will integrate Next.js with Strapi fully. And we…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…