Easily add your DEV posts to any Gatsby site
Tags: webdev, javascript, gatsby, tutorial
Published: 2021-01-04 10:52:07

Last week I created a Gatsby source plugin called `gatsby-source-mydev`. This plugin is an out-of-the-box integration between your Gatsby site and your DEV account by using the DEV beta API endpoints. 

At the moment it only retrieves all articles, but this source plugin will evolve and grow depending on the DEV API.

I will show you step by step how to use this source plugin within your Gatsby site.

{% github https://github.com/basilebong/gatsby-source-mydev %}

## Create an API key

1. Go to https://dev.to/settings/account
2. Navigate to the section *DEV Community API Keys*
3. Add a project name and generate your API Key

![Generate a DEV API Key](https://dev-to-uploads.s3.amazonaws.com/i/avulkebzheuhdveoagi6.png)

## Configure your Gatsby site

Create a new Gatsby site:
```bash
gatsby new mysite
cd ./mysite
```

Install all dependencies:
```bash
npm i
```

Install `dotenv` and `gatsby-source-mydev`:
```bash
npm i -S dotenv gatsby-source-mydev
```

Create a `.env` file at the root of your project:
```bash
touch .env
```

Edit `.env` and add the following line.
Replace `MYAPIKEYXXXXX` with your API key.
```text
DEV_API_KEY=MYAPIKEYXXXXX
```

Edit `gatsby-config.js`:
```js
// In your gatsby-config.js
require('dotenv').config();

module.exports = {
  plugins: [
    // ...
    {
      resolve: `gatsby-source-mydev`,
      options: {
        apiKey: process.env.DEV_API_KEY,
      },
    },
  ],
}
```

Run your Gatsby site and go to http://localhost:8000/___graphql.

```bash
npm start
```

In the GraphQL explorer you will see `myDev` and `allMyDev`.

> Note: *Your `.env` file should always be in `.gitignore` then it contains confidetial information that should not be comitted.*

## Create a page for each article

Create a template file:
```bash
touch src/templates/blog.js
```

Install `react-markdown`:
```bash
npm i -S react-markdown
```

Edit `src/templates/blog.js`:

```jsx
import React from "react"
import ReactMarkdown from "react-markdown"

import Layout from "../components/layout"
import SEO from "../components/seo"

export default function Template({
  pageContext, // this prop will be injected by the GraphQL query below.
}) {
  const { article } = pageContext // data holds your post data
  return (
    <Layout>
        <SEO title={article.title} />
        <div className="blog-post-container">
            <div className="blog-post">
                <h1>{article.title}</h1>
                <h2>{article.published_at}</h2>
                <ReactMarkdown>{article.body_markdown}</ReactMarkdown>
            </div>
        </div>
    </Layout>
  )
}
```

Edit `gatsby-node.js`:

```jsx
/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.com/docs/node-apis/
 */

// You can delete this file if you're not using it

exports.createPages = async ({ actions, graphql, reporter }) => {
    const { createPage } = actions
    const blogPostTemplate = require.resolve(`./src/templates/blog.js`)
    const result = await graphql(`
        query {
            allMyDev {
            nodes {
                article {
                body_markdown
                canonical_url
                comments_count
                cover_image
                description
                id
                page_views_count
                path
                positive_reactions_count
                public_reactions_count
                published
                published_at
                published_timestamp
                slug
                tag_list
                title
                type_of
                url
                user {
                    github_username
                    name
                    profile_image
                    profile_image_90
                    twitter_username
                    username
                    website_url
                }
                }
            }
            }
      }
    `)
    // Handle errors
    if (result.errors) {
      reporter.panicOnBuild(`Error while running GraphQL query.`)
      return
    }
    result.data.allMyDev.nodes.forEach(({ article }) => {
      createPage({
        path: `blog/${article.slug}`,
        component: blogPostTemplate,
        context: {
            article: article
        },
      })
    })
}
```

Good job, you did it! Now when you go to http://localhost:8000/blog/article-slug you will see the content of your DEV article. 

> Note: *Replace `article-slug` by the slug of an article. The easiest way to find an article's slug is to go to your dev.to article and to copy paste the end of the url: https://dev.to/basilebong/THIS-IS-YOUR-SLUG*

I will leave the creation of a blog page list to you.

*** 
Do you need help or do you have an idea for a new feature? Open an issue [here](https://github.com/basilebong/gatsby-source-mydev/issues).

If you like my posts follow me on [dev.to](https://dev.to/basilebong) and [twitter](https://twitter.com/basilebong/)!