Challenges

Server Rendering a GitHub Repo

Fetch Post List from GitHub

Now we are going to fetch the post list from our data repository. For that, install this NPM module:

Setup GitHub CMS

yarn add @arunoda/git-cms

Then create a file called lib/github-cms.js and add the following content:

import { GitHubCMS } from '@arunoda/git-cms'

const githubCms = new GitHubCMS({
    owner: process.env.GITHUB_REPO_OWNER,
    repo: process.env.GITHUB_REPO_NAME,
    token: process.env.GITHUB_PAT
})

export default githubCms

Now we need to update our .env.local file with the following env variables:

GITHUB_REPO_OWNER="<repo-owner>" # eg: "arunoda"
GITHUB_REPO_NAME="<repo-name>" # eg: "bulletproof-next-app-data"

Use GitHub CMS

After that, import above githubCms from the pages/index.js with:

import githubCms from '../lib/github-cms'

And remove this import:

import { promises as fsPromises } from 'fs'

Then replace the existing getStaticProps function in pages/index.js with the following:

export async function getServerSideProps () {
  const postList = await githubCms.getPostList()

  return {
    props: {
      postList
    }
  }
}

(Here's the final version of the file after all these changes.)


It's time for an experiment.

  • Now run your app with yarn dev
  • Visit http://localhost:3009
  • Create a file called 2020-July-10-Yet-Another-Post.md inside your data repository's data directory. (using GitHub's web UI)
  • Check the above page for 5 seconds
  • Reload it
Q: What was your experience?
authenticating...

Here we are using getServerSideProps instead of getStaticProps.
(Consider the case of when we run our app in the production)

Q: What's the reason for that?
authenticating...

🙏 We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: