Next-js-Boilerplate
🚀🎉📚 Boilerplate and Starter for Next.js 14+ with App Router and Page Router support, Tailwind CSS 3.4 and TypeScript ⚡️ Made with developer experience first: Next.js + TypeScript + ESLint + Prettier + Drizzle ORM + Husky + Lint-Staged + Vitest + Testing Library + Playwright + Storybook + Commitlint + VSCode + Netlify + PostCSS + Tailwind CSS ✨
Top Related Projects
The React Framework
The best way to start a full-stack, typesafe Next.js app
🔋 Next.js + Tailwind CSS + TypeScript starter and boilerplate packed with useful development features
Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
This is a Next.js, Tailwind CSS blogging starter template. Comes out of the box configured with the latest technologies to make technical writing a breeze. Easily configurable and customizable. Perfect as a replacement to existing Jekyll and Hugo individual blogs.
💼 An enterprise-grade Next.js boilerplate for high-performance, maintainable apps. Packed with features like Tailwind CSS, TypeScript, ESLint, Prettier, testing tools, and more to accelerate your development.
Quick Overview
Next.js Boilerplate is a comprehensive starter template for building modern web applications with Next.js. It provides a well-structured foundation with pre-configured tools and best practices, allowing developers to quickly set up and start building scalable React applications.
Pros
- Includes a wide range of pre-configured tools and libraries (TypeScript, ESLint, Prettier, Husky, etc.)
- Implements best practices for performance, SEO, and developer experience
- Provides a clean and organized project structure
- Includes built-in testing setup with Jest and React Testing Library
Cons
- May include more features than needed for simple projects, potentially leading to bloat
- Requires familiarity with multiple tools and libraries to fully utilize the boilerplate
- Some developers may prefer to set up their own project structure and tools
Code Examples
- API Route Example:
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' });
}
This code creates a simple API route that returns a JSON response.
- Page Component Example:
import { Meta } from '@/layouts/Meta';
import { Main } from '@/templates/Main';
const Index = () => {
return (
<Main
meta={
<Meta
title="Next.js Boilerplate Presentation"
description="Next js Boilerplate is the perfect starter code for your project. Build your React application with the Next.js framework."
/>
}
>
<h1 className="text-2xl font-bold">
Welcome to Next.js Boilerplate!
</h1>
</Main>
);
};
export default Index;
This code creates a basic page component using the provided layouts and templates.
- Custom Hook Example:
import { useEffect, useState } from 'react';
const useScrollPosition = () => {
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
const updatePosition = () => {
setScrollPosition(window.pageYOffset);
};
window.addEventListener('scroll', updatePosition);
updatePosition();
return () => window.removeEventListener('scroll', updatePosition);
}, []);
return scrollPosition;
};
export default useScrollPosition;
This custom hook tracks the current scroll position of the window.
Getting Started
To use this boilerplate, follow these steps:
-
Clone the repository:
git clone https://github.com/ixartz/Next-js-Boilerplate.git my-project cd my-project
-
Install dependencies:
npm install
-
Start the development server:
npm run dev
-
Open your browser and navigate to
http://localhost:3000
to see your application running.
Competitor Comparisons
The React Framework
Pros of Next.js
- Official framework with extensive documentation and community support
- More frequent updates and cutting-edge features
- Broader ecosystem with official plugins and integrations
Cons of Next.js
- Steeper learning curve for beginners
- Less opinionated, requiring more setup for advanced features
- May include unnecessary features for simpler projects
Code Comparison
Next-js-Boilerplate:
import { AppProps } from 'next/app';
const MyApp = ({ Component, pageProps }: AppProps) => (
<Component {...pageProps} />
);
export default MyApp;
Next.js:
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
The code structure is similar, but Next-js-Boilerplate uses a more concise arrow function syntax, while Next.js uses a traditional function declaration. Both achieve the same result of creating a custom App component.
Next-js-Boilerplate is a pre-configured boilerplate with additional tools and best practices, making it easier to start a project quickly. It includes features like TypeScript, ESLint, and testing setups out of the box. Next.js, being the core framework, provides more flexibility but requires manual setup for these additional features.
Next.js is ideal for developers who want full control over their project structure and dependencies, while Next-js-Boilerplate is better suited for those who prefer a pre-configured environment with common tools and practices already in place.
The best way to start a full-stack, typesafe Next.js app
Pros of create-t3-app
- Offers a more comprehensive full-stack solution with built-in support for tRPC, Prisma, and NextAuth.js
- Provides a more opinionated and structured approach to building applications
- Includes TypeScript by default, ensuring type safety throughout the project
Cons of create-t3-app
- Less flexibility in terms of customization compared to Next-js-Boilerplate
- Steeper learning curve for developers unfamiliar with the T3 stack
- May include unnecessary dependencies for simpler projects
Code Comparison
Next-js-Boilerplate:
import type { Metadata } from 'next';
import { AppConfig } from '@/utils/AppConfig';
export const metadata: Metadata = {
title: AppConfig.title,
description: AppConfig.description,
};
create-t3-app:
import { type NextPage } from "next";
import Head from "next/head";
import { trpc } from "../utils/trpc";
const Home: NextPage = () => {
const hello = trpc.example.hello.useQuery({ text: "from tRPC" });
The code snippets highlight the differences in setup and structure between the two boilerplates. Next-js-Boilerplate focuses on a simpler configuration approach, while create-t3-app integrates tRPC for type-safe API calls out of the box.
🔋 Next.js + Tailwind CSS + TypeScript starter and boilerplate packed with useful development features
Pros of ts-nextjs-tailwind-starter
- More comprehensive documentation and examples for components and hooks
- Includes pre-configured Absolute Imports and Module Path Aliases
- Provides a more opinionated folder structure for better organization
Cons of ts-nextjs-tailwind-starter
- Less focus on testing setup compared to Next-js-Boilerplate
- Fewer pre-configured CI/CD options out of the box
- May require more initial setup for certain features like internationalization
Code Comparison
ts-nextjs-tailwind-starter:
import { NextSeo } from 'next-seo';
import * as React from 'react';
import Layout from '@/components/layout/Layout';
import Seo from '@/components/Seo';
export default function HomePage() {
return (
<Layout>
<Seo templateTitle='Home' />
<main>
<h1 className='text-2xl font-bold'>Welcome to Next.js</h1>
</main>
</Layout>
);
}
Next-js-Boilerplate:
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { Meta } from '@/layouts/Meta';
import { Main } from '@/templates/Main';
const Index = () => {
const { t } = useTranslation(['common', 'index']);
return (
<Main meta={<Meta title={t('common:title')} description={t('common:description')} />}>
<h1 className="text-2xl font-bold">{t('index:title')}</h1>
</Main>
);
};
export const getStaticProps = async ({ locale }: { locale: string }) => ({
props: {
...(await serverSideTranslations(locale, ['common', 'index'])),
},
});
export default Index;
Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
Pros of ui
- Highly customizable and flexible component library
- Focuses on accessibility and follows WAI-ARIA guidelines
- Provides a CLI tool for easy component installation and customization
Cons of ui
- Less opinionated structure compared to Next-js-Boilerplate
- Requires more setup and configuration for a complete project
- Limited to UI components, lacking full-stack features
Code Comparison
ui:
import { Button } from "@/components/ui/button"
export default function Home() {
return <Button>Click me</Button>
}
Next-js-Boilerplate:
import { Main } from '@/templates/Main';
const Index = () => {
return (
<Main meta={<Meta title="Home" description="Lorem ipsum" />}>
<h1>Welcome</h1>
</Main>
);
};
export default Index;
Summary
ui is a flexible UI component library that prioritizes customization and accessibility. It's ideal for developers who want granular control over their UI components. Next-js-Boilerplate, on the other hand, provides a more structured, full-stack approach with pre-configured features like TypeScript, ESLint, and testing setups. The choice between the two depends on project requirements and developer preferences.
This is a Next.js, Tailwind CSS blogging starter template. Comes out of the box configured with the latest technologies to make technical writing a breeze. Easily configurable and customizable. Perfect as a replacement to existing Jekyll and Hugo individual blogs.
Pros of tailwind-nextjs-starter-blog
- Focused on blogging: Provides a ready-to-use blog template with features like tags, categories, and SEO optimization
- Simpler setup: Fewer dependencies and configurations, making it easier for beginners to get started
- Built-in dark mode: Includes a toggle for dark/light themes out of the box
Cons of tailwind-nextjs-starter-blog
- Less comprehensive: Lacks some advanced features and tooling present in Next-js-Boilerplate
- Limited to blogging: May require more customization for non-blog projects
- Fewer testing tools: Doesn't include as robust a testing setup as Next-js-Boilerplate
Code Comparison
tailwind-nextjs-starter-blog:
<Layout>
<MDXLayoutRenderer
layout={frontMatter.layout || DEFAULT_LAYOUT}
mdxSource={mdxSource}
frontMatter={frontMatter}
/>
</Layout>
Next-js-Boilerplate:
<Main meta={<Meta title="Lorem ipsum" description="Lorem ipsum" />}>
<h1 className="capitalize">Next.js Boilerplate</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit.
</p>
</Main>
Both examples showcase the basic structure of a page layout, but tailwind-nextjs-starter-blog focuses on rendering MDX content, while Next-js-Boilerplate provides a more generic layout structure.
💼 An enterprise-grade Next.js boilerplate for high-performance, maintainable apps. Packed with features like Tailwind CSS, TypeScript, ESLint, Prettier, testing tools, and more to accelerate your development.
Pros of next-enterprise
- Includes more advanced features like OpenAI integration and Prisma ORM
- Offers a more comprehensive testing setup with Playwright and Vitest
- Provides better TypeScript support with stricter configurations
Cons of next-enterprise
- More complex setup may be overwhelming for beginners
- Heavier dependencies could lead to longer build times
- Less frequently updated compared to Next-js-Boilerplate
Code Comparison
Next-js-Boilerplate:
import type { Metadata } from 'next';
import { AppConfig } from '@/utils/AppConfig';
export const metadata: Metadata = {
title: AppConfig.title,
description: AppConfig.description,
};
next-enterprise:
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Next.js Enterprise Boilerplate',
description: 'A boilerplate for Next.js with enterprise-level features',
openGraph: {
title: 'Next.js Enterprise Boilerplate',
description: 'A boilerplate for Next.js with enterprise-level features',
url: 'https://next-enterprise.vercel.app/',
siteName: 'Next.js Enterprise Boilerplate',
},
};
Both repositories provide solid foundations for Next.js projects, but next-enterprise offers more advanced features suitable for larger, enterprise-level applications. Next-js-Boilerplate, on the other hand, provides a simpler setup that may be more appropriate for smaller projects or developers new to Next.js.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Boilerplate and Starter for Next.js 14+, Tailwind CSS 3.4, and TypeScript.
ð Boilerplate and Starter for Next.js with App Router support, Tailwind CSS, and TypeScript â¡ï¸ Prioritizing developer experience first: Next.js, TypeScript, ESLint, Prettier, Husky, Lint-Staged, Jest (replaced by Vitest), Testing Library, Commitlint, VSCode, PostCSS, Tailwind CSS, Authentication with Clerk, Database with DrizzleORM (PostgreSQL, SQLite, and MySQL), Error Monitoring with Sentry, Logging with Pino.js and Log Management, Monitoring as Code, Storybook, Multi-language (i18n), and more. Ready for Next.js 15.
Clone this project and use it to create your own Next.js project. You can check a Next js templates demo.
Sponsors
Add your logo here |
Features
Developer experience first, extremely flexible code structure and only keep what you need:
- â¡ Next.js with App Router support
- ð¥ Type checking TypeScript
- ð Integrate with Tailwind CSS
- â Strict Mode for TypeScript and React 18
- ð Authentication with Clerk: Sign up, Sign in, Sign out, Forgot password, Reset password, and more.
- ð¤ Passwordless Authentication with Magic Links, Multi-Factor Auth (MFA), Social Auth (Google, Facebook, Twitter, GitHub, Apple, and more), Passwordless login with Passkeys, User Impersonation
- ð¦ Type-safe ORM with DrizzleORM, compatible with PostgreSQL, SQLite, and MySQL
- ð½ Offline and local development database with PGlite
- ð Multi-language (i18n) with next-intl and Crowdin
- â»ï¸ Type-safe environment variables with T3 Env
- â¨ï¸ Form handling with React Hook Form
- ð´ Validation library with Zod
- ð Linter with ESLint (default Next.js, Next.js Core Web Vitals, Tailwind CSS and Airbnb configuration)
- ð Code Formatter with Prettier
- ð¦ Husky for Git Hooks
- ð« Lint-staged for running linters on Git staged files
- ð Lint git commit with Commitlint
- ð Write standard compliant commit messages with Commitizen
- 𦺠Unit Testing with Vitest and React Testing Library
- 𧪠Integration and E2E Testing with Playwright
- ð· Run tests on pull request with GitHub Actions
- ð Storybook for UI development
- ð¨ Error Monitoring with Sentry
- âï¸ Code coverage with Codecov
- ð Logging with Pino.js and Log Management with Better Stack
- ð¥ï¸ Monitoring as Code with Checkly
- ð Automatic changelog generation with Semantic Release
- ð Visual testing with Percy (Optional)
- ð¡ Absolute Imports using
@
prefix - ð VSCode configuration: Debug, Settings, Tasks and Extensions
- ð¤ SEO metadata, JSON-LD and Open Graph tags
- ðºï¸ Sitemap.xml and robots.txt
- â Database exploration with Drizzle Studio and CLI migration tool with Drizzle Kit
- âï¸ Bundler Analyzer
- ð Include a FREE minimalist theme
- ð¯ Maximize lighthouse score
Built-in feature from Next.js:
- â Minify HTML & CSS
- ð¨ Live reload
- â Cache busting
Philosophy
- Nothing is hidden from you, so you have the freedom to make the necessary adjustments to fit your needs and preferences.
- Dependencies are updated every month
- Easy to customize
- Minimal code
- SEO-friendly
- ð Production-ready
Requirements
- Node.js 20+ and npm
Getting started
Run the following command on your local environment:
git clone --depth=1 https://github.com/ixartz/Next-js-Boilerplate.git my-project-name
cd my-project-name
npm install
For your information, all dependencies are updated every month.
Then, you can run the project locally in development mode with live reload by executing:
npm run dev
Open http://localhost:3000 with your favorite browser to see your project.
Set up authentication
Create a Clerk account at Clerk.com and create a new application in Clerk Dashboard. Then, copy NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
and CLERK_SECRET_KEY
into .env.local
file (not tracked by Git):
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_pub_key
CLERK_SECRET_KEY=your_clerk_secret_key
Now, you have a fully working authentication system with Next.js: Sign up, Sign in, Sign out, Forgot password, Reset password, Update profile, Update password, Update email, Delete account, and more.
Set up remote database
The project uses DrizzleORM, a type-safe ORM compatible with PostgreSQL, SQLite, and MySQL databases. By default, the project is set up to work seamlessly with PostgreSQL and you can easily choose any PostgreSQL database provider.
Translation (i18n) setup
For translation, the project uses next-intl
combined with Crowdin. As a developer, you only need to take care of the English (or another default language) version. Other languages are automatically generated and handled by Crowdin. You can use Crowdin to collaborate with your translation team or translate the messages yourself with the help of machine translation.
To set up translation (i18n), create an account at Crowdin.com and create a new project. In the newly created project, you will able to find the project ID. You'll also require to create a new Personal Access Tokens by going to Account Settings > API. Then, in your GitHub Actions, you need to define the following environment variables CROWDIN_PROJECT_ID
and CROWDIN_PERSONAL_TOKEN
.
After defining the environment variables in your GitHub Actions, your localization files will be synchronized with Crowdin everytime you push a new commit to the main
branch.
Project structure
.
âââ README.md # README file
âââ .github # GitHub folder
âââ .husky # Husky configuration
âââ .storybook # Storybook folder
âââ .vscode # VSCode configuration
âââ migrations # Database migrations
âââ public # Public assets folder
âââ scripts # Scripts folder
âââ src
â âââ app # Next JS App (App Router)
â âââ components # React components
â âââ libs # 3rd party libraries configuration
â âââ locales # Locales folder (i18n messages)
â âââ models # Database models
â âââ styles # Styles folder
â âââ templates # Templates folder
â âââ types # Type definitions
â âââ utils # Utilities folder
â âââ validations # Validation schemas
âââ tests
â âââ e2e # E2E tests, also includes Monitoring as Code
â âââ integration # Integration tests
âââ tailwind.config.js # Tailwind CSS configuration
âââ tsconfig.json # TypeScript configuration
Customization
You can easily configure Next js Boilerplate by making a search in the whole project with FIXME:
for making quick customization. Here is some of the most important files to customize:
public/apple-touch-icon.png
,public/favicon.ico
,public/favicon-16x16.png
andpublic/favicon-32x32.png
: your website favicon, you can generate from https://favicon.io/favicon-converter/src/utils/AppConfig.ts
: configuration filesrc/templates/BaseTemplate.tsx
: default themenext.config.mjs
: Next.js configuration.env
: default environment variables
You have access to the whole code source if you need further customization. The provided code is only example for you to start your project. The sky is the limit ð.
Commit Message Format
The project enforces Conventional Commits specification. This means that all your commit messages must be formatted according to the specification. To help you write commit messages, the project uses Commitizen, an interactive CLI that guides you through the commit process. To use it, run the following command:
npm run commit
One of the benefits of using Conventional Commits is that it allows us to automatically generate a CHANGELOG
file. It also allows us to automatically determine the next version number based on the types of commits that are included in a release.
Testing
All unit tests are located with the source code inside the same directory. So, it makes it easier to find them. The project uses Vitest and React Testing Library for unit testing. You can run the tests with:
npm run test
Integration & E2E Testing
The project uses Playwright for Integration and E2E testing. You can run the tests with:
npx playwright install # Only for the first time in a new environment
npm run test:e2e
In the local environment, visual testing is disabled. The terminal will display the message [percy] Percy is not running, disabling snapshots.
. By default, the visual testing only runs in GitHub Actions.
Enable Edge runtime (optional)
The App Router folder is compatible with the Edge runtime. You can enable it by adding the following lines src/app/layouts.tsx
:
export const runtime = 'edge';
For your information, the database migration is not compatible with the Edge runtime. So, you need to disable the automatic migration in src/libs/DB.ts
:
await migrate(db, { migrationsFolder: './migrations' });
After disabling it, you are required to run the migration manually with:
npm run db:migrate
You also require to run the command each time you want to update the database schema.
Deploy to production
During the build process, the database migration is automatically executed. So, you don't need to run the migration manually. But, in your environment variable, DATABASE_URL
need to be defined.
Then, you can generate a production build with:
$ npm run build
It generates an optimized production build of the boilerplate. For testing the generated build, you can run:
$ npm run start
You also need to defined the environment variables CLERK_SECRET_KEY
using your own key.
The command starts a local server with the production build. Then, you can now open http://localhost:3000 with your favorite browser to see the project.
Error Monitoring
The project uses Sentry to monitor errors. For development environment, you don't need to do anything: Next.js Boilerplate is already configured to use Sentry and Spotlight (Sentry for Development). All errors will be automatically sent to your local Spotlight instance. So, you can try the Sentry experience locally.
For production environment, you need to create a Sentry account and create a new project. Then, in next.config.mjs
, you need to update the org
and project
attribute in withSentryConfig
function. You also need to add your Sentry DSN in sentry.client.config.ts
, sentry.edge.config.ts
and sentry.server.config.ts
.
Code coverage
Next.js Boilerplate relies on Codecov for code coverage reporting solution. To use Codecov, create a Codecov account and connect it to your GitHub account. On your Codecov dashboard, it should display a list of your repositories. Select the repository you want to enable Codecov for and copy the token. Then, in your GitHub Actions, you need to define the CODECOV_TOKEN
environment variable and paste the token you copied.
Be sure to create the CODECOV_TOKEN
as a Github Actions secret, do not paste it directly into your source code.
Logging
The project uses Pino.js for logging. By default, for development environment, the logs are displayed in the console.
For production environment, the project is already integrated with Better Stack to manage and query your logs using SQL. To use Better Stack, you need to create a Better Stack account and create a new source: go to your Better Stack Logs Dashboard > Sources > Connect source. Then, you need to give a name to your source and select Node.js as the platform.
After creating the source, you able to see your source token and copy it. Then, in your environment variabless, you can paste the token in LOGTAIL_SOURCE_TOKEN
variable. Now, all your logs will be automatically sent and ingested by Better Stack.
Checkly monitoring
The project uses Checkly to ensure that your production environment is always up and running. At regular intervals, Checkly runs the tests ending with *.check.spec.ts
extension and notifies you if any of the tests fail. Additionally, you have the flexibility to execute tests across multiple locations to ensure that your application is available worldwide.
To use Checkly, you must first create an account on their website. Once you have an account, you can set the CHECKLY_API_KEY
environment variable in GitHub Actions by generating a new API key in the Checkly Dashboard. Additionally, you will need to define the CHECKLY_ACCOUNT_ID
, which can also be found in your Checkly Dashboard under User Settings > General.
To complete the setup, make sure to update the checkly.config.ts
file with your own email address and production URL.
Useful commands
Bundle Analyzer
Next.js Boilerplate comes with a built-in bundle analyzer. It can be used to analyze the size of your JavaScript bundles. To begin, run the following command:
npm run build-stats
By running the command, it'll automatically open a new browser window with the results.
Database Studio
The project is already configured with Drizzle Studio to explore the database. You can run the following command to open the database studio:
npm run db:studio
Then, you can open https://local.drizzle.studio with your favorite browser to explore your database.
VSCode information (optional)
If you are VSCode users, you can have a better integration with VSCode by installing the suggested extension in .vscode/extension.json
. The starter code comes up with Settings for a seamless integration with VSCode. The Debug configuration is also provided for frontend and backend debugging experience.
With the plugins installed on your VSCode, ESLint and Prettier can automatically fix the code and show you the errors. Same goes for testing, you can install VSCode Vitest extension to automatically run your tests and it also show the code coverage in context.
Pro tips: if you need a project wide type checking with TypeScript, you can run a build with Cmd + Shift + B on Mac.
Contributions
Everyone is welcome to contribute to this project. Feel free to open an issue if you have question or found a bug. Totally open to any suggestions and improvements.
License
Licensed under the MIT License, Copyright © 2024
See LICENSE for more information.
Sponsors
Add your logo here |
Made with ⥠by CreativeDesignsGuru
Top Related Projects
The React Framework
The best way to start a full-stack, typesafe Next.js app
🔋 Next.js + Tailwind CSS + TypeScript starter and boilerplate packed with useful development features
Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
This is a Next.js, Tailwind CSS blogging starter template. Comes out of the box configured with the latest technologies to make technical writing a breeze. Easily configurable and customizable. Perfect as a replacement to existing Jekyll and Hugo individual blogs.
💼 An enterprise-grade Next.js boilerplate for high-performance, maintainable apps. Packed with features like Tailwind CSS, TypeScript, ESLint, Prettier, testing tools, and more to accelerate your development.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot