Logo
Next.js Pages Template
Published on

Next.js Pages Template

Authors
  • Name
    Dana Davis
    Twitter

Building the Perfect Next.js Starter Template: My Journey to Developer Happiness

You know that feeling when you start a new project and spend the first three hours just setting up the same boilerplate code you've written a dozen times before? Yeah, I got tired of that too. That's what led me to create my ultimate Next.js starter template – a comprehensive foundation that gets you from idea to deployment faster than you can say "npx create-next-app."

The Problem: Setup Fatigue

Every time I started a new project, I found myself going through the same tedious setup routine:

  • Install Next.js ✓
  • Add TypeScript configuration ✓
  • Set up Tailwind CSS ✓
  • Configure a UI component library ✓
  • Add database integration ✓
  • Set up PWA capabilities ✓
  • Configure theme switching ✓
  • Add animations ✓

By the time I finished all this setup, I'd already lost momentum on the actual project! I realized I needed a battle-tested template that included everything I typically reach for, pre-configured and ready to go.

My Philosophy: Developer Experience First

When building this template, I had a few core principles:

Start Building Immediately: No configuration paralysis – just clone and code Production Ready: Not just a toy example, but something you can actually ship Batteries Included: Common features baked in, not bolted on later Modern Best Practices: Using the latest and greatest web standards

The Tech Stack: My Dream Team

After building countless Next.js projects, I've settled on what I consider the perfect stack for most web applications:

const myDreamStack = 

Why These Specific Choices?

Next.js 13 with Pages Router: I chose the Pages Router over the newer App Router because, honestly, it's more stable and I know it inside and out. Sometimes the tried-and-true approach wins over bleeding edge.

NextUI v2: After trying countless UI libraries, NextUI hit the sweet spot. It's like having a professional designer on your team – beautiful components that just work out of the box, with accessibility baked in.

MongoDB: For most projects, the flexibility of a document database beats the rigidity of SQL. Plus, MongoDB Atlas makes deployment a breeze.

PWA Capabilities: In 2024, if your web app doesn't feel like a native app, you're behind. Next-PWA makes this incredibly easy to implement.

Building the Foundation: Key Features

The UI System That Actually Works

One of my biggest wins with this template was nailing the design system. Using NextUI means you get beautiful components without spending weeks on design:

// Look how clean this is!
import  from '@nextui-org/react'

const ExampleComponent = () => 

The best part? These components are accessible by default, responsive out of the box, and themeable without losing your sanity.

Database Integration Done Right

Setting up MongoDB connection in Next.js can be tricky if you don't handle connection pooling properly. I've burned myself on this before, so the template includes a bulletproof database setup:

// No more connection pool exhaustion!
import  from 'mongodb'

let cachedClient = null
let cachedDb = null

export async function connectToDatabase() 
  }

  const client = await MongoClient.connect(process.env.MONGODB_URI)
  const db = await client.db(process.env.MONGODB_DB_NAME)

  cachedClient = client
  cachedDb = db

  return 
}

This approach reuses connections across serverless function invocations, which is crucial for performance in production.

PWA Magic Without the Complexity

Making a web app feel native used to be a nightmare of service worker configuration and manifest files. With Next-PWA, it's embarrassingly simple:

// next.config.js - that's it!
const withPWA = require('next-pwa')()

module.exports = withPWA()

Your app now works offline, can be installed on devices, and supports push notifications. It's like magic, but the kind that actually works in production.

Animations That Don't Suck

Framer Motion integration means you can add delightful animations without turning your code into spaghetti:

// Smooth, professional animations with minimal code
import  from 'framer-motion'

const AnimatedCard = () => }
      animate=}
      transition=}
      className="bg-white rounded-lg shadow-lg p-6"
    >
      ### This feels so smooth!

      Your users will love the polish

    
  )
}

The Project Structure: Organization That Makes Sense

One thing I learned from working on teams is that a good folder structure can make or break a project. Here's how I organized everything:

nextjs-pages-template/
├── components/           # All your reusable UI magic
│   ├── ui/              # Base components (buttons, inputs, etc.)
│   ├── layout/          # Layout components (headers, footers)
│   └── common/          # Shared utility components
├── lib/                 # The utility belt
│   ├── db.ts           # Database connection helpers
│   ├── auth.ts         # Authentication utilities
│   └── utils.ts        # General helper functions
├── pages/              # Next.js pages (the bread and butter)
│   ├── api/            # Backend API routes
│   └── index.tsx       # Your homepage
├── styles/             # Global styles and CSS
└── types/              # TypeScript definitions
    └── database.ts     # Keep your types organized

This structure scales beautifully from small projects to large applications. I've used variations of this on projects with hundreds of components, and it still makes sense.

Dark Mode Done Right

Getting dark mode to work properly across server-side rendering, local storage, and system preferences is trickier than it should be. This template handles all the edge cases:

// Theme provider setup that actually works
import  from 'next-themes'
import  from '@nextui-org/react'

export default function App()  />
      
    
  )
}

No more flash of wrong theme, no more hydration mismatches, no more headaches. It just works.

TypeScript Configuration: Strict but Sensible

I spent way too much time fine-tuning the TypeScript configuration so you don't have to. It's strict enough to catch real bugs but not so pedantic that it gets in your way:


  }
}

The path mapping means you can write import Button from '@/components/ui/Button' instead of import Button from '../../../components/ui/Button'. Your future self will thank you.

Performance: Built for Speed

Optimization Lessons Learned

After shipping dozens of Next.js projects, I've learned some hard lessons about performance:

Bundle Analysis: The template includes bundle analysis tools so you can catch bloated dependencies before they reach production.

Image Optimization: Next.js Image component is configured and ready to go – no more manually optimizing images.

Code Splitting: Automatic code splitting ensures users only download what they need.

Here's a performance monitoring setup I include:

// Keep an eye on your Core Web Vitals
const performanceConfig = ,
  thresholds: ,
}

Getting Started: From Zero to Hero in Minutes

The best part about this template? Getting started is ridiculously easy:

# Clone and you're 90% done
git clone https://github.com/xi-Rick/nextjs-pages-template.git my-awesome-project
cd my-awesome-project
npm install

# Add your MongoDB connection
cp .env.local.example .env.local
# Edit .env.local with your database URL

# Start building!
npm run dev

Within minutes, you have:

  • A beautiful, responsive UI ✓
  • Database connectivity ✓
  • PWA capabilities ✓
  • Dark mode ✓
  • TypeScript configured ✓
  • Animations ready ✓

Real-World Usage: What I've Built With This

Since creating this template, I've used it to build:

SaaS Dashboard: A customer analytics platform with real-time charts and user management E-commerce Store: Online marketplace with product catalogs and payment integration Portfolio Site: Personal portfolio with dynamic content management Blog Platform: Content management system with markdown support

Each project started with this template and was production-ready within days, not weeks.

Security and Best Practices Baked In

I've made all the security mistakes so you don't have to:

Environment Variables: Proper handling of secrets and configuration Input Validation: Built-in sanitization to prevent common attacks CORS Configuration: Secure cross-origin resource sharing Database Security: Secure MongoDB connection patterns

The template follows Next.js security best practices and includes safeguards against common vulnerabilities.

What's Next: Future Improvements

I'm constantly improving this template based on real-world usage:

Planned Additions

  • NextAuth.js Integration: Complete authentication system with multiple providers
  • Testing Setup: Jest and React Testing Library configured and ready
  • Docker Support: Containerization for consistent deployments
  • CI/CD Pipeline: GitHub Actions workflow for automated testing and deployment

Community Requests

Based on feedback from developers using the template:

  • Storybook Integration: Component documentation and testing
  • API Documentation: Swagger/OpenAPI generation
  • Internationalization: Multi-language support setup
  • Analytics Integration: Privacy-friendly analytics configuration

Lessons Learned Building This Template

The MongoDB Connection Pool Trap

Early versions of this template had a nasty bug where MongoDB connections would leak in serverless environments. I learned the hard way that you need to cache connections properly in Next.js API routes. The solution I implemented has been battle-tested across multiple production apps.

NextUI vs. Other Libraries

I tried Material-UI, Chakra UI, and Ant Design before settling on NextUI. Here's why NextUI won:

  • Accessibility is built-in, not an afterthought
  • Bundle size is reasonable – some libraries are just bloated
  • TypeScript support is excellent – proper types, not just any everywhere
  • Customization is actually possible without fighting the library

PWA Gotchas

Making PWAs work properly across all browsers and devices is harder than the tutorials make it seem. I've included workarounds for:

  • iOS Safari's quirky PWA behavior
  • Service worker update strategies that don't break users' experience
  • Offline fallbacks that actually work

Why This Template Exists

There are tons of Next.js starters out there, so why did I create another one? Most templates fall into one of these categories:

Too Basic: Just Next.js + Tailwind with maybe TypeScript Too Opinionated: Locked into specific services or patterns you might not want Too Experimental: Using bleeding-edge features that aren't production-ready Too Enterprise: Over-engineered for simple projects

My template hits the sweet spot: comprehensive but not overwhelming, modern but stable, opinionated but flexible.

Community Impact and Feedback

Since releasing this template, I've received amazing feedback from developers:

Success Stories

  • A startup used it to build their MVP in two weeks instead of two months
  • A freelancer saved 40+ hours per project by starting with this template
  • A student was able to build their final project without getting lost in configuration

Common Customizations

People often customize the template by:

  • Adding different authentication providers
  • Swapping MongoDB for PostgreSQL or Supabase
  • Including specific deployment configurations
  • Adding industry-specific components

The Technical Deep Dive

Why Pages Router Over App Router?

This is probably the most controversial choice I made. The App Router is the future, but:

  • Stability: Pages Router is battle-tested and predictable
  • Community: More examples, tutorials, and Stack Overflow answers
  • Migration Path: You can migrate to App Router later when you need its features

For most projects, Pages Router is still the right choice in 2024.

Performance Monitoring Setup

I include performance monitoring because Core Web Vitals actually matter for user experience and SEO:

// Real-world performance tracking
export function reportWebVitals(metric) )
  }
}

Database Best Practices

The MongoDB setup includes several production-ready patterns:

  • Connection pooling to prevent connection exhaustion
  • Retry logic for transient network errors
  • Proper error handling and logging
  • Schema validation at the application level

Conclusion: Start Building, Not Configuring

Building this template has been one of my most rewarding projects. Not because of the code (though I'm proud of that), but because of the time it's saved other developers.

Every hour you spend configuring build tools is an hour you're not spending on your actual product. This template gets you past the boring setup phase and into the fun part: building something users will love.

Whether you're a solo developer trying to ship quickly, a startup needing to validate an idea, or a team wanting to standardize on a solid foundation, this template has you covered.

Check out the demo to see it in action, or jump straight to the GitHub repo to start building.

Now stop reading about templates and go build something awesome! 🚀


Want to contribute or have suggestions? The template is open source and I welcome contributions. Found it useful? Give it a star on GitHub – it helps other developers find it!

Enjoyed this project?

If you have any questions, feedback, or just want to say hi, feel free to share on Twitter