How To Use Tailwind CSS with Next.js

    In this guide, we'll walk through how to install Tailwind CSS in a Next.js project. This guide assumes you are using Next.js 9.2 or above — check out the pre 9.2 guide for earlier versions.

    1Create a new project

    If you are starting fresh, run the following command to create a new Next.js project. Otherwise, you can proceed with these steps to add Tailwind to an existing Next.js app.

    npm create next-app next-js-tailwind
    cd next-js-tailwind

    2Install dependencies

    Run the following to install Tailwind and a few other packages:

    npm install tailwindcss autoprefixer @fullhuman/postcss-purgecss --save-dev

    3Configure the build pipeline

    Create a postcss.config.js file with the following contents:

    module.exports = {
    plugins: {
    tailwindcss: {},
    autoprefixer: {},
    ...(process.env.NODE_ENV === 'production'
    ? {
    '@fullhuman/postcss-purgecss': {
    content: [
    defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    : {})

    Here were are running PurgeCSS in production to keep the CSS size to a minimum.

    4Add Tailwind to your CSS

    Create a styles.css file in the root of your project with the Tailwind directives:

    /* purgecss start ignore */
    @tailwind base;
    @tailwind components;
    /* purgecss end ignore */
    @tailwind utilities;

    The purgecss comments tell PurgeCSS to never purge important base styles.

    5Import your CSS

    If you don't already have a custom pages/_app.js file, create one like this:

    import '../styles.css';
    function App({ Component, pageProps }) {
    return <Component {...pageProps} />;
    export default App;

    If you already have a custom app file, just add the import for your stylesheet. That's it! You can now start using Tailwind CSS utilities in your className attributes!

    Check out the source on GitHub →