
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou'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:
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:
query ($slug: String!) to accept a slug parameter(slug: {current: {eq: $slug}}) to filter the specific postYou 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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store