Author: Richard Haines

Posted: 11 Mar 2020

take me there

We have setup our project but it doesn't do much right now. Lets add a backend to store our products!

This is part 2 in a series of tutorials. The format is step by step.

So lets recap what we have done so far:
  • Setup a project
  • Added our demo and theme projects
  • Linked our demo to our theme
  • Created a repository and committed our work
  • Added a site layout
  • Added our theme styles

Backend support

Having a website that looks sweet is all well and good but we are going to need somewhere to store and our products data. We could do it from the filesystem but thats not very user friendly. What if we could not only store our products data somewhere, but we could also give the user of our theme a nice UI from which to enter their data..... Enter Sanity.io πŸ’ƒ

Sanity will allow us easily (and i really mean easily πŸ˜‰) set up our backend with a React based dashboard. The schema is super easy to get the hang of. Lets get started!

At our project root create a new folder called studio. Navigate into that folder and install the sanity CLI then initialize the sanity project.

1yarn global add @sanity/cli
2sanity init

This will globally install the CLI and create a new project for us. You can follow the step provided by the CLI, choose the ecommerce template and for the rest you can accept the defaults.

I have noticed some lag when running sanity init via the in built vscode terminal, it can hang. If it does i recommend quitting and running the command from another terminal. I use Cmder.

Once installed open the studio folder and you will see some schema definition files. Open the product.js file. It should look like this:

Product Schema

1export default {
2 name: 'product',
3 title: 'Product',
4 type: 'document',
5 fields: [
6 {
7 name: 'title',
8 title: 'Title',
9 type: 'string'
10 },
11 {
12 name: 'slug',
13 title: 'Slug',
14 type: 'slug',
15 options: {
16 source: 'title',
17 maxLength: 96
18 }
19 },
20 {
21 title: 'Default variant',
22 name: 'defaultProductVariant',
23 type: 'productVariant'
24 },
25 {
26 title: 'Variants',
27 name: 'variants',
28 type: 'array',
29 of: [
30 {
31 title: 'Variant',
32 type: 'productVariant'
33 }
34 ]
35 },
36 {
37 title: 'Tags',
38 name: 'tags',
39 type: 'array',
40 of: [
41 {
42 type: 'string'
43 }
44 ],
45 options: {
46 layout: 'tags'
47 }
48 },
49 {
50 name: 'vendor',
51 title: 'Vendor',
52 type: 'reference',
53 to: {type: 'vendor'}
54 },
55 {
56 name: 'blurb',
57 title: 'Blurb',
58 type: 'localeString'
59 },
60 {
61 name: 'body',
62 title: 'Body',
63 type: 'localeBlockContent'
64 }
65 ],
66
67 preview: {
68 select: {
69 title: 'title',
70 manufactor: 'manufactor.title',
71 media: 'defaultProductVariant.images[0]'
72 }
73 }
74}

Each object in the fields array corresponds to an input field in the studio, you can see the type the field expects with the type key. For some they refer to other objects which themselves define their own input fields. For example the Default variant object field. For more information of the inner workings of sanity i highly suggest you go over their docs. They are really exceptional. For now we can leave this file as is.

After you have had a little explore of the different schema files and read the docs on the sanity site create a new file in the schemas folder and call it home.js. We will use this to allow the theme user to add a hero image to the home page of our theme. Add the following to the new home.js schema file:

Home Schema

1export default {
2 title: 'Home Page Image',
3 name: 'home',
4 type: 'document',
5 fields: [
6 {
7 name: 'title',
8 title: 'Title',
9 type: 'string'
10 },
11 {
12 name: 'slug',
13 title: 'Slug',
14 type: 'slug',
15 options: {
16 source: 'title',
17 maxLength: 96
18 }
19 },
20 {
21 name: 'alt',
22 title: 'Alt text',
23 type: 'string'
24 },
25 {
26 name: 'images',
27 title: 'Home Images',
28 type: 'array',
29 of: [
30 {
31 type: 'image',
32 options: {
33 hotspot: true
34 }
35 }
36 ]
37 },
38 ]
39 }

The title field will be the name of our website. You can auto generate the slug in the studio. The images array will allow us to add multiple images which we will be able to access via a graphql query on our home page, page. Wait till you check out the image handling in the studio πŸ‘―β€β™€οΈ

We can also create our blog post schema. You'll notice that this time we have added a description to each field object. This will show in the studio as helper text to explain to the user what they should do or what the input expects. Its a small but important feature when thinking about studio handover, in our case, the end user of our theme.

Blog Post Schema

1export default {
2 name: 'post',
3 type: 'document',
4 title: 'Blog Post',
5 fields: [
6 {
7 name: 'title',
8 type: 'string',
9 title: 'Title',
10 description: 'Titles should be catchy, descriptive, and not too long'
11 },
12 {
13 name: 'slug',
14 type: 'slug',
15 title: 'Slug',
16 description: 'Some frontends will require a slug to be set to be able to show the post',
17 options: {
18 source: 'title',
19 maxLength: 96
20 }
21 },
22 {
23 name: 'publishedAt',
24 type: 'datetime',
25 title: 'Published at',
26 description: 'This can be used to schedule post for publishing'
27 },
28 {
29 name: 'mainImage',
30 type: 'mainImage',
31 title: 'Main image'
32 },
33 {
34 name: 'excerpt',
35 type: 'excerptPortableText',
36 title: 'Excerpt',
37 description:
38 'This ends up on summary pages, on Google, when people share your post in social media.'
39 },
40 {
41 name: 'authors',
42 title: 'Authors',
43 type: 'array',
44 of: [
45 {
46 type: 'authorReference'
47 }
48 ]
49 },
50 {
51 name: 'categories',
52 type: 'array',
53 title: 'Categories',
54 of: [
55 {
56 type: 'reference',
57 to: {
58 type: 'category'
59 }
60 }
61 ]
62 },
63 {
64 name: 'body',
65 type: 'bodyPortableText',
66 title: 'Body'
67 }
68 ],
69 orderings: [
70 {
71 name: 'publishingDateAsc',
72 title: 'Publishing date new–>old',
73 by: [
74 {
75 field: 'publishedAt',
76 direction: 'asc'
77 },
78 {
79 field: 'title',
80 direction: 'asc'
81 }
82 ]
83 },
84 {
85 name: 'publishingDateDesc',
86 title: 'Publishing date old->new',
87 by: [
88 {
89 field: 'publishedAt',
90 direction: 'desc'
91 },
92 {
93 field: 'title',
94 direction: 'asc'
95 }
96 ]
97 }
98 ]
99}

Next open the schema.js file located in the same folder and inside the createSchema builder we can add our home and blog schemas, make sure you import it if vscode doesn't automatically do this for you. By default the function is well commented.

Now that we have created our new home page and blog schemas and exported them in the builder function we can deploy and start our studio!

1sanity graphql deploy
2sanity deploy

When deploying we can host our studio anywhere we like but sanity can also handle this for us. If we make a change to our schema we have to remember to run sanity graphql deploy for the changes to take affect. You should now be able to view the studio at gatsby-theme-fashion.sanity.studio. On the left of the studio you will see all of our content, the stuff created from the schema definitions. Click on the product and then click to create a new product. Now you should be able to see how each of the field type are represented in the studio. The default variant box is where we will be getting most of our data from. Feel free add some products, filling in the necessary information. As we chose the ecommerce template there will already be some products you can use for reference. I would suggest looking over them and adding your own. Once done remove the default template products.

Open the home content tab on the left and add an image to be displayed on the home page of our theme. Make sure you remember to hit publish every time you add or change something in the studio otherwise nothing will happen πŸ˜†. If you open the blog content tab and scroll down you will see what looks like a wysiwyg editor. This is sanities rich text editor. In order to properly display its contents in our theme we will need to install another package.

1yarn add @sanity/block-content-to-react

This will render an array of block text from the rich text editor in our studio. Each paragraph will be an index in the array. Now in order to use this component and display our rich text properly we will have to create some serializers. This concept was hard for me to understand at first and i did do some hacky stuff to get it working. The actual way of doing it, once you get it right is very simple. There is a handy blog post about it by Eric Howey - using-theme-ui-with-sanity that gives an example of using the serializers with theme-ui, we'll be using the sx prop directly instead of importing the theme-ui Styled component but it will work much the same way. Lets create a folder under components and name it common. Inside create a file called index.js and add the following:

Serializers

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3
4export const serializers = {
5 types: {
6 block(props) {
7 switch (props.node.style) {
8 case "h1":
9 return <h1 sx={{
10 fontFamily: 'heading',
11 fontWeight: 'bold'
12 }}>{props.children}</h1>;
13 case "h2":
14 return <h2 sx={{
15 fontFamily: 'heading'
16 }}>{props.children}</h2>;
17 default:
18 return <p sx={{
19 fontFamily: 'body'
20 }}>{props.children}</p>;
21 }
22 }
23 }
24};

We are styling the html elements that are specified in the rich text editor in our studio with the theme-ui sx prop, getting the values from our theme file. Pretty nifty. For a more in depth look into how it works check out the sanity.io docs. Of course you can add all the html elements your heart desires so long as they are already defined in the schema for block content. In fact, lets take a peek at that file so that you know what i mean:

Block Content

1/**
2 * This is the schema definition for the rich text fields used for
3 * for this blog studio. When you import it in schemas.js it can be
4 * reused in other parts of the studio with:
5 * {
6 * name: 'someName',
7 * title: 'Some title',
8 * type: 'blockContent'
9 * }
10 */
11export default {
12 title: 'Block Content',
13 name: 'blockContent',
14 type: 'array',
15 of: [
16 {
17 title: 'Block',
18 type: 'block',
19 // Styles let you set what your user can mark up blocks with. These
20 // corresponds with HTML tags, but you can set any title or value
21 // you want and decide how you want to deal with it where you want to
22 // use your content.
23 styles: [
24 {title: 'Normal', value: 'normal'},
25 {title: 'H1', value: 'h1'},
26 {title: 'H2', value: 'h2'},
27 {title: 'H3', value: 'h3'},
28 {title: 'H4', value: 'h4'},
29 {title: 'Quote', value: 'blockquote'}
30 ],
31 lists: [{title: 'Bullet', value: 'bullet'}],
32 // Marks let you mark up inline text in the block editor.
33 marks: {
34 // Decorators usually describe a single property – e.g. a typographic
35 // preference or highlighting by editors.
36 decorators: [{title: 'Strong', value: 'strong'}, {title: 'Emphasis', value: 'em'}],
37 // Annotations can be any object structure – e.g. a link or a footnote.
38 annotations: [
39 {
40 title: 'URL',
41 name: 'link',
42 type: 'object',
43 fields: [
44 {
45 title: 'URL',
46 name: 'href',
47 type: 'url'
48 }
49 ]
50 }
51 ]
52 }
53 },
54 // You can add additional types here. Note that you can't use
55 // primitive types such as 'string' and 'number' in the same array
56 // as a block type.
57 {
58 type: 'image',
59 options: {hotspot: true}
60 }
61 ]
62}

This is taken directly from the template project output. You should have the same in your sanity project under the schemas folder. As you can see the blocks array defines the markup we want to use in our rich text editor, these are the defaults, you can add or remove as many as you wish. Again, see the docs for more info 😊

So lets recap what we have done so far:
  • Added sanity to our project
  • Looked at the schemas
  • Added our own home and blog post schemas
  • Deployed our studio and added some products and a home page image
  • Looked at serializers and added our own to handle the rich text input for our blog posts

We're making great headway! Now that we have our sanity backend up and running we need to hook it up to our theme. Head over to the theme projects root and install the gatsby-source-sanity plugin.

1yarn add gatsby-source-sanity

Now create two .env files at the demo sites root. .env.development and .env.production. In these files add the following:

Env Files

1SANITY_PROJECT_ID=<your-sanity-project-id>
2SANITY_PROJECT_DATASET=<your-sanity-dataset>

If you go to https://manage.sanity.io/ and click on your project, gatsby-theme-fashion, or whatever you chose to name it you will find your project id below the project name. You can find the dataset name if you have forgotten what you called it (it will be production if you went with the defaults) under the datasets tab directly under the project id and studio link.

Lets tell our theme to expect these variables form the consumer. Open the themes gatsby-config.js file and add the following:

Theme - gatsby-config.js

1module.exports = (options) => {
2 const {SANITY_PROJECT_ID, SANITY_PROJECT_DATASET} = options;
3
4 return {
5 plugins: [
6 {
7 resolve: 'gatsby-plugin-google-fonts',
8 options: {
9 fonts: [
10 'Muli',
11 'Open Sans',
12 'source sans pro\:300,400,400i,700'
13 ]
14 }
15 },
16 {
17 resolve: 'gatsby-source-sanity',
18 options: {
19 projectId: SANITY_PROJECT_ID,
20 dataset: SANITY_PROJECT_DATASET,
21 watchMode: false
22 }
23 },
24 'gatsby-plugin-theme-ui'
25 ]
26 }
27}

Now we want to navigate to our gatsby-config.js file in our demo sites folder and add the following:

Demo- gatsby-config.js

1let activeEnv =
2 process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development" || "production"
3
4require("dotenv").config({
5 path: `.env.${activeEnv}`,
6})
7
8module.exports = {
9 plugins: [
10 {
11 resolve: 'gatsby-theme-fashion',
12 options: {
13 SANITY_PROJECT_ID: process.env.SANITY_PROJECT_ID,
14 SANITY_PROJECT_DATASET: process.env.SANITY_PROJECT_DATASET
15 }
16 }
17 ]
18};

Here we are checking what environment we are in and getting the env variables dependant on that. We will just add the same data to both the development and production env files but you can create different ones dependant on your needs. Its important to always keep your API keys and other sensitive information hidden so the go to thing to do is use env variables.

Now that we have configured our theme to use our sanity backend we can start creating some components to fetch the data and display it. We'll start with the home page. As of now all we have to display is our hero image we added to our home content in the studio. Create a folder under components and call it home. Inside create a new file and call it hero.js.

Hero Image

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import { graphql, useStaticQuery } from "gatsby";
4import GatsbyImage from "gatsby-image";
5
6const Hero = () => {
7 const home = useStaticQuery(query);
8 const { images, title, alt } = home.sanityHome;
9
10 return (
11 <section sx={{
12 margin: '2em'
13 }}>
14 <GatsbyImage sx={{
15 width: 'auto',
16 height: 'auto',
17 maxWidth: '80%',
18 maxHeight: '90%',
19 margin: '0 auto'
20 }} fluid={images[0].asset.fluid} alt={alt} />
21 </section>
22 );
23};
24
25export default Hero;
26
27export const query = graphql`
28 query HeroQuery {
29 sanityHome {
30 title
31 alt
32 images {
33 asset {
34 fluid(maxHeight: 865) {
35 ...GatsbySanityImageFluid
36 }
37 }
38 }
39 }
40 }
41`;

Lets break it down.

  • We have created a new component that fetches the hero image via a graphql query.
  • We access that query using gatsbys nifty hook useStaticQuery.
  • We have destructured the resulting content and passed it to a gatsby image component.
  • We have added some styling using the sx prop.

This component is now ready to be imported into our index.js file that is waiting for us all lonley in the pages folder of our theme. Right now it looks like this:

Home Page

1import React from 'react'
2
3export default () => <h1>Hello im coming at you from the theme!!<h1>

Lets remove all that and add our hero image!

Home Page

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import Main from "../components/layout/main";
4import Hero from "../components/home/hero";
5
6export default () => {
7
8 return (
9 <Main>
10 <Hero/>
11 </Main>
12 )
13}

By importing the Main component and using it as the parent to all others in this component we have told gatsby that anything inside this component will live in the grid area main. This will be the pattern moving forward for all of our pages.

Go to the demo project and run yarn dev to see your image displayed. Lets take a look at our content plan again and check off what we have done:

  • Navbar
  • Landing/home page βœ…
    • Hero image βœ…
    • Showcase of products
    • Blog snippets
    • Instagram feed
    • Contact section
    • About section
  • Products page
  • Blog page
    • Blog posts page

We've still got some way to go πŸ˜… The showcase and blog post snippets both require us to do some setup before we can add them to the home page. So lets go ahead and create the about, contact and instagram feed sections!

We can begin by adding a container div to our home page component (index.js) and styling it with our trusty friend the grid.

Home Page

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import Main from "../components/layout/main";
4import Hero from "../components/home/hero";
5
6export default () => {
7
8 return (
9 <Main>
10 <div sx={{
11 display: 'grid',
12 gridTemplateRows: "auto",
13 }}>
14 <Hero/>
15 <section>About Section</section>
16 <section>Showcase Section</section>
17 <section>Blog Snippet Section</section>
18 <section>Instagram Feed</section>
19 </div>
20 </Main>
21 )
22}

Seeing as our home page sections are all going to be the same we can extract that to a new component. Create a new home-section.js file under the components/home folder.

Home Section

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3
4const HomeSection = ({children}) => (
5 <section
6 sx={{
7 height: 'max-content',
8 padding: '1em'
9 }}
10 >
11 {children}
12 </section>
13);
14
15export default HomeSection;

We can now import and use that component to wrap our placeholder sections in our home page.

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import Main from "../components/layout/main";
4import Hero from "../components/home/hero";
5import HomeSection from "../components/home/home-section";
6
7export default () => {
8
9 return (
10 <Main>
11 <div sx={{
12 display: 'grid',
13 gridTemplateRows: "auto",
14 }}>
15 <Hero/>
16 <HomeSection>About Section</HomeSection>
17 <HomeSection>Showcase Section</HomeSection>
18 <HomeSection>Blog Snippet Section</HomeSection>
19 <HomeSection>Instagram Feed</HomeSection>
20 </div>
21 </Main>
22 )
23}

Our about section will simply display some text that we will import via a graphql query form our sanity backend. First we need to create the schema for that. Head into the sanity project and create a new schema file under the schema folder and call it about.js

About Schema

1export default {
2 name: 'about',
3 title: 'About',
4 type: 'document',
5 fields: [
6 {
7 name: 'title',
8 title: 'About Title',
9 type: 'string',
10 description: 'The title of the page',
11 },
12 {
13 name: 'slug',
14 title: 'Slug',
15 type: 'slug',
16 description: 'The slug for the page',
17 options: {
18 source: 'title',
19 maxLength: 96
20 }
21 },
22 {
23 title: 'About Us',
24 name: 'aboutUs',
25 type: 'array',
26 of: [
27 {
28 type: 'block'
29 },
30 {
31 type: 'image'
32 }
33 ]
34 }
35 ]
36}

Import it into the schema file and deploy. Then add some content.

1sanity graphql deploy
2sanity deploy

Now we can use the sanity block-content-to-react package and our sanitizers. Create an about-section.js file under components/home

About Section

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import PortableText from "@sanity/block-content-to-react";
4import { graphql, useStaticQuery } from "gatsby";
5import {serializers} from "../components/common";
6
7const AboutSection = () => {
8 const about = useStaticQuery(query);
9 const info = about.allSanityAbout.nodes;
10
11 return (
12 <div sx={{
13 width: '100%'
14 }}>
15 {info.map((node, index) => (
16 <PortableText
17 key={node.title + index}
18 blocks={node._rawAboutUs}
19 serializers={serializers}
20 />
21 ))}
22 </div>
23 );
24}
25
26export default AboutSection;
27
28export const query = graphql`
29 query AboutQuery {
30 allSanityAbout {
31 nodes {
32 title
33 _rawAboutUs(resolveReferences: { maxDepth: 10 })
34 }
35 }
36 }
37`;

Lets add our new about component to our home page:

Home Page

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import Main from "../components/layout/main";
4import Hero from "../components/home/hero";
5import HomeSection from "../components/home/home-section";
6import AboutSection from "../components/home/about-section";
7
8export default () => {
9
10 return (
11 <Main>
12 <div sx={{
13 display: 'grid',
14 gridTemplateRows: "auto",
15 }}>
16 <Hero/>
17 <AboutSection/>
18 <HomeSection>Showcase Section</HomeSection>
19 <HomeSection>Blog Snippet Section</HomeSection>
20 <HomeSection>Instagram Feed</HomeSection>
21 </div>
22 </Main>
23 )
24}

Next up is our instagram feed. For this we will be using a great theme by Horacio Herrera called @horacioh/gatsby-theme-instagram. Its super simple to use and gives great results. Just what we need! From our themes root run then navigate to the themes gatsby-config.js and add it there.

1yarn add @horacioh/gatsby-theme-instagram

Theme - gatsby-config.js

1module.exports = (options) => {
2 const {SANITY_PROJECT_ID, SANITY_PROJECT_DATASET} = options;
3
4 return {
5 plugins: [
6 {
7 resolve: 'gatsby-plugin-google-fonts',
8 options: {
9 fonts: [
10 'Muli',
11 'Open Sans',
12 'source sans pro\:300,400,400i,700'
13 ]
14 }
15 },
16 {
17 resolve: 'gatsby-source-sanity',
18 options: {
19 projectId: SANITY_PROJECT_ID,
20 dataset: SANITY_PROJECT_DATASET,
21 watchMode: false
22 }
23 },
24 {
25 resolve: "@horacioh/gatsby-theme-instagram",
26 options: {
27 username: "your-instagram-username-here",
28 },
29 },
30 'gatsby-plugin-theme-ui'
31 ]
32 }
33}

Now we can add it to our home page. There are number of options for how to display the data, i suggest checking out the package docs, we will be using the grid with that standard styling.

Home Page

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import Main from "../components/layout/main";
4import Hero from "../components/home/hero";
5import HomeSection from "../components/home/home-section";
6import AboutSection from "../components/home/about-section";
7import { Grid } from "@horacioh/gatsby-theme-instagram";
8
9export default () => {
10
11 return (
12 <Main>
13 <div sx={{
14 display: 'grid',
15 gridTemplateRows: "auto",
16 }}>
17 <Hero/>
18 <AboutSection/>
19 <HomeSection>Showcase Section</HomeSection>
20 <HomeSection>Blog Snippet Section</HomeSection>
21 <HomeSection>
22 <Grid />
23 </HomeSection>
24 </div>
25 </Main>
26 )
27}
So lets recap what we have done so far:
  • Added env variables and connected our theme to our sanity studio
  • Created a Hero image component
  • Created our home page layout
  • Extracted our home page sections to a component.
  • Created a new schema for about information
  • Created a new AboutSection component and fetched our about information from the studio via graphql query
  • Used the blockContent package to render our about information
  • Installed and added our Instagram feed to our home page

πŸ˜… Wow, we have accomplished a lot! I think this is a good place to stop and reflect on what we have done so far. In the next part we will be diving into gatsby-node.js and creating pages from queries on the fly using some templates that we will create. 😎

Edit on GitHub.Previous: How to make a gatsby ecommerce theme. Part 1Next: Notes on JavaScript