Stitches homepage
Blog

Using Gatsby with Stitches

A simple guide to use Gatsby with Stitches.

Pedro Duarte

4 min read

Gatsby is a popular React framework for creating websites and apps. It's built with performance, scalability and security in mind. Backed up a wide ecosystem, Gatsby has Plugins for integrating services, Themes for effortless configuration and Recipes for automating common chores.

In this guide, I'll show you how you can use Gatsby with Stitches.

First and foremost, install the Gatsby CLI:

npm install -g gatsby-cli

Create a new Gatbsy site:

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

There are two ways to do this.

The Short Way

You can use the gatsby-theme-stitches Gatsby Theme, created by Hyeseong Kim.

yarn add gatsby-theme-stitches @stitches/react

Refer to the gatsby-theme-stitches docs for more information.

🎉 You can skip to Step 5.

The Slightly Longer Way

Set up and configure Stitches. Create a stitches.config.ts file (I usually do this in the root). Optionally provide a configuration object.

Finally, export the styled and css functions.

import { createStitches } from '@stitches/react';
export const { styled, css } = createStitches({
tokens: {
fonts: {
system: 'system-ui',
},
colors: {
hiContrast: 'hsl(206,10%,5%)',
loContrast: 'white',
},
fontSizes: {
1: '13px',
2: '15px',
3: '17px',
},
},
});

Set up server-side rendering. Create a gatsby-ssr.js and include the critical path CSS. Learn more about Gatsby SSR APIs.

import * as React from 'react';
import { getCssText } from './src/stitches.config';
export const onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<style id="stitches" dangerouslySetInnerHTML={{ __html: getCssText(), }} />,
]);
};

From this point onwards, you can import the styled function and you're good to go.

// src/pages/index.js
import { styled } from '../stitches.config';
const Text = styled('p', {
fontFamily: '$system',
color: '$hiContrast',
variants: {
size: {
1: {
fontSize: '$1',
},
2: {
fontSize: '$2',
},
3: {
fontSize: '$3',
},
},
},
});
export default function Home() {
return (
<Text as="h1" size="3">
Hello, from Stitches.
</Text>
);
}

The example above creates a Text Component. It relies on token-aware values and variants.

Setting up Stitches in a Gatsby project is straight-forward.

Apart from the unavoidable initial configuration, the only thing left to do is to make sure the styles are server-side rendered. We took advantage of Stitches' getCssText function to do that.

For a full working demo, hop over to the gatsby-with-stitches-demo repository.

Share this post on Twitter.