How To Remove Gatsby Folder From Page Slug

React

25/03/2021


By default, Gatsby's gatsby-source-filesystem plugin will create a page's slug based on its file path. However, what if you wish to use folders merely for organizing your files, therefore excluding them from the slug?

In my case, I wanted to organize my blog posts by year, yet have the year excluded from the slugs (for better SEO juice 😏). In other words, I wanted a slug like /2021/remove-folder-from-gatsby-slug/ to become /remove-folder-from-gatsby-slug/.

Regex removal

While I couldn't find a "plugin supported" solution, I came up with a workaround by removing the date from the slug right after it is generated and right before it is added to a page. So in my gatsby-node.js file in the onCreateNode function, I made the following change.

DIFF
const slug = createFilePath({ node, getNode, basePath: "" })
createNodeField({
node,
name: "slug",
- value: slug,
// Remove any subfolder in the slug
+ value: slug.replace(/^\/[0-9a-z]+\//, '/'),
})

What this regular expression does is basically look at the start of the slug for a /, followed by at least one or more letters and/or numbers, and then another /. If it finds a match, it replaces the find with a /, hence the 2nd argument in the replace() function. If it doesn't, nothing happens. 😄

This regex only works on folders that do not include any special characters. For example, a folder with a hyphen like bla-bla will not work.


WRITTEN BY

Code and stuff