Introduction
In this post, we will set up Nextjs, Tailwind CSS and Styled Components with TypeScript, using the following tools:
- Nextjs
- Tailwind CSS
- Styled Components
- TypeScript
Prerequisites
You need to have the following tools installed on your system:
- Node.js
- Yarn
Set up the Nextjs app
Step 1: create a Nextjs app
First, we will create a Nextjs app using the following command:
# Create a Nextjs apppnpm create next-app nextjs-tailwind-styled-components-typescriptThen you will be asked whether to use TypeScript and ESLint. Choose the following options:
# Choose a TypeScript✔ Would you like to use TypeScript with this project? … No / Yes # Choose Yes
# Choose a ESLint✔ Would you like to use ESLint with this project? … No / Yes # Choose YesStep 2: go to the Nextjs app directory
After creating the Nextjs app, we need to go to the Nextjs app directory using the following command:
# Go to the Nextjs app directorycd nextjs-tailwind-styled-components-typescriptStep 3: prepare the Nextjs app
First, we need to install the following dependencies:
# Install the following dependenciespnpm add -D eslint-config-prettier eslint-plugin-prettier prettierNext, we need to create a .npmrc file in the root directory of the Nextjs app, and we will add the following content to the .npmrc file:
# Create a .npmrc filetouch .npmrc# Add the following content to the .npmrc fileshamefully-hoist=trueengine-strict=truesave-exact = truetag-version-prefix=""strict-peer-dependencies = falseauto-install-peers = truelockfile = trueNext, we need to create a .nvmrc file in the root directory of the Nextjs app, and we will add the following content to the .nvmrc file:
# Create a .nvmrc filetouch .nvmrc# Add the following content to the .nvmrc filelts/fermiumThen, we need to create a .yarnrc file in the root directory of the Nextjs app, and we will add the following content to the .yarnrc file:
# Create a .yarnrc filetouch .yarnrc# Add the following content to the .yarnrc file--install.ignore-engines trueThen, we need to create a .prettierrc file in the root directory of the Nextjs app, and we will add the following content to the .prettierrc file:
# Create a .prettierrc filetouch .prettierrc# Add the following content to the .prettierrc file{ "printWidth": 80, "tabWidth": 2, "useTabs": false, "semi": true, "singleQuote": true, "quoteProps": "as-needed", "jsxSingleQuote": false, "trailingComma": "es5", "bracketSpacing": true, "jsxBracketSameLine": false, "arrowParens": "always", "requirePragma": false, "insertPragma": false, "proseWrap": "preserve", "htmlWhitespaceSensitivity": "css", "endOfLine": "lf"}Then, we need to create a .prettierignore file in the root directory of the Nextjs app, and we will add the following content to the .prettierignore file:
# Create a .prettierignore filetouch .prettierignore# Add the following content to the .prettierignore file.yarn.vscode.nextdistnode_modulesThen, we need to create an eslint.config.mjs file in the root directory of the
Nextjs app:
# Create an eslint.config.mjs filetouch eslint.config.mjsESLint 9 reads a flat config file (eslint.config.mjs) and no longer reads
.eslintrc or .eslintignore. eslint-config-next still ships its rules in
the old format, so FlatCompat translates them, which is what
create-next-app generates too. Ignore patterns move into the config itself
under ignores:
// Add the following content to the eslint.config.mjs fileimport {FlatCompat} from '@eslint/eslintrc';import {dirname} from 'node:path';import {fileURLToPath} from 'node:url';
const compat = new FlatCompat({ baseDirectory: dirname(fileURLToPath(import.meta.url)),});
export default [ {ignores: ['.yarn', '.vscode', '.next', 'dist', 'node_modules']}, ...compat.extends('next/core-web-vitals', 'plugin:prettier/recommended'), { rules: { 'prettier/prettier': ['error', {}, {usePrettierrc: true}], }, },];FlatCompat comes from @eslint/eslintrc, so add it alongside ESLint:
pnpm add -D eslint @eslint/eslintrcNext, add the engines field to the package.json file:
# Add the following content to the package.json file{ "engines": { "node": ">=20.0.0", "pnpm": ">=10.0.0" },}Step 4: install Tailwind CSS
First, we will install Tailwind CSS using the following command:
# Install Tailwind CSSpnpm add -D tailwindcss@latest postcss@latest autoprefixer@latestThen, we will create a Tailwind CSS configuration file using the following command:
# Create a Tailwind CSS configuration filepnpm exec tailwindcss init -pNext, we will change the tailwind.config.js file, and we will add the following content to the tailwind.config.js file:
// Add the following content to the tailwind.config.js file/** @type {import('tailwindcss').Config} */
module.exports = { content: ['./src/**/*.{js,ts,jsx,tsx}'], theme: { extend: {}, }, plugins: [],};Step 5: install Styled Components
First, we will install Styled Components using the following command:
# Install Styled Componentspnpm add styled-components
# Install Styled Components TypeScriptpnpm add -D @types/styled-components
# Install Styled Components Babel Pluginpnpm add -D babel-plugin-styled-componentsThen, we will create a .babelrc file in the root directory of the Nextjs app using the following command:
# Create a .babelrc filetouch .babelrcThen, we will add the following code to the .babelrc file:
{ "presets": ["next/babel"], "plugins": [ [ "styled-components", { "ssr": true, "displayName": true, "preprocess": false } ] ]}Step 6: install and set up twin.macro
First, we will install twin.macro using the following command:
# Install twin.macropnpm add twin.macro
# Install twin.macro Babel Pluginpnpm add -D babel-plugin-twinThen, we will add the following code to the .babelrc file:
{ "presets": ["next/babel"], "plugins": [ [ "styled-components", { "ssr": true, "displayName": true, "preprocess": false } ], [ "babel-plugin-twin", { "debug": false, "styled": "styled-components" } ], "babel-plugin-macros" ]}Next, add the babelMacros field to the package.json file:
# Add the following content to the package.json file{ "babelMacros": { "twin": { "styled": { "import": "default", "from": "styled-components" } } }}Step 7: set up _document.tsx
First, we will create a pages/_document.tsx file using the following command:
# Create a pages/_document.tsx filetouch pages/_document.tsxThen, we will add the following code to the pages/_document.tsx file:
import Document, { DocumentContext, Head, Html, Main, NextScript,} from 'next/document';import {ServerStyleSheet} from 'styled-components';
export default class _Document extends Document { static async getInitialProps(ctx: DocumentContext) { const sheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage;
try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), });
const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), }; } finally { sheet.seal(); } }
render() { return ( <Html> <Head> <meta name="theme-color" content="#000000" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }}Step 8: set up _app.tsx
We will add the following code to the pages/_app.tsx file:
import type {AppProps} from 'next/app';import Head from 'next/head';import 'tailwindcss/tailwind.css';
const _App = ({Component, pageProps}: AppProps) => { return ( <> <Head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Component {...pageProps} />; </> );};
export default _App;Step 9: Start styling
We will create a styles directory in the root directory of the Nextjs app using the following command:
# Create a styles directorymkdir stylesThen, we will create a main.ts file in the styles directory using the following command:
# Create a styles/main.ts filetouch styles/main.tsThen, we will add the following code to the styles/main.ts file:
import styled from 'styled-components';import tw from 'twin.macro';
export const Container = tw.div` flex min-h-screen flex-col items-center justify-center py-2`;
export const Main = tw.main` flex w-full flex-1 flex-col items-center justify-center px-20 text-center`;
export const Title = tw.h1` text-6xl font-bold`;
export const TitleLink = tw.a` text-blue-600`;
export const Description = tw.p` mt-3 text-2xl`;
export const DescriptionCodeHighlight = tw.code` rounded-md bg-gray-100 p-3 font-mono text-lg`;
export const Cards = tw.div` mt-6 flex max-w-4xl flex-wrap items-center justify-around sm:w-full`;
export const Card = tw.a` mt-6 w-96 rounded-xl border p-6 text-left hover:text-blue-600 focus:text-blue-600`;
export const CardTitle = tw.h3` text-2xl font-bold`;
export const CardDescription = tw.p` mt-4 text-xl`;
export const Footer = tw.footer` flex h-24 w-full items-center justify-center border-t`;
export const FooterCopyRight = tw.a` flex items-center justify-center gap-2`;Then, we will redesign the pages/index.tsx file using the following code:
import { Container, Main, Title, TitleLink, Description, DescriptionCodeHighlight, Cards, Card, CardTitle, Footer, FooterCopyRight,} from '../styles/Home.styles';import type {NextPage} from 'next';import Image from 'next/image';
const HomePage: NextPage = () => { return ( <Container> <Main> <Title> Welcome to <TitleLink href="https://nextjs.org">Next.js!</TitleLink> </Title>
<Description> Get started by editing{' '} <DescriptionCodeHighlight>pages/index.tsx</DescriptionCodeHighlight> </Description>
<Cards> <Card href="https://nextjs.org/docs"> <CardTitle>Documentation →</CardTitle> <p>Find in-depth information about Next.js features and API.</p> </Card>
<Card href="https://nextjs.org/learn"> <CardTitle>Learn →</CardTitle> <p>Learn about Next.js in an interactive course with quizzes!</p> </Card>
<Card href="https://github.com/vercel/next.js/tree/canary/examples"> <CardTitle>Examples →</CardTitle> <p>Discover and deploy boilerplate example Next.js projects.</p> </Card>
<Card href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <h2>Deploy →</h2> <p> Instantly deploy your Next.js site to a public URL with Vercel. </p> </Card> </Cards> </Main>
<Footer> <FooterCopyRight href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > Powered by{' '} <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} /> </FooterCopyRight> </Footer> </Container> );};
export default HomePage;Source Code
The source code for this tutorial is available on GitHub
Live Demo
The live demo for this tutorial is available on Vercel
Conclusion
In this tutorial, we have learned how to use Tailwind CSS with Nextjs and Styled Components. We have also learned how to use TypeScript with Nextjs and Styled Components.
References
- Next.js Official Documentation
- Tailwind CSS Official Documentation
- Styled Components Official Documentation
- TypeScript Official Documentation
- twin.macro GitHub Repository
- Next.js with TypeScript
- Install Tailwind CSS with Next.js
- Styled Components: Advanced Usage - Next.js
- Babel Official Website
- ESLint Official Website
- Prettier Official Website
- Yarn Package Manager
- Node.js Official Website
- Vercel Platform
- Source Code for this tutorial on GitHub








