In this tutorial, you’ll learn how to use Gatsby to create a blog app that integrates with the Netlify content management system (CMS) for content. Your app will allow you to author posts in Markdown and add or edit posts from your browser or Git. As a last step, you’ll secure a section of your app with Okta.

First, let’s take a step back. What is Gatsby? Gatsby is a tool for creating static websites with React. With Gatsby, you can pull data from CMSs, Markdown files, APIs, databases, and more. Gatsby uses GraphQL and webpack to combine your data and React code to generate static files for your website. 

Another piece of the puzzle here is the JAMstack. You can deliver JAM—JavaScript, APIs, and Markup—apps by pre-rendering files and serving them directly from a CDN, so you don’t have to manage or run web servers.

And as one final point of explanation before we get started, Netlify, which we’ll integrate with for content, is a hosting company for static sites that offers continuous integrations, HTML forms, AWS Lambda functions, and, (most relevant for us) content management.

Before you begin, there’s a few things you’ll need:

If you’d prefer to watch a video, you can watch this tutorial as a screencast.

To create a Gatsby site, you’ll need to install the Gatsby CLI. This tool gets you up and running with a Gatsby app in no time. It also runs a development server and builds your Gatsby application for production.

npm install -g gatsby-cli

Run gatsby new to create an app using Gatsby’s Hello World starter:

gatsby new gatsby-netlify-okta gatsbyjs/gatsby-starter-hello-world

If prompted to choose between yarn and npm, choose npm. This process creates a directory layout, adds a package.json with dependencies, and prints out instructions to continue.

Your new Gatsby site has been successfully bootstrapped. Start developing it by running:

  cd gatsby-netlify-okta
  gatsby develop

NOTE: You can also use npm start as an alias for gatsby develop. I use npm start to do the default tasks on most of my Node projects. I love this attention to detail from the Gatsby developers! ❤️

You can use the tree command to view your new project’s directory structure.

$ cd gatsby-netlify-okta
$ tree -I node_modules
.
├── LICENSE
├── README.md
├── gatsby-config.js
├── package-lock.json
├── package.json
├── src
│   └── pages
│       └── index.js
└── static
    └── favicon.ico

Run npm start and check out your “Hello World” app at http://localhost:8000.

Now let’s move on to adding a neat feature, sourcing content from Netlify CMS!

Netlify CMS is a single-page React app too! Its features include custom-styled previews, UI widgets, editor plugins, and backends to support different Git platform APIs.

You can install Netlify CMS and the Gatsby plugin for it using npm:

npm i netlify-cms-app@2.11.20 gatsby-plugin-netlify-cms@4.1.40

In gatsby-config.js, register the Netlify CMS plugin:

module.exports = {
  plugins: [`gatsby-plugin-netlify-cms`],
}

Then create a static/admin directory and a config.yml file in it.

.static/admin/config.yml

backend:
  name: test-repo
  
media_folder: static/assets
public_folder: assets
  
collections:
  - name: blog
    label: Blog
    folder: blog
    create: true
    fields:
      - { name: path, label: Path }
      - { name: date, label: Date, widget: datetime }
      - { name: title, label: Title }
      - { name: body, label: Body, widget: markdown }

Restart your app using Ctrl+C and npm start.

You’ll now be able to edit content at http://localhost:8000/admin/.

Click the Login button and you’ll see the screen below.

Everyone can log in and everything is in-memory at this point. You can even add a new blog post:

Click Publish and you’re in business!

Unfortunately, you’ll lose your post as soon as you restart your development server. However, you can update Netlify CMS to store files in Git instead!

To save to a Git repository, you can create a repo on GitHub, for example, I created one at oktadeveloper/gatsby-netlify-okta-example.

You can add Git to your Gatsby project using the following commands:

git init
git add .
git commit -m "Add project to Git"
git remote add origin git@github.com:${user}/${repo}.git
git push origin master

Now you can publish your Gatsby site straight from GitHub using Netlify’s create a new site page.

You’ll be prompted for a Git hosting provider. Click on GitHub.

Find the repository you deployed to.

Accept all the default deploy settings and click Deploy site.

You’ll return to your site’s dashboard and the build will be in progress.

In a couple of minutes, your site will be live!

If you scroll down to the Production deploys section, you can click on the build and see what happened.

You’ve built a React app, checked it into source control, and published it to production – that’s pretty cool!

Not only that, but you automated the deployment process. Any changes you push to your GitHub repo will be automatically deployed by Netlify. ��

Netlify CMS will need to authenticate with GitHub to save your content changes to your repo.

Modify static/admin/config.yml to use your GitHub repo:

backend:
  name: github
  repo: your-username/your-repo-name

In my case, I used:

backend:
  name: github
  repo: oktadeveloper/gatsby-netlify-okta-example

Save config.yml, commit the change, and push it to your GitHub repo.

git add .
git commit -m "Add GitHub Backend"
git push origin master

When your changes finish deploying on Netlify (it should take around 30 seconds), navigate to your site’s /admin/ endpoint. You’ll be prompted to log in with GitHub.

Click Login with GitHub and you’ll see a page that says “No Auth Provider Found”.

On Netlify, go to Site settings and navigate to Access control > (scroll down) OAuth.

Click Install provider. It will prompt you for a client ID and secret. To get this, navigate to GitHub Developer settings > OAuth Apps > New OAuth App.

Register a new application with the following settings:

  • Application name: My Gatsby Blog
  • Homepage URL: <copy URL from Netlify>
  • Authorization callback URL: https://api.netlify.com/auth/done

Click Register application and you’ll be provided with the client ID and secret you were looking for.

Copy and paste these values into your Netlify OAuth provider dialog and click Install.

Now if you go to your site’s /admin/ endpoint and log in with GitHub, you’ll be prompted for authorization. Click the green Authorize button at the bottom to continue.

If you see an error the first time it loads, you can ignore it. It happens because no blogs exist. Add a new one and it’ll go away. For the path, use something like /blog/first-post.

In a terminal window, run git pull origin master and you’ll see your project is updated with the post you created.

git pull origin master
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 1), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), done.
From github.com:oktadeveloper/gatsby-netlify-okta-example
 * branch            master     -> FETCH_HEAD
   c1b8722..421a113  master     -> origin/master
Updating c1b8722..421a113
Fast-forward
 blog/1st-post.md | 6 ++++++
 1 file changed, 6 insertions(+)
 create mode 100644 blog/1st-post.md

Run npm start locally to see the blog at http://localhost/admin/. But how can others (without admin access) read it?

Create a src/components/BlogRoll.js file. This file will contain a React component that queries for blog posts using GraphQL.


Then add a link to it in src/pages/index.js:

Restart your Gatsby app using npm start and navigate to http://localhost:8000.

You’ll receive an error because your project doesn’t have Markdown support.

Gatsby’s Add Markdown Pages docs show the process that it uses to create pages from Markdown files:

  1. Read files into Gatsby from the filesystem
  2. Transform Markdown to HTML and frontmatter to data
  3. Add a Markdown file
  4. Create a page component for the Markdown files
  5. Create static pages using Gatsby’s Node.js createPage() API

Install a couple of Gatsby plugins to make this happen.

npm i gatsby-source-filesystem gatsby-transformer-remark

Then configure them in gatsby-config.js:

Restart everything and you’ll be able to see your blog posts at /blog.

However, if you try to navigate into a blog, it doesn’t work because you didn’t tell Gatsby to generate pages for each one.

Create a gatsby-node.js in the root directory of your project and add code to create a static page for each blog.

You might notice this JavaScript code uses a template at src/templates/blog.js. Create this file with the following code in it.

Restart your app to see Markdown rendering properly!

Commit your changes and verify everything works in production.

git add .
git commit -m "Add /blog and Markdown support"
git push origin master

Add an Account section for your site by creating a file at src/pages/account.js.

Add a link to the account page in src/pages/index.js:

Since this section will have dynamic content that shouldn’t be rendered statically, you need to exclude it from the build. Add the following JavaScript to the bottom of gatsby-node.js to indicate that /account is a client-only route.

Restart with npm start and you should be able to navigate to this new section.

To begin with Okta, you’ll need to register your app, just like you did with GitHub. Log in to your Okta developer account and navigate to Applications > Add Application.

  • Choose Single-Page App and Next
  • Enter a name like Gatsby Account
  • Specify the following Login redirect URIs:
    • http://localhost:8000/account
    • http://localhost:9000/account
    • https://<your-site>.netlify.com/account
  • Specify the following Logout redirect URIs:
    • http://localhost:8000
    • http://localhost:9000
    • https://<your-site>.netlify.com
  • Click Done

Your Okta application settings should resemble the screenshot below.

Add Trusted Origins for Your Gatsby Sites

Gatsby can run on two different ports (8000 and 9000) locally. One is for development and one is for production (invoked with gatsby build and gatsby serve). You also have your production Netlify site. Add all of these as Trusted Origins in API > Trusted Origins.

Click Add Origin, select CORS and Redirect for Type, and add each of the following:

  • http://localhost:8000
  • http://localhost:9000
  • https://<your-site>.netlify.com

When you’re finished, your screen should resemble the following.

Install Okta’s Sign-In Widget:

npm i @okta/okta-signin-widget@3.7.2

Create a Login component in src/components/Login.js:

Replace the placeholders near the top of this file with your Okta app settings.

For example:

Modify src/pages/account.js to include an Account component that uses Login to get ID tokens and logout.

Restart your app with npm start, open http://localhost:8000 in a private window, and click on My Account. You’ll be prompted to log in.

Enter your credentials and click Sign In to browse the account section. You should also see your name and be able to logout.

To test building your app for production, run gatsby build. You’ll get an error because Okta’s Sign-In Widget doesn’t expect to be compiled for server-side rendering.

To fix this, you can exclude it from the compilation process. Modify the webpack build to exclude it from compilation by configuring webpack. Add the JavaScript below to the bottom of gatsby-node.js.

Try gatsby build again and it should work this time. Run gatsby serve to see if the production build works on http://localhost:9000. Rejoice when it does!

To give people the ability to sign-up for accounts, go to your Okta dashboard > Users > Registration, and enable it.

Modify src/components/Login.js to add Okta’s user registration feature.

Then build for production and serve it up again.

gatsby build
gatsby serve

You will now see a Sign Up link at the bottom of the login form.

Click the link to see the user registration form.

Hooray – you did it! Check-in your code and rejoice in your new-found knowledge. ��

Extend Your Gatsby Account Functionality

Armed with Okta for authentication, you could develop features in the account settings of your application. For example, a setting where people can sign up for a newsletter (e.g., with TinyLetter). You could store this setting in Okta by creating a Node app that uses the Okta Node SDK to update user attributes.

In fact, you might even develop a Java or .NET backend to handle this and communicate to it from your Gatsby application using fetch() and an OAuth 2.0 access token retrieved from the Sign-In Widget.

async componentDidMount() {
  try {
    const response = await fetch('http://<node-server-url>/user/settings', {
      headers: {
        Authorization: 'Bearer ' + await signIn.authClient.tokenManager.get('accessToken')
      }
    });
    const data = await response.json();
    this.setState({ settings: data.settings });
  } catch (err) {
    // handle error as needed
    console.error(err);
  }
}

Phew! This tutorial packed a punch! ����

You learned how to build a new site with Gatsby, automate its deployment with Netlify, integrate Gatsby with Netlify CMS, process Markdown files, store your files in Git, and use Okta for authentication. Okta leverages OAuth 2.0 and OpenID Connect for its developer APIs. They’re awesome!

You can find the source code for this example on GitHub in the oktadeveloper/gatsby-netlify-okta-example repository.

If you want to make your Gatsby site even more secure, you can use the Gatsby Netlify plugin as it adds a bunch of basic security headers. After installing, configuring, and deploying, you can test your site’s security with securityheaders.com.

I learned a bunch about Gatsby and authentication from Jason Lengstorf and Aaron Parecki in their Add authentication to your apps with Okta video.

Gatsby’s documentation was extremely helpful in writing this post, as was the Gatsby + Netlify CMS Starter.

To see how the Okta Sign-In Widget can be customized, check out developer.okta.com/live-widget.

To learn more about Netlify, React, OAuth 2.0, and OIDC, I recommend some of our other blog posts:

If you liked this tutorial, please follow @oktadev on Twitter. We also like to do screencasts and post them to our YouTube channel. If you have any questions, I’d be happy to answer them in the comments below. 





Source link

Write A Comment