DevLog

Building a Modern Web App with Next.js

A comprehensive guide to setting up a production-ready Next.js application with best practices.

Tramdev
15 tháng 1, 2025
Frontend
#Next.js#React#Web Development
Building a Modern Web App with Next.js

Building a Modern Web App with Next.js

Setting up a modern web application requires careful consideration of architecture, performance, and developer experience. In this post, we'll explore how to build a production-ready Next.js application following best practices.

Project Setup

First, let's create a new Next.js project with TypeScript:

npx create-next-app@latest my-app --typescript --tailwind --eslint --app
cd my-app

Key Features to Implement

1. App Router Structure

Next.js 13+ App Router provides a more intuitive way to organize your application:

app/
├── layout.tsx
├── page.tsx
├── blog/
│   ├── page.tsx
│   └── [slug]/
│       └── page.tsx
└── api/
    └── posts/
        └── route.ts

2. Component Architecture

Organize your components following atomic design principles:

// components/ui/Button.tsx
interface ButtonProps {
  children: React.ReactNode;
  variant?: 'primary' | 'secondary';
  onClick?: () => void;
}

export function Button({ children, variant = 'primary', onClick }: ButtonProps) {
  return (
    <button
      className={`px-4 py-2 rounded-md font-medium ${
        variant === 'primary'
          ? 'bg-blue-600 text-white hover:bg-blue-700'
          : 'bg-gray-200 text-gray-900 hover:bg-gray-300'
      }`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

3. Data Fetching Patterns

Use Server Components for data fetching to improve performance:

// app/blog/page.tsx
import { getPosts } from '@/lib/posts';

export default async function BlogPage() {
  const posts = await getPosts();

  return (
    <div className="grid gap-6">
      {posts.map((post) => (
        <article key={post.slug} className="border rounded-lg p-6">
          <h2 className="text-2xl font-bold mb-2">{post.title}</h2>
          <p className="text-gray-600 mb-4">{post.excerpt}</p>
          <time className="text-sm text-gray-500">{post.date}</time>
        </article>
      ))}
    </div>
  );
}

Performance Optimization

Image Optimization

Use Next.js Image component for automatic optimization:

import Image from 'next/image';

export function OptimizedImage({ src, alt }: { src: string; alt: string }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={800}
      height={400}
      className="rounded-lg"
      priority
    />
  );
}

Bundle Analysis

Monitor your bundle size with built-in tools:

npm run build
npm run analyze

Deployment

Deploy to Vercel for optimal Next.js performance:

npm i -g vercel
vercel --prod

This setup provides a solid foundation for building modern web applications with excellent performance and developer experience.