How to Set Up Tailwind UI with Next.js

Published Jan 28, 2022  ∙  Updated May 2, 2022

In celebration of Tailwind CSS v3.0 and Next.js 12, let’s see how easy it is to incorporate Tailwind CSS into our Next.js projects.

1. Set up a Next.js app

Let’s start by creating our Next.js application.

npx create-next-app my-app

Be sure to replace my-app with your real app name.

Let’s navigate into this directory.

cd my-app

2. Install Tailwind dependencies

To use use Tailwind, we’ll need three dependencies: tailwind, postcss, autoprefixer.

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

If we plan on using form styles in Tailwind, we’ll likely also need @tailwindcss/forms.

npm install @tailwindcss/forms

3. Prepare config files

We’ll need config files for tailwind and postcss, both of which can be created with this command:

npx tailwindcss init -p

This should create tailwind.config.js and postcss.config.js in the root of our application.

4. Update Tailwind config

Tailwind has the ability to purge all unused styles.

We can specify which pages Tailwind should search in tailwind.config.js.

Let’s replace everything in that file with this:

module.exports = {
  purge: ['./pages/**/*.{js,ts,jsx,tsx}'],
  darkMode: false, // or 'media' or 'class'
  theme: {
     extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: []
}

Here, we want Tailwind to look for styles in all JavaScript and TypeScript folders.

The purge property is an array, so we can append other folders that may include Tailwind styles (e.g. ./components/**/*.{js,ts,jsx,tsx}).

If we need to use form styles, we need to require @tailwindcss/forms in the plugins field.

plugins: [
  require("@tailwindcss/forms")
]

5. Import Tailwind in application

Finally, we need to import Tailwind styles into our application.

The easiest place to import this file is in /pages/_app.js.

import 'tailwindcss/tailwind.css'

const App = ({ Component, pageProps }) => {
  return <Component {...pageProps} />
}
export default App;