Issue targeting individual blog posts on portfolio site resolved with GraphQL query fix
You're absolutely right about the issue! Your GraphQL query in templates/blog.js is not filtering by slug, so it's just returning one post (likely the first or most recent one) regardless of which URL you're on.
The fix involves two parts:
1. Update your template query to accept a slug parameter
In templates/blog.js, modify your query to filter by the slug:
export const query = graphql`
query ($slug: String!) {
sanityPost(slug: {current: {eq: $slug}}) {
id
slug {
current
}
title
publishedAt(formatString: "MMM Do, YYYY")
_rawBody
}
}
`The key changes:
- Added
query ($slug: String!)to accept a slug parameter - Added
(slug: {current: {eq: $slug}})to filter the specific post
2. Create pages programmatically in gatsby-node.js
You need to use Gatsby's createPages API to generate individual pages for each blog post and pass the slug as context. In your gatsby-node.js:
const path = require('path')
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
{
allSanityPost {
nodes {
slug {
current
}
}
}
}
`)
result.data.allSanityPost.nodes.forEach((node) => {
createPage({
path: `/blog/${node.slug.current}`,
component: path.resolve('./src/templates/blog.js'),
context: {
slug: node.slug.current
}
})
})
}This creates a page for each post and passes the slug as context, which becomes the $slug variable in your template query.
After making these changes, restart your Gatsby dev server (gatsby clean && gatsby develop is recommended to clear the cache).
The gatsby-source-sanity plugin handles all the data fetching from Sanity, and this pattern of using createPages with context variables is the standard Gatsby approach for dynamic pages from any CMS. The _raw fields you're using (like _rawBody) are specific to the Gatsby integration and work perfectly for rendering Portable Text content!
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.