How to make SEO friendly URL using Javascript and Static Site Generators
If all your pages in your app are created manually, you can skip this article, because the URL is based on the filename.
This article is helpful if you are generating pages based on data from an API.
Before showing any code on how to handle the URL with Javascript, let’s have a look at what could be the case, we want to fix.
// API{
title: "This article - is a must read!",
id: 123
}
Ok, so we receive this piece of data, and we want to create a page for it. With this, we have two choices.
A (Don’t do like this, since it doesn’t contain any keywords):
/article/:id
/article/123
B (This is what we will use, but without Javascript solution, yet):
/article/:title
/article/This%20article%20-%20is%20a%20must%20read
Now that looks pretty scary, right? Looking at those two examples above you would probably select solution A and I won’t blame you!
But no matter which one, both of them are bad SEO. What do I mean about bad SEO, you think?
SEO LOVES KEYWORDS
In URL just as much as in content. So we need to fix this URL. Here is the solution with simple Javascript
const beautifyURL = (title) =>
title
.replace(/\s/g, "-")
.replace(/-+/g, "-")
.replace(/[^a-å0-9-]/gi, "")
.toLowerCase();
Let’s have a look at each step
- We are replacing all spaces with a dash
- If more than one dash appears, replace it so it will end up with only one dash. In this example, it will replace /article/this-article — — — is-a-must-read with /article/this-article-is-a-must-read
- Remove all none letters- numbers or dashes
- Always make URL lowercase
So the final URL will be (drumroll):
/article/this-article-is-a-must-read
Yay! It doesn’t get more SEO friendly than that.
I hope you find this article useful.
I use it in all projects where it is needed and it goes very well both in Gatsby and NextJS projects