Solved. By checking if eight digits (YYYYMMDD) are present at the beginning of the slug in gatsby-node.js
file. With this code snippet:
/* gatsby-node.js */
let slug = createFilePath({ node, getNode, basePath: `pages` })
console.log(slug)
if (!isNaN(slug.substring(1, 9))) {
slug = slug.replace(slug.substring(1, 10), "");
console.log("removed date. new slug: " + slug);
}
I am sure there is a better way to do this. This only checks if the digits are numbers, and does not validate if the number is a date. It also assumes there is a trailing hyphen to be removed. Note this does not match the folder structure mentioned in the question, rather the basic one pages/bees-are-dying.mdx
used in the Gatsby Tutorial .
Full gatsby-node.js
here:
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const fileNode = getNode(node.parent)
console.log(`\n`, fileNode.relativePath)
let slug = createFilePath({ node, getNode, basePath: `pages` })
console.log(slug)
/*
Checks if 8 numbers are present at start of slug string,
with the isNaN numerical check recommended here https://stackoverflow.com/a/175787/9761761
If yes, these numbers and the following hyphen are removed
*/
if (!isNaN(slug.substring(1, 9))) {
slug = slug.replace(slug.substring(1, 10), "");
console.log("removed date. new slug: " + slug);
}
createNodeField({
node,
name: `slug`,
value: slug,
})
}
}
exports.createPages = async ({ graphql, actions }) => {
// **Note:** The graphql function call returns a Promise
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for more info
const { createPage } = actions
const result = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`)
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/blog-post.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.fields.slug,
},
})
})
}
Known Issue: Two pages that share the same name after the date will overwrite each other. If two files /20210309-bees-are-dying.mdx
and /20690420-bees-are-dying.mdx
exist, only one page with slug /bees-are-dying/
will prevail.