Adding Context to Automatically Created Pages in Gatsby
Let’s say you want to modify context of index page in your Gatsby site. Since Gatsby automatically creates index page from the pages/index.js
file, you can’t set its context. To pass your own context to such pages, you need to recreate them by hand.
You can recreate a page with Gatsby’s onCreatePage
Node API, which is available inside gatsby-node.js
.
// gatsby-node.js
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions;
const newPage = Object.assign({}, page);
if (page.path === '/') {
deletePage(page);
newPage.context = {
posts: getPosts(),
data: ['some data'],
moreData: { foo: 'bar' },
};
createPage(newPage);
}
};
Find the page you want by checking its path
. For the index page, look for the /
path. For a page like about.js
it should be /about/
.
You can always use console.log(page.path)
inside onCreatePage
to print all page paths. Check your terminal while the build is running and see which path you are looking for.