Stitches homepage
Blog

Using Next.js with Stitches

A simple guide to use Next.js with Stitches.

Pedro Duarte

3 min read

Next.js is a popular React framework. It comes with all the necessary features to build anything you want whilst giving you the best developer experience. It's bundled with styled-jsx but, it's possible to use any CSS-in-JS solution, should you prefer a different library.

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

There are two easy ways to do this.

npx create-next-app --example with-stitches

🎉 Done. You can skip to Step 4.

npx create-next-app

TypeScript users: follow this step from the official Next.js documentation.

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 createCss from '@stitches/react';
export const { styled, getCssString } = createCss({
theme: {
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 _document.tsx file in the /pages directory, and include the critical path CSS. Learn more about Custom Document.

import React from 'react';
import NextDocument, { Html, Head, Main, NextScript } from 'next/document';
import { getCssString } from '../stitches.config';
export default class Document extends NextDocument {
static async getInitialProps(ctx) {
try {
const initialProps = await NextDocument.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
<style id="stitches" dangerouslySetInnerHTML={{ __html: getCssString() }} />
</>
),
};
} finally {
}
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

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

// 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 Next.js 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' getCssString function to do that.

Share this post on Twitter.