Building a Serverless Jamstack app with Redwood, Fauna and Vercel

A Redwood app combines three things: React on the front end, GraphQL for data, and Prisma for database queries. That stack gives us a serverless back end (Fauna's GraphQL API), a Jamstack front end (Redwood), and a hosted deploy (Vercel).

Generating the project

You'll need Yarn installed to run the Redwood CLI. Start there, then scaffold the app:

yarn create redwood-app ./csstricks

Change into the new project directory and start the development server:

cd csstricks
yarn rw dev

The front end serves on localhost:8910; the back end listens for GraphQL queries on localhost:8911. Redwood includes a GraphiQL playground, which we'll use later.

The Redwood starting page indicates that the front end of our app is ready to go. It also provides a nice instruction for how to start creating custom routes for the app.

As of this writing Redwood is at version 0.21.0. The docs warn against using it in production until it reaches 1.0, and there's a community forum open for feedback.

What the generated directories hold

Redwood favors convention over configuration, which means a lot of generated boilerplate. Yarn workspaces split the codebase into two directories:

├── api
│   ├── prisma
│   │   ├── schema.prisma
│   │   └── seeds.js
│   └── src
│       ├── functions
│       │   └── graphql.js
│       ├── graphql
│       ├── lib
│       │   └── db.js
│       └── services
└── web
    ├── public
    │   ├── favicon.png
    │   ├── README.md
    │   └── robots.txt
    └── src
        ├── components
        ├── layouts
        ├── pages
        │   ├── FatalErrorPage
        │   │   └── FatalErrorPage.js
        │   └── NotFoundPage
        │       └── NotFoundPage.js
        ├── index.css
        ├── index.html
        ├── index.js
        └── Routes.js

web holds front-end code: pages, layouts, and components. api holds back-end code: function handlers, the schema definition language, services for business logic, and the database client.

The framework assumes Prisma as its data store, but we're using Fauna instead, so delete the prisma directory and empty db.js — though keep the file, since we'll reuse it for the Fauna client.

Index files

A React build packs the whole site into one JavaScript bundle, rendered into the "root" DOM node at line 11 of index.html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/png" href="https://css-tricks.com/favicon.png" />
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>

  <body>
    <div id="redwood-app"></div> // HIGHLIGHT
  </body>
</html>

Redwood doesn't pre-render yet the way Next or Gatsby can, but it still counts as Jamstack: it ships static files and fetches data through JavaScript.

import ReactDOM from 'react-dom'
import { RedwoodProvider, FatalErrorBoundary } from '@redwoodjs/web'
import FatalErrorPage from 'src/pages/FatalErrorPage'
import Routes from 'src/Routes'
import './index.css'

ReactDOM.render(
  <FatalErrorBoundary page={FatalErrorPage}>
    <RedwoodProvider>
      <Routes />
    </RedwoodProvider>
  </FatalErrorBoundary>,

  document.getElementById('redwood-app')
)

index.js holds the root component. document.getElementById() selects the element whose id is redwood-app, and ReactDOM.render() mounts the application there. Inside that tree, <Routes /> and all pages sit within <RedwoodProvider>, which also packages Flash — a Context-based mechanism for passing message objects between nested components, consumed via the useFlash hook. The provider is wrapped in <FatalErrorBoundary>, which takes <FatalErrorPage> as a prop and renders it as a fallback.

Routing

The router holds every route in a Router, each declared as a Route. It matches the current URL against routes in order and stops at the first match, rendering only that route — except for notfound, which renders a single Route carrying a notfound prop when nothing else matches.

import { Router, Route } from '@redwoodjs/router'

const Routes = () => {
  return (
    <Router>
      <Route notfound page={NotFoundPage} />
    </Router>
  )
}

export default Routes

Creating pages

The generate page command creates a named route function and the matching component. Here it generates home, rendering HomePage at the URL path /:

yarn rw g page home /

rw and g are shorthand for redwood and generate. The command does four things:

  • Creates web/src/pages/HomePage/HomePage.js, capitalizing the first argument and appending "Page".
  • Creates web/src/pages/HomePage/HomePage.test.js with one passing test.
  • Creates web/src/pages/HomePage/HomePage.stories.js for Storybook.
  • Adds a <Route> to web/src/Routes.js mapping / to HomePage.
// web/src/pages/HomePage/HomePage.js

import { Link, routes } from '@redwoodjs/router'

const HomePage = () => {
  return (
    <>
      <h1>HomePage</h1>
      <p>
        Find me in <code>./web/src/pages/HomePage/HomePage.js</code>
      </p>
      <p>
        My default route is named <code>home</code>, link to me with `
        <Link to={routes.home()}>Home</Link>`
      </p>
    </>
  )
}

export default HomePage
The HomePage.js file has been set as the main route, /.

Page navigation belongs in a reusable layout, so we strip the Link and routes imports and the <Link to={routes.home()}>Home</Link> line, leaving:

// web/src/pages/HomePage/HomePage.js

const HomePage = () => {
  return (
    <>
      <h1>RedwoodJS+FaunaDB+Vercel 🚀</h1>
      <p>Taking Fullstack to the Jamstack</p>
    </>
  )
}

export default HomePage

Now the About page, same command with about instead of home. No path is needed since the route name and path both become about:

yarn rw g page about
AboutPage.js is now available at /about.
// web/src/pages/AboutPage/AboutPage.js

import { Link, routes } from '@redwoodjs/router'

const AboutPage = () => {
  return (
    <>
      <h1>AboutPage</h1>
      <p>
        Find me in <code>./web/src/pages/AboutPage/AboutPage.js</code>
      </p>
      <p>
        My default route is named <code>about</code>, link to me with `
        <Link to={routes.about()}>About</Link>`
      </p>
    </>
  )
}

export default AboutPage

Repeat the edits: remove the <Link> and routes imports and the Link to={routes.about()}>About</Link> element.

// web/src/pages/AboutPage/AboutPage.js

const AboutPage = () => {
  return (
    <>
      <h1>About 🚀🚀</h1>
      <p>For those who want to stack their Jam, fully</p>
    </>
  )
}

Routes.js now lists both routes:

const Routes = () => {
  return (
    <Router>
      <Route path="/about" page={AboutPage} name="about" />
      <Route path="/" page={HomePage} name="home" />
      <Route notfound page={NotFoundPage} />
    </Router>
  )
}

Layouts

A layout lets you import a header with navigation into as many pages as you like instead of repeating the code. Layouts have a generator too:

yarn rw g layout blog
// web/src/layouts/BlogLayout/BlogLayout.js

const BlogLayout = ({ children }) => {
  return <>{children}</>
}

export default BlogLayout

To link pages, import Link and routes from @redwoodjs/router into BlogLayout.js, add a <Link to={}></Link> per link, and pass a named route function such as routes.home() into each to={} prop:

// web/src/layouts/BlogLayout/BlogLayout.js

import { Link, routes } from '@redwoodjs/router'

const BlogLayout = ({ children }) => {
  return (
    <>
      <header>
        <h1>RedwoodJS+FaunaDB+Vercel 🚀</h1>

        <nav>
          <ul>
            <li>
              <Link to={routes.home()}>Home</Link>
            </li>
            <li>
              <Link to={routes.about()}>About</Link>
            </li>
          </ul>
        </nav>

      </header>

      <main>
        <p>{children}</p>
      </main>
    </>
  )
}

export default BlogLayout

Nothing changes in the browser yet, because no page imports BlogLayout. Import it into HomePage and wrap the whole return statement in its tags:

// web/src/pages/HomePage/HomePage.js

import BlogLayout from 'src/layouts/BlogLayout'

const HomePage = () => {
  return (
    <BlogLayout>
      <p>Taking Fullstack to the Jamstack</p>
    </BlogLayout>
  )
}

export default HomePage
Hey look, the navigation is taking shape!

Navigation to About works, but not back — AboutPage needs the layout too:

// web/src/pages/AboutPage/AboutPage.js

import BlogLayout from 'src/layouts/BlogLayout'

const AboutPage = () => {
  return (
    <BlogLayout>
      <p>For those who want to stack their Jam, fully</p>
    </BlogLayout>
  )
}

export default AboutPage

Wiring up the data layer

Create a new file called sdl.gql with the schema below. Fauna applies a few transformations to it.

// sdl.gql

type Post {
  title: String!
  body: String!
}

type Query {
  posts: [Post]
}

Save it and upload it to Fauna's GraphQL Playground; you'll need a Fauna account (the free tier is sufficient).

The GraphQL Playground is located in the selected database.
The Fauna shell allows us to write, run and test queries.

Redwood and Fauna must agree on the SDL, so the original version can't be reused — it no longer reflects the types as they exist on Fauna's database.

Running the shell's default queries shows the Post collection and posts Index unchanged, but Fauna also creates an intermediary PostPage type with a data object. That object holds an array of every Post in the database. We use these types in a second schema definition language placed in the graphql directory on the api side:

// api/src/graphql/posts.sdl.js

import gql from 'graphql-tag'

export const schema = gql`
  type Post {
    title: String!
    body: String!
  }

  type PostPage {
    data: [Post]
  }

  type Query {
    posts: PostPage
  }
`

Services and the request client

The posts service queries the Fauna GraphQL API for an array of posts, requesting title and body for each, which arrive inside the data object from PostPage:

// api/src/services/posts/posts.js

import { request } from 'src/lib/db'
import { gql } from 'graphql-request'

export const posts = async () => {
  const query = gql`
  {
    posts {
      data {
        title
        body
      }
    }
  }
  `

  const data = await request(query, 'https://graphql.fauna.com/graphql')

  return data['posts']
}

Then install graphql-request, a minimal promise-based GraphQL client:

cd api
yarn add graphql-request graphql

Token in the request header

The last piece of the connection: import graphql-request into db.js and point an endpoint at https://graphql.fauna.com/graphql. Instantiating a GraphQLClient sets the authorization header:

// api/src/lib/db.js

import { GraphQLClient } from 'graphql-request'

export const request = async (query = {}) => {
  const endpoint = 'https://graphql.fauna.com/graphql'

  const graphQLClient = new GraphQLClient(endpoint, {
    headers: {
      authorization: 'Bearer ' + process.env.FAUNADB_SECRET
    },
  })

  try {
    return await graphQLClient.request(query)
  } catch (error) {
    console.log(error)
    return error
  }
}

Seeding the database

Use the Fauna Shell and Fauna Query Language (FQL) commands to create blog posts with a title and body:

Create(
  Collection("Post"),
  {
    data: {
      title: "Deno is a secure runtime for JavaScript and TypeScript.",
      body: "The original creator of Node, Ryan Dahl, wanted to build a modern, server-side JavaScript framework that incorporates the knowledge he gained building out the initial Node ecosystem."
    }
  }
)
{
  ref: Ref(Collection("Post"), "282083736060690956"),
  ts: 1605274864200000,
  data: {
    title: "Deno is a secure runtime for JavaScript and TypeScript.",
    body:
      "The original creator of Node, Ryan Dahl, wanted to build a modern, server-side JavaScript framework that incorporates the knowledge he gained building out the initial Node ecosystem."
  }
}
Create(
  Collection("Post"),
  {
    data: {
      title: "NextJS is a React framework for building production grade applications that scale.",
      body: "To build a complete web application with React from scratch, there are many important details you need to consider such as: bundling, compilation, code splitting, static pre-rendering, server-side rendering, and client-side rendering."
    }
  }
)
{
  ref: Ref(Collection("Post"), "282083760102441484"),
  ts: 1605274887090000,
  data: {
    title:
      "NextJS is a React framework for building production grade applications that scale.",
    body:
      "To build a complete web application with React from scratch, there are many important details you need to consider such as: bundling, compilation, code splitting, static pre-rendering, server-side rendering, and client-side rendering."
  }
}
Create(
  Collection("Post"),
  {
    data: {
      title: "Vue.js is an open-source front end JavaScript framework for building user interfaces and single-page applications.",
      body: "Evan You wanted to build a framework that combined many of the things he loved about Angular and Meteor but in a way that would produce something novel. As React rose to prominence, Vue carefully observed and incorporated many lessons from React without ever losing sight of their own unique value prop."
    }
  }
)
{
  ref: Ref(Collection("Post"), "282083792286384652"),
  ts: 1605274917780000,
  data: {
    title:
      "Vue.js is an open-source front end JavaScript framework for building user interfaces and single-page applications.",
    body:
      "Evan You wanted to build a framework that combined many of the things he loved about Angular and Meteor but in a way that would produce something novel. As React rose to prominence, Vue carefully observed and incorporated many lessons from React without ever losing sight of their own unique value prop."
  }
}

Fetching with cells

Cells are a declarative way to fetch data. Each bundles a GraphQL query with loading, empty, error, and success states, and renders itself according to whichever state applies.

The BlogPostsCell

yarn rw generate cell BlogPosts

export const QUERY = gql`
  query BlogPostsQuery {
    blogPosts {
      id
    }
  }
`
export const Loading = () => <div>Loading...</div>
export const Empty = () => <div>Empty</div>
export const Failure = ({ error }) => <div>Error: {error.message}</div>

export const Success = ({ blogPosts }) => {
  return JSON.stringify(blogPosts)
}

By default the cell dumps the data with JSON.stringify where it's imported. To adapt it:

  • Rename blogPosts to posts.
  • Rename BlogPostsQuery to POSTS.
  • Query the title and body of each post.
  • Map over the data object in the success component.
  • Render a component built from each post's title and body.
// web/src/components/BlogPostsCell/BlogPostsCell.js

export const QUERY = gql`
  query POSTS {
    posts {
      data {
        title
        body
      }
    }
  }
`
export const Loading = () => <div>Loading...</div>
export const Empty = () => <div>Empty</div>
export const Failure = ({ error }) => <div>Error: {error.message}</div>

export const Success = ({ posts }) => {
  const {data} = posts
  return data.map(post => (
    <>
      <header>
        <h2>{post.title}</h2>
      </header>
      <p>{post.body}</p>
    </>
  ))
}

The POSTS query returns a data object holding an array of posts. Object destructuring pulls out data, map() walks it to reach each post, and each title goes into an <h2> inside <header> while the body gets a <p> tag.

Import the cell into HomePage:

// web/src/pages/HomePage/HomePage.js

import BlogLayout from 'src/layouts/BlogLayout'
import BlogPostsCell from 'src/components/BlogPostsCell/BlogPostsCell.js'

const HomePage = () => {
  return (
    <BlogLayout>
      <p>Taking Fullstack to the Jamstack</p>
      <BlogPostsCell />
    </BlogLayout>
  )
}

export default HomePage
Check that out! Posts are returned to the app and rendered on the front end.

Deploying on Vercel

Vercel builds the project and hosts it, with build previews triggered by pushes to the repository. The free tier suffices. Redwood's original deploy target was Netlify, and its Netlify integrations remain well documented, but the framework aims for portability across deploy targets: official Vercel support plus community integrations for the Serverless framework, AWS Fargate, and PM2.

One configuration change is required: open netlify.toml and set apiProxyPath to "/api". Then import the project in Vercel by supplying the repository URL so Vercel can watch it and build on changes.

I’m using GitHub to host my project, but Vercel is capable of working with GitLab and Bitbucket as well.

Redwood ships a preset build command that works out of the box:

Simply select “Redwood” from the preset options and we’re good to go.

The site is live but the database isn't connected yet:

Add the FAUNADB_SECRET token from your Fauna account to Vercel's environment variables:

The deploy is complete.