/jamstack-nyc

Gatsby + GraphQL Static Queries + Basic authentication

Primary LanguageCSSMIT LicenseMIT

JAMstack with Gatsby & AWS Amplify

Deploy to the Amplify console

Click the button to deploy a fullstack app in your AWS account:

amplifybutton

You can now continuously deploy changes to your frontend or backend and Amplify Console will automatically deploy those changes.

Build from scratch

To get started, first initialize an Amplify project:

amplify init

To rebuild from scratch

First create the Gatsby project

gatsby new jamstack-project

GraphQL Static Queries

  1. Install dependencies
npm install gatsby-source-graphql aws-amplify aws-amplify-react
  1. Add the GraphQL API
amplify add api
  1. Set the GraphQL Schema
type Talk @model {
  id: ID!
  name: String!
  description: String!
  speakerName: String!
}
  1. Deploy the API
amplify push
  1. Set the plugin configuration in the plugins array of gatsby-config.js
plugins: [
  {
    resolve: 'gatsby-source-graphql',
    options: {
      typeName: 'Talk',
      fieldName: 'talks',
      url: '<APPSYNC_URL>',
      headers: {
        'x-api-key': '<APPSYNC_API_KEY>'
      }
    }
  }
  // ...
]
  1. Query from the client
/* import graphql */
import { Link, graphql } from "gatsby"

/* define query */
export const query = graphql`
  query list {
    talks {
      listTalks {
        items {
          id
          name
          description
          speakerName
        }
      }
    }
  }
`

/* data is available in the app */
const IndexPage = ({ data }) => {}

Authentication

  1. Add authentication
amplify add auth

? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings? No, I am done.
  1. Configure Amplify
import Amplify from '@aws-amplify/core'
import config from '../aws-exports'
Amplify.configure(config)
  1. Create new protected route with basic component. Here, add the withAuthenticator HOC to render auth flow:
import React, { useEffect, useState } from "react"
import { Link } from 'gatsby'

import Layout from "../components/layout"

import { withAuthenticator } from 'aws-amplify-react'
import { Auth } from 'aws-amplify'

const Protected = () => {
  const [user, setUser] = useState({})
  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(user => console.log({ user }))
      .catch(err => console.log('user not signed in!: ', err))
  }, [])
  return (
    <Layout>
      <h1>Hi people</h1>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <Link to="/">Go back to the homepage</Link>
    </Layout>
  )
}

export default withAuthenticator(Protected, {
  includeGreetings: true
})