404 Not Found

404 Not Found


nginx

Environment Setup & Project Structure

Setting up a Next.js 16 development environment is like renovating a new house—the scaffolding helps you lay the foundation, and the rest of the structure, layout, and configuration can all be adjusted as needed.

1. What You'll Learn


2. A True Story of a Front-End Newbie

(1) Pain Point: It takes three days to set up the development environment

Charlie is a front-end beginner who has just learned React and wants to try Next.js. He opens the official documentation and, faced with a dozen configuration options and three different scaffolding commands, has no idea which one to choose:

"With create-react-app, I can get it running with just one command. But with Next.js, do I need the src/ directory? Do I need TypeScript? Do I need ESLint? Do I need Tailwind? Just figuring out these choices took me two days."

He also encountered the following problems:

Issue Symptoms
Trouble Choosing Settings 7 options—not sure which ones to enable
I don't understand the directory structure The roles of app/, public/, and styles/ are unclear
Hot reload is too slow With Webpack, I have to wait 1–2 seconds every time I save
No assistance in VS Code No hints, no autocomplete—it’s like writing in Notepad

(2) The create-next-app Solution

Use the create-next-app interactive scaffolding to generate a best-practice project structure with a single click.

BASH
# An interactive command,Just answer a few simple questions
npx create-next-app@latest taskflow --ts --tailwind --app --src-dir --import-alias "@/*"

(3) Revenue

Dimension Before (manual setup) After (create-next-app)
Project Setup Time 2 days of research 3 minutes
HMR Speed 1-2s (Webpack) 3-10ms (Turbopack)
Code Hints None JSX autocomplete + Tailwind class name hints
Understanding the Table of Contents Confusion Organized by function, easy to understand

3. The create-next-app Scaffold

(1) Interactive Creation

BASH
# Run the scaffolding command
npx create-next-app@latest

You'll see the following interactive options:

TEXT
? What is your project named?  taskflow
? Would you like to use TypeScript?  Yes / No
? Would you like to use ESLint?  Yes / No
? Would you like to use Tailwind CSS?  Yes / No
? Would you like to use `src/` directory?  Yes / No
? Would you like to use App Router? (recommended)  Yes / No
? Would you like to customize the import alias (`@/*` by default)?  No
BASH
# Recommended Options for This Course(All projects use this set)
npx create-next-app@latest taskflow ^
  --typescript ^
  --eslint ^
  --tailwind ^
  --src-dir ^
  --app ^
  --import-alias "@/*"
Option Value Reason
TypeScript Yes Standard for production-level projects, type-safe
ESLint Yes Code quality assurance
Tailwind CSS Yes Used throughout this tutorial
src/ directory Yes Separation of code and configuration
App Router Yes Next.js 16 default routing system
Import Alias @/* Concise import path

▶ Example: Complete Process for Creating Scaffolding

BASH
# ============================================
# Create a file named shophub New Project
# ============================================

npx create-next-app@latest shophub --ts --tailwind --app --src-dir

# Console Output
cd shophub
npm run dev

Output:

TEXT
Creating a new Next.js project in C:\Users\Charlie\shophub.

✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … Yes
✔ Would you like to use Tailwind CSS? … Yes
✔ Would you like to use `src/` directory? … Yes
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the import alias? … @/*

Success! Created shophub at shophub
Inside that directory, you can run:
  npm run dev       # Start the development server
  npm run build     # Build the production version
  npm start         # Start the production server

(3) Project Structure Generated by Scaffold

100%
graph TB
    A[shophub/] --> B[src/]
    A --> C[public/]
    A --> D[Other Profiles]
    B --> E[app/]
    B --> F[app/globals.css]
    B --> G[app/layout.tsx]
    B --> H[app/page.tsx]
    C --> I[favicon.ico]
    C --> J[Images and other static resources]
    D --> K[package.json]
    D --> L[tsconfig.json]
    D --> M[next.config.ts]
    D --> N[tailwind.config.ts]
    D --> O[postcss.config.mjs]

    style B fill:#d4edda
    style C fill:#f8d7da
    style E fill:#cce5ff

4. Detailed Explanation of the Project Directory Structure

(1) src/app/ — The Core of Your Application Code

File Purpose Required?
layout.tsx Root layout (encloses all pages) ✅ Required
page.tsx Home (Routed via /) ✅ Required
globals.css Global Styles Recommended
favicon.ico Website Icon Optional

▶ Example: The default app/page.tsx file

Output:

TEXT
Diagram: shophub/; src/; public/; Other Profiles; app/; app/globals.css.
TSX
// ============================================
// create-next-app Default Home Page
// ============================================

import Image from "next/image";

export default function Home() {
  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
        <Image
          className="dark:invert"
          src="/next.svg"
          alt="Next.js logo"
          width={180}
          height={38}
          priority
        />
        <ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
          <li className="mb-2">
            Get started by editing{" "}
            <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
              src/app/page.tsx
            </code>
          </li>
          <li>Save and see your changes instantly.</li>
        </ol>
        <div className="flex gap-4 items-center flex-col sm:flex-row">
          <a className="...">Deploy now</a>
          <a className="...">Read our docs</a>
        </div>
      </main>
    </div>
  );
}

Output:

TEXT
Renders: Home component with described UI elements.

Output:

TEXT
Open in a browser http://localhost:3000,As you can see:
- Next.js Official Logo
- "Get started by editing src/app/page.tsx" Presentation
- "Deploy now" and "Read our docs" two links
- Dark/Light Theme Responsive

(2) public/ — Static Resources Directory

TEXT
public/
├── favicon.ico      # Browser Tab Icons
├── file.svg         # File Type Icons
├── globe.svg        # Earth icon
├── next.svg         # Next.js Logo
├── vercel.svg       # Vercel Logo
└── window.svg       # Window Icon

All files located under public/ can be accessed directly via the / root path:

TSX
// Reference in a component public Images in the directory
<img src="/logo.png" alt="Logo" />
// or use next/image Components
import Image from 'next/image';
<Image src="/logo.png" alt="Logo" width={200} height={100} />

(3) Root Configuration File

File Purpose Frequency of Modification
next.config.ts Next.js compile-time configuration Low (configured when the project starts)
tsconfig.json TypeScript compilation options Low
tailwind.config.ts Tailwind CSS Themes/Plugins Chinese (Add Custom Colors)
postcss.config.mjs PostCSS plugin configuration Very low
package.json Project Dependencies + NPM Scripts Medium (when adding dependencies)
.eslintrc.json ESLint rule Low

▶ Example: Configuring next.config.ts

Output:

TEXT
TypeScript compiled.
TS
// ============================================
// next.config.ts — Next.js Compile-Time Configuration
// ============================================

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  // Allow external images to be loaded from specified domains
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "fakestoreapi.com",
      },
      {
        protocol: "https",
        hostname: "images.unsplash.com",
      },
    ],
  },

  // Enable PPR(Partial Prerendering)
  experimental: {
    ppr: true,
  },
};

export default nextConfig;

Output:

TEXT
Component renders its UI.

Output:

TEXT
After the configuration takes effect:
1. <Image> components can load images from fakestoreapi.com and images.unsplash.com
2. On the page Suspense Content after the boundary will use PPR Streaming Rendering
3. Run Again npm run dev The configuration will take effect afterward

5. Development Servers and Turbopack

(1) Start the development server

BASH
# Go to the project directory
cd shophub

# Start the development server
npm run dev

▶ Example: Turbopack Live Hot Reload Experience

Output:

TEXT
  ▲ Next.js 16.0.0
  - Local:        http://localhost:3000
  - Environments: .env.local

 ✓ Starting...
 ✓ Ready in 1.2s
BASH
# ============================================
# Start the development server,Observation Turbopack At top speed HMR
# ============================================

npm run dev

# Console Output
> shophub@0.1.0 dev
> next dev

  ▲  ▲
  ▲  Next.js 16.2
  ▲  - Local: http://localhost:3000
  ▲  - Turbopack: ✓ loaded in 742ms

✔ Compiled /src/app/page.tsx in 142ms (modules: 523)

Now edit src/app/page.tsx to change any text, then save:

TEXT
✔ Updated /src/app/page.tsx in 4ms    ← 4 milliseconds!Updates almost instantly

Output:

TEXT
  ▲ Next.js 16.2
  - Local: http://localhost:3000
  - Turbopack: ✓ loaded in 742ms

✔ Compiled /src/app/page.tsx in 142ms (modules: 523)
✔ Updated /src/app/page.tsx in 4ms    ← 4 milliseconds! Updates almost instantly

Compared to Webpack:

Operation Webpack (v15) Turbopack (v16) Performance Improvement
Cold Start 5–10 s 0.7–1.2 s 8x
Single-file hot reload 50–200 ms 2–10 ms 20x
Large Project Builds Baseline 10x Faster 10x

(2) npm run build Production Build

BASH
# Build the production version
npm run build

Output:

TEXT
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (5/5)
✓ Collecting build traces
✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ○ /                                    5.1 kB          89 kB
├ ○ /_not-found                          152 B          84.1 kB
└ λ /api/hello                           0 B            84.1 kB
+ First Load JS shared by all            84.1 kB
  ├ chunks/main-app                      ...
  └ chunks/webpack                       ...

○  (Static)  Static Generation(SSG)
λ  (Dynamic) Dynamic Rendering(SSR)

▶ Example: "npm run build" displays the route type

Output:

TEXT
(See output above)
BASH
# ============================================
# Interpreting Production Build Output
# ============================================

# Suppose two pages have been created:
# app/about/page.tsx and app/dashboard/page.tsx
# Among them dashboard Used cookies() Dynamic Functions

npm run build

# Meaning of Symbols in the Output:
○  /              # Static Page(No dynamic functions)
○  /about         # Static Page
λ  /dashboard     # Dynamic Pages(Used dynamic API)
○  /_not-found    # 404 Page

Output:

TEXT
Route (app)                              Size     First Load JS
┌ ○ /                                    5.1 kB          89 kB
├ ○ /about                               3.2 kB          87 kB
├ λ /dashboard                           6.8 kB          92 kB
└ ○ /_not-found                          152 B          84.1 kB

Output:

TEXT
Route (app)                              Size     First Load JS
┌ ○ /                                    5.1 kB          89 kB
├ ○ /about                               3.2 kB          87 kB
├ λ /dashboard                           6.8 kB          92 kB
└ ○ /_not-found                          152 B          84.1 kB

○  (Static)  Static Generation(SSG)
λ  (Dynamic) Dynamic Rendering(SSR)

(3) npm start Production Server

BASH
# Start the production server after deployment
npm run build
npm start
💡 Tip: npm start must be run after npm run build; it launches the optimized production version, not the development version.


6. Understanding the Scripts in package.json

(1) List of Default Scripts

JSON
{
  "name": "shophub",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "^16.2.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "@types/react": "^19.0.0",
    "@types/react-dom": "^19.0.0",
    "typescript": "^5.7.0",
    "tailwindcss": "^4.0.0",
    "eslint": "^9.0.0",
    "@eslint/eslintrc": "^3.0.0"
  }
}
Script Command Purpose
npm run dev next dev Start the development server (Turbopack)
npm run build next build Production Build
npm start next start Start Production Server
npm run lint next lint Code Style Check

▶ Example: Adding a Custom Script

Output:

TEXT
JSON structure with scripts (dev, build, start, lint, type-check, format, preview) and their corresponding CLI commands.
JSON
// ============================================
// Add commonly used custom scripts in package.json
// ============================================

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "type-check": "tsc --noEmit",
    "format": "prettier --write .",
    "preview": "npm run build && npm start"
  }
}

Output:

TEXT
npm run type-check   → Run TypeScript Type Checking(Do not output a file)
npm run format       → Format all code with Prettier
npm run preview      → Build first, then start the production server(Done with a single command)

Output:

TEXT
npm run type-check   → Run TypeScript Type Checking (no files output)
npm run format       → Format all code with Prettier
npm run preview      → Build first, then start the production server (single command)

(1) Core Plugins

Plugin Name Purpose Number of Installs
Tailwind CSS IntelliSense Tailwind class name autocomplete + hover preview 10M+
ES7+ React/Redux/React-Native snippets JSX snippets (rafce → component template) 8M+
Prettier - Code Formatter Automatic code formatting 40M+
Error Lens Inline error messages 5M+
GitLens Git History Visualization 15M+

8. Complete Example: Building a TaskFlow Project from Scratch

BASH
# ============================================
# Comprehensive Example:Build a Complete System from Scratch Next.js 16 Project
# TaskFlow — Project Collaboration Management Platform
# ============================================

# 1. Create a Project
npx create-next-app@latest taskflow ^
  --typescript ^
  --eslint ^
  --tailwind ^
  --src-dir ^
  --app ^
  --import-alias "@/*"

# 2. Go to the project directory
cd taskflow

# 3. View Directory Structure
tree . /F | findstr /r "^.*src" > nul && dir /s /b src

# 4. Start the development server
npm run dev

# 5. In another terminal,Add Recommended VS Code Layout
mkdir .vscode
JSON
// .vscode/settings.json — Project-Level Configuration
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "typescript.preferences.importModuleSpecifier": "non-relative"
}
TSX
// src/app/page.tsx — Change the homepage to TaskFlow Welcome Page
import Link from "next/link";

export default function Home() {
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      <div className="container mx-auto px-4 py-16 text-center">
        <h1 className="text-5xl font-bold text-gray-900 mb-4">
          TaskFlow
        </h1>
        <p className="text-xl text-gray-600 mb-8 max-w-2xl mx-auto">
          A collaborative project management platform built with Next.js 16.
          Plan, track, and deliver projects together.
        </p>
        <div className="flex gap-4 justify-center">
          <Link
            href="/login"
            className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Get Started
          </Link>
          <Link
            href="/about"
            className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            Learn More
          </Link>
        </div>
        <div className="mt-16 grid grid-cols-3 gap-8 max-w-3xl mx-auto">
          <div className="p-6 bg-white rounded-xl shadow-sm">
            <h3 className="font-bold text-lg">Plan</h3>
            <p className="text-gray-500 mt-2">Create projects and assign tasks</p>
          </div>
          <div className="p-6 bg-white rounded-xl shadow-sm">
            <h3 className="font-bold text-lg">Track</h3>
            <p className="text-gray-500 mt-2">Monitor progress in real-time</p>
          </div>
          <div className="p-6 bg-white rounded-xl shadow-sm">
            <h3 className="font-bold text-lg">Deliver</h3>
            <p className="text-gray-500 mt-2">Ship projects on schedule</p>
          </div>
        </div>
      </div>
    </div>
  );
}

Expected Output:

TEXT
In the browser http://localhost:3000 See:

[TaskFlow Title]
A collaborative project management platform built with Next.js 16.
Plan, track, and deliver projects together.

[Get Started] [Learn More]

┌──────┐  ┌──────┐  ┌──────┐
│ Plan │  │ Track│  │Deliver│
└──────┘  └──────┘  └──────┘

❓ FAQ

Q create-next-app Do I have to include parameters like --ts --tailwind?
A No, you don’t have to. If you don’t include any parameters, it will enter interactive Q&A mode and prompt you for each option one by one. Parameter mode is suitable for CI/CD automation. Both methods yield the same results.
Q src/ What are the benefits of using a directory structure? Is it required?
A src/ A directory structure separates the application code (src/) from the configuration files (root directory), making the project structure clearer. It is not required, but this tutorial recommends using one. You can also choose not to use it, in which case the app/ directory is placed directly in the root directory.
Q Why doesn’t the browser refresh automatically after I change the code?
A Check if you’re using npm run dev (development mode). If you’re using npm start, that’s the production server; you’ll need to switch back to npm run build. Also, Turbopack defaults to hot reloading rather than a full page refresh, so changes to styles or tags should take effect immediately.
Q Can Turbopack be disabled?
A Yes. Set experimental.turbopack: false in next.config.ts to fall back to Webpack. However, Next.js 16 officially recommends using Turbopack, and Webpack support may be removed in future versions.
Q Should .vscode/settings.json be committed to Git?
A It is recommended to commit it. It contains project-wide formatting and code quality configurations, ensuring that all team members—including new developers—use consistent settings. However, .vscode/launch.json (debug configurations) vary from person to person, so they do not need to be committed.
Q What does the ^ prefix before the Next.js version number in package.json mean?
A ^16.2.0 indicates that npm install is allowed to install the latest minor version within the 16.x.x range (e.g., 16.3.0, 16.4.0), but it will not upgrade to 17.0.0. ~16.2.0 only allows 16.2.x. To lock the version, use 16.2.0 without the prefix.

📖 Summary


📝 Exercises

  1. Basic Exercise (⭐): Use create-next-app to create a new project named my-next-app (with TypeScript, Tailwind, and App Router enabled), start the development server, open localhost:3000 in your browser, and take a screenshot of the home page.

  2. Advanced Exercise (⭐⭐): Configure remotePatterns in next.config.ts to allow loading images from images.unsplash.com, then use the <Image> component in app/page.tsx to load an Unsplash image (width 800, height 600).

  3. Challenge (⭐⭐⭐): Create two pages, app/about/page.tsx and app/contact/page.tsx; configure .vscode/settings.json to automatically format when saved; run npm run build to view the and λ symbols in the output; and interpret the type of each route.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏