Reputation: 140833
I'm following the official documentation to have a custom slug using the gatsby-node.js but once the system is running, it is like if I had no custom configuration at all.
I can confirm using the GraphQL or visiting the website: both show the slugs from the folders structure and not the one I programmatically changed.
What I am trying to achieve is to remove the year folder in the URL. When I am setting a breakpoint in the gatsby-node.js
I see that the value for the createNodeField is set to my modified newSlug
. I have deleted the cache folder and re-run: no change. Here is the code that I am sure it is executed.
const { createFilePath } = require("gatsby-source-filesystem")
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions;
if (node.internal.type === `Mdx`) {
const relativeFilePath = createFilePath({
node,
getNode,
trailingSlash: false,
});
const newSlug = relativeFilePath.substring(6); // Remove the year
const url = `/blog/${newSlug}`;
createNodeField({
name: `slug`,
node,
value: url,
});
}
};
I expect to have /blog/my-article
but it is still to /blog/2021/my-article
, any idea?
Upvotes: 2
Views: 619
Reputation: 29315
Apparently it seems that you are creating properly the node (as for the debug information you've provided). My guess, is that besides you are creating the new slug correctly, you might be not applying it in the page creation (createPages
).
Your new slug field is created under field
node (resulting in node.fields.slug
), so your final query should look like this:
const path = require("path")
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
const result = await graphql(`
query {
allMdx {
edges {
node {
id
fields {
slug
}
}
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}
const posts = result.data.allMdx.edges
posts.forEach(({ node }, index) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/components/posts-page-layout.js`),
context: { id: node.id },
})
})
}
The path
property is where you set the path for the dynamically created page so, that should result in /blog/${newSlug}
.
Upvotes: 1