{"id":4021,"date":"2023-11-04T23:14:00","date_gmt":"2023-11-04T23:14:00","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-blog-with-gatsby-and-contentful\/"},"modified":"2023-11-05T05:48:24","modified_gmt":"2023-11-05T05:48:24","slug":"how-to-build-a-blog-with-gatsby-and-contentful","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-blog-with-gatsby-and-contentful\/","title":{"rendered":"How to Build a Blog with Gatsby and Contentful"},"content":{"rendered":"
In this tutorial, we will explore how to build a blog using Gatsby and Contentful. Gatsby is a popular static site generator built with React, and Contentful is a headless content management system (CMS). Combining these two technologies allows you to create a dynamic blog with a smooth development experience.<\/p>\n
Before we get started, make sure you have the following installed on your machine:<\/p>\n
To begin, let’s create a new Gatsby project by opening a terminal and running the following command:<\/p>\n
npx gatsby new gatsby-blog\n<\/code><\/pre>\nThis will create a new Gatsby project called “gatsby-blog” in a directory of the same name. Go into the project directory:<\/p>\n
cd gatsby-blog\n<\/code><\/pre>\nStep 2: Install required dependencies<\/h2>\n
Next, we need to install the necessary packages for our blog. Run the following command to install the required dependencies:<\/p>\n
npm install gatsby-source-contentful contentful gatsby-transformer-remark react-helmet\n<\/code><\/pre>\n\ngatsby-source-contentful<\/code> is a Gatsby plugin that allows us to pull data from Contentful into our Gatsby website.<\/li>\ncontentful<\/code> is the official Contentful JavaScript SDK.<\/li>\ngatsby-transformer-remark<\/code> is a plugin for transforming Markdown files into HTML.<\/li>\nreact-helmet<\/code> allows us to manipulate the head of our HTML document.<\/li>\n<\/ul>\nStep 3: Configure Contentful<\/h2>\n
To connect our Gatsby project with Contentful, we need to set up a Contentful account and create a new space.<\/p>\n
\n- Go to the Contentful website<\/a> and sign up for a new account if you don’t already have one.<\/li>\n
- Once logged in, click on the “Create space” button to create a new space.<\/li>\n
- Give your space a name (e.g., “Gatsby Blog”) and select the option “Website” for the purpose of your space.<\/li>\n
- After creating the space, you’ll be directed to the Contentful web app. <\/li>\n<\/ol>\n
Keep this browser tab open as we’ll need the information from this page later.<\/p>\n
Step 4: Create a Contentful content model<\/h2>\n
In Contentful, a content model defines the structure of the content in each entry. We need to create a content model for our blog posts.<\/p>\n
\n- In the Contentful web app, click on the “Content model” option on the left sidebar.<\/li>\n
- Click on the “+ Add Content Type” button and name it “Blog Post”.<\/li>\n
- Add the following fields to the “Blog Post” content type:<\/li>\n<\/ol>\n
\n- Title (Text field)<\/li>\n
- Slug (Symbol field)<\/li>\n
- Published date (Date & time field)<\/li>\n
- Body (Rich text field)<\/li>\n
- Cover image (Media field)<\/li>\n<\/ul>\n
\n- Once you have added all the fields, click on the “Save” button to save the content model.<\/li>\n<\/ol>\n
Step 5: Retrieve Contentful API keys<\/h2>\n
In order for our Gatsby project to access the content from Contentful, we need to retrieve our Contentful API keys.<\/p>\n
\n- In the Contentful web app, go to “Settings” in the top-right corner.<\/li>\n
- Under the “API keys” tab, click on the “Add API key” button.<\/li>\n
- Give your API key a name (e.g., “Gatsby Blog API key”) and select the “Content Delivery” role.<\/li>\n
- After creating the API key, you will see two keys: “Space ID” and “Content Delivery API – access token”.<\/li>\n<\/ol>\n
Make sure to keep these API keys safe and avoid sharing them publicly.<\/p>\n
Step 6: Configure Gatsby to use the Contentful plugin<\/h2>\n
To connect our Gatsby project with Contentful, we need to configure the gatsby-config.js<\/code> file.<\/p>\n\n- Open the
gatsby-config.js<\/code> file in the root of your project.<\/li>\n- Replace the existing
plugins<\/code> array with the following code:<\/li>\n<\/ol>\nmodule.exports = {\n siteMetadata: {\n title: \"Gatsby Blog\",\n },\n plugins: [\n {\n resolve: `gatsby-source-contentful`,\n options: {\n spaceId: process.env.CONTENTFUL_SPACE_ID,\n accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,\n },\n },\n `gatsby-transformer-remark`,\n ],\n};\n<\/code><\/pre>\nWe are setting the spaceId<\/code> and accessToken<\/code> options for the gatsby-source-contentful<\/code> plugin. However, instead of hardcoding these values, we will use environment variables in the next step.<\/p>\nStep 7: Set up environment variables<\/h2>\n
We need to set up environment variables to securely store our Contentful API keys.<\/p>\n
\n- Create a new file called
.env.development<\/code> in the root of your project.<\/li>\n- Add the following content to the file:<\/li>\n<\/ol>\n
CONTENTFUL_SPACE_ID=<your-contentful-space-id>\nCONTENTFUL_ACCESS_TOKEN=<your-contentful-access-token>\n<\/code><\/pre>\nReplace <your-contentful-space-id><\/code> and <your-contentful-access-token><\/code> with the corresponding values from step 5.<\/p>\n\n- Create a similar
.env.production<\/code> file and fill in the same values.<\/li>\n<\/ol>\nStep 8: Create a blog post template<\/h2>\n
To display the blog posts on our Gatsby blog, we need to create a template.<\/p>\n
\n- Create a new directory called
src\/templates<\/code> in the root of your project.<\/li>\n- Inside the
templates<\/code> directory, create a new file called blog-post.js<\/code>.<\/li>\n- Add the following content to the
blog-post.js<\/code> file:<\/li>\n<\/ol>\nimport React from \"react\";\nimport { graphql } from \"gatsby\";\nimport { Helmet } from \"react-helmet\";\n\nexport default function BlogPost({ data }) {\n const post = data.contentfulBlogPost;\n\n return (\n <div>\n <Helmet>\n <title>{post.title} - Gatsby Blog<\/title>\n <\/Helmet>\n <h1>{post.title}<\/h1>\n {post.publishedDate}\n <div\n dangerouslySetInnerHTML={{ __html: post.body.childMarkdownRemark.html }}\n \/>\n <\/div>\n );\n}\n\nexport const query = graphql`\n query($slug: String!) {\n contentfulBlogPost(slug: { eq: $slug }) {\n title\n publishedDate(formatString: \"MMMM Do, YYYY\")\n body {\n childMarkdownRemark {\n html\n }\n }\n }\n }\n`;\n<\/code><\/pre>\nThe BlogPost<\/code> component receives the data<\/code> prop, which contains the blog post data from Contentful. We are using the Helmet<\/code> component from react-helmet<\/code> to set the page title dynamically based on the blog post.<\/p>\nThe GraphQL query at the bottom fetches the blog post data for the specified slug.<\/p>\n
Step 9: Fetch and render blog posts<\/h2>\n
Now let’s fetch the blog posts from Contentful and render them on our Gatsby blog.<\/p>\n
\n- Open the
gatsby-node.js<\/code> file in the root of your project.<\/li>\n- Replace the existing code with the following:<\/li>\n<\/ol>\n
exports.createPages = async ({ graphql, actions }) => {\n const { createPage } = actions;\n const result = await graphql(`\n query {\n allContentfulBlogPost {\n edges {\n node {\n slug\n }\n }\n }\n }\n `);\n\n result.data.allContentfulBlogPost.edges.forEach(({ node }) => {\n createPage({\n path: `\/blog\/${node.slug}`,\n component: require.resolve(\".\/src\/templates\/blog-post.js\"),\n context: {\n slug: node.slug,\n },\n });\n });\n};\n<\/code><\/pre>\nWe are using the createPages<\/code> API from Gatsby’s Node API to dynamically create pages for each blog post. The createPage<\/code> function creates a new page at the specified path, uses the blog-post.js<\/code> template we created earlier, and passes the blog post slug as a context.<\/p>\nStep 10: Style the blog<\/h2>\n
The last step before launching our blog is to add some styling.<\/p>\n
\n- Open the
src\/components\/layout.css<\/code> file.<\/li>\n- Replace the existing content with the following CSS:<\/li>\n<\/ol>\n
body {\n margin: 0;\n padding: 0;\n font-family: Arial, sans-serif;\n}\n\nh1 {\n margin-bottom: 0.5rem;\n}\n\np {\n color: #888;\n margin-top: 0;\n}\n\na {\n color: #007bff;\n text-decoration: none;\n}\n\n.blog-post {\n max-width: 800px;\n margin: 2rem auto;\n}\n<\/code><\/pre>\nThis CSS will give the blog posts a simple and clean styling.<\/p>\n
Step 11: Start the development server<\/h2>\n
Finally, let’s start our Gatsby development server and see the blog in action.<\/p>\n
Run the following command in the terminal:<\/p>\n
npm run develop\n<\/code><\/pre>\nYour blog should now be accessible at `http:\/\/localhost:8000`.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we learned how to build a blog using Gatsby and Contentful. We set up a Gatsby project, connected it with Contentful, created a content model for blog posts, and fetched and rendered the posts. With this foundation, you can extend your blog with features like pagination, comments, and search. Happy blogging!<\/p>\n","protected":false},"excerpt":{"rendered":"
In this tutorial, we will explore how to build a blog using Gatsby and Contentful. Gatsby is a popular static site generator built with React, and Contentful is a headless content management system (CMS). Combining these two technologies allows you to create a dynamic blog with a smooth development experience. Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[872,871,873,49,870],"yoast_head":"\nHow to Build a Blog with Gatsby and Contentful - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n