explainx.ai0k
TrendingAI News TodayPathwaysSkills
Pricing
explainx.ai

Upskill in AI — 16 free pathways, live workshops & bootcamps, and 50+ courses from practitioners. Plus the skills, tools, and MCP servers to practice on.

follow us

follow on google

Add explainx.ai as a preferred source

corporate training

support@explainx.ai

get started

Find your pathTake Free Evaluation

community

Join the community

learn

mind: share how you thinkpathways — start freeworkshopsbootcampscoursescompare Explainxcertificationsmock testsexplainx universitycorporate traininglearn skills & mcp

discover

skillsmcp serversexplainx mcptoolsmdx readeragentsllmsdesignsdictionarypeopleagi trackerfelony benchranks

company

aboutvisionmissionteaminstructorsteach on explainxpartnershipscommunityhackathonscareers

content

daily AI newsstate of AI — live resultsblogreleasespromptsgeneratorsresource libraryfor LLMsexplainx.ai kids

solutions

all solutionsdeveloper upskillingmarketing upskillingproduct manager upskillingleadership upskilling

newsletter · weekly

Get AI news, tools, and insights in your inbox.

supportcontactprivacytermsdata rightshow we create contentsubmission guidelines

© 2026 AISOLO Technologies Pvt Ltd

explainx.ai

On this page

  • What Next.js adds over plain HTML/CSS
  • Prerequisites
  • Step 1: Create your first Next.js project
  • Step 2: Understand the project structure
  • Step 3: Start the development server
  • Step 4: Edit the homepage
  • Step 5: Create a new page
  • Step 6: Add a shared layout
  • Step 7: Server vs Client components
  • Step 8: Fetch data in a server component
  • Step 9: Dynamic routes
  • Useful scripts
  • Deploy to Vercel in 2 minutes
  • How do you debug your first Next.js project?
  • What should happen when the posts API fails?
  • How can you practice routing without adding a database?
  • What should you check before sharing the deployed link?
  • What to build next
← Back to blog

explainx / blog

What is Next.js? How to Install and Build Your First Next.js Project (2026)

Next.js, Beginner Guide, React, Web Development, JavaScript

Next.js explained from scratch: what it is, how to install it, and how to build your first page — step by step. Covers the App Router, file-based routing, and server vs client components. Beginner guide for 2026.

Jun 27, 2026·8 min read·Yash Thakker
add explainx.ai
go deep
What is Next.js? How to Install and Build Your First Next.js Project (2026)

Next.js is the most popular framework for building web applications with React. It takes care of routing, page rendering, image optimisation, and deployment — so you can focus on building your product rather than configuring infrastructure.

Weekly digest3.5k readers

Catch up on AI

Curated AI updates on agents, skills, and MCP — delivered to your inbox. Unsubscribe anytime.

This is the website framework behind explainx.ai, Vercel's own site, and thousands of production apps. If you want to build real websites and web apps in 2026, Next.js is the foundation worth learning.

Once the first project structure makes sense, use the full-stack AI chat app guide to connect the App Router to Auth.js, streamed Claude responses, private chat history, and a Vercel deployment.


What Next.js adds over plain HTML/CSS

Next.js install diagram showing a typed terminal command transforming into a stacked project structure

table · 2 cols
Plain HTML/CSSNext.js
One file = one pageAutomatic routing from folder structure
Manual <script> includesComponent system with imports
No built-in data fetchingasync server components fetch data directly
Static files onlyMix of static pages, server-rendered pages, and APIs
Manual image handling<Image> component with auto-optimisation
Deploy manuallygit push → deploy to Vercel automatically

Prerequisites

You need Node.js installed. Check:

bash
node --version

If you get command not found, follow the Node.js install guide first. Use a Node.js version supported by the Next.js release you install. Check the current installation prerequisites before using create-next-app@latest.


Step 1: Create your first Next.js project

Next.js provides a CLI tool called create-next-app that scaffolds everything for you. Run:

bash
npx create-next-app@latest my-nextjs-app

You'll be asked several questions. For a beginner setup, answer like this:

snippet
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 your code inside a `src/` directory? → No
Would you like to use App Router? → Yes
Would you like to use Turbopack for next dev? → Yes
Would you like to customise the import alias? → No

This creates a folder called my-nextjs-app with everything configured.

Navigate into it:

bash
cd my-nextjs-app

Step 2: Understand the project structure

snippet
my-nextjs-app/
├── app/                 ← All your pages and layouts live here
│   ├── layout.tsx       ← Root layout — wraps every page
│   ├── page.tsx         ← Your homepage (/)
│   └── globals.css      ← Global styles
├── public/              ← Static files (images, fonts, etc.)
├── next.config.ts       ← Next.js configuration
├── package.json         ← Dependencies and scripts
└── tsconfig.json        ← TypeScript configuration

The app/ directory is the most important. A folder becomes a browsable page route when it contains a page.tsx file. Other folders can organize components without creating a page:

snippet
app/page.tsx         → /
app/about/page.tsx   → /about
app/blog/page.tsx    → /blog
app/blog/[slug]/page.tsx → /blog/any-slug-here

Step 3: Start the development server

bash
npm run dev

Open your browser to http://localhost:3000. You'll see the default Next.js welcome page.

Leave this running. Every time you save a file, the page updates in the browser automatically — this is called hot reload.


Step 4: Edit the homepage

Open app/page.tsx in your editor. You'll see the default starter code. Delete everything inside the file and replace it with:

tsx
export default function HomePage() {
  return (
    <main className="min-h-screen flex flex-col items-center justify-center p-8">
      <h1 className="text-4xl font-bold mb-4">Hello, Next.js</h1>
      <p className="text-gray-500 text-lg">My first Next.js page.</p>
    </main>
  );
}

Save the file. Your browser updates instantly.

What's happening here:

  • export default function HomePage() — every page.tsx must export a default function
  • The function returns JSX — HTML-like syntax with JavaScript inside curly braces
  • The className attributes are Tailwind CSS utility classes

Step 5: Create a new page

Add an About page. Create a new folder and file:

bash
mkdir app/about

Create app/about/page.tsx:

tsx
export default function AboutPage() {
  return (
    <main className="min-h-screen p-8 max-w-2xl mx-auto">
      <h1 className="text-3xl font-bold mb-6">About</h1>
      <p className="text-gray-600 leading-relaxed">
        This is my first Next.js project. I built it by following a beginner guide.
      </p>
    </main>
  );
}

Go to http://localhost:3000/about — the page is live. No configuration needed. The folder name becomes the URL.


Step 6: Add a shared layout

The app/layout.tsx file wraps every page in your app. This is where you put things that appear on every page — navigation, footers, font loading, meta tags.

Open app/layout.tsx. Add a simple nav:

tsx
import type { Metadata } from "next";
import "./globals.css";

export const metadata: Metadata = {
  title: "My Next.js App",
  description: "My first Next.js project",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <nav className="border-b px-8 py-4 flex gap-6">
          <a href="/" className="font-semibold hover:text-blue-600">Home</a>
          <a href="/about" className="font-semibold hover:text-blue-600">About</a>
        </nav>
        {children}
      </body>
    </html>
  );
}

Now every page has the nav bar — and you only wrote it once.


Step 7: Server vs Client components

This is the most important concept in the App Router.

Server components (the default) — render on the server. Can fetch data directly. Cannot use browser APIs (window, document) or React hooks (useState, useEffect).

Client components — support browser interactivity and React hooks. Their initial HTML can also be rendered on the server; they do not run exclusively in the browser. Add "use client" at the top of the file.

Rule of thumb: Start with server components (the default). Only add "use client" when you need interactivity or browser APIs.

Example of a client component — a counter button:

Create app/components/Counter.tsx:

tsx
"use client";

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button
      onClick={() => setCount(count + 1)}
      className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
    >
      Clicked {count} times
    </button>
  );
}

Now use it in your homepage (a server component):

tsx
import Counter from "./components/Counter";

export default function HomePage() {
  return (
    <main className="min-h-screen flex flex-col items-center justify-center p-8 gap-6">
      <h1 className="text-4xl font-bold">Hello, Next.js</h1>
      <Counter />
    </main>
  );
}

The homepage stays a server component. The Counter is a client component embedded inside it. This is the standard pattern.


Step 8: Fetch data in a server component

Server components can async/await directly — no useEffect needed:

Create app/posts/page.tsx:

tsx
async function getPosts() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
  return res.json();
}

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

  return (
    <main className="p-8 max-w-2xl mx-auto">
      <h1 className="text-3xl font-bold mb-6">Posts</h1>
      <ul className="space-y-4">
        {posts.map((post: { id: number; title: string; body: string }) => (
          <li key={post.id} className="border rounded p-4">
            <h2 className="font-semibold mb-1">{post.title}</h2>
            <p className="text-gray-500 text-sm">{post.body}</p>
          </li>
        ))}
      </ul>
    </main>
  );
}

Visit http://localhost:3000/posts. It fetches and displays real data — without a client-side fetch in this example. A production page still needs deliberate loading and error handling. The data is fetched on the server and the HTML arrives ready.


Step 9: Dynamic routes

Create a route that accepts a variable segment — like a blog post URL.

Create app/posts/[id]/page.tsx:

tsx
async function getPost(id: string) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
  return res.json();
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const post = await getPost(id);

  return (
    <main className="p-8 max-w-2xl mx-auto">
      <h1 className="text-2xl font-bold mb-4">{post.title}</h1>
      <p className="text-gray-600">{post.body}</p>
    </main>
  );
}

Visit http://localhost:3000/posts/1, then /posts/2, then /posts/5. Same file, different data — the [id] folder makes the segment dynamic.


Useful scripts

bash
npm run dev        # Start development server (with hot reload)
npm run build      # Build for production
npm run start      # Start the production server
npm run lint       # Check for code issues

Deploy to Vercel in 2 minutes

Vercel is made by the same team that makes Next.js. Deploying takes two steps:

  1. Push your project to GitHub (see the Git guide)
  2. Go to vercel.com, click Add New Project, import your GitHub repo

Vercel detects Next.js automatically. Every git push deploys a new version. Your site gets a free .vercel.app URL instantly.


How do you debug your first Next.js project?

Separate the terminal, server, and browser before changing code. A command that cannot find the project directory is a shell problem. A server that exits while compiling a page is a project problem. A browser that opens successfully but shows an empty list may be a data or rendering problem. Each needs different evidence.

First confirm that the terminal is in the folder containing your package file. Read the scripts before running them; generated starters can change their tooling over time. When the development server starts, use the address it prints. If another application already occupies the usual port, the new server may choose a different one, and refreshing an old tab will show the wrong project.

Next read the first useful error rather than the last stack frame. A misspelled import often produces several downstream messages. Fix the missing module or wrong path, save, and wait for a fresh compilation result. Avoid reinstalling all dependencies before establishing what the error actually says: that can change the project while leaving the original typo untouched.

A “window is not defined” message means browser-dependent code is running in a context without that browser object. Inspect the component boundary and the location of the access. Adding a client directive is relevant for an interactive component, but reading browser state during render can still need careful handling. Consult the official server and client component examples before moving an entire page into the client bundle.

What should happen when the posts API fails?

The demonstration endpoint makes the happy path easy to understand. A real page also needs to handle a rejected request, an unexpected response shape, and an identifier that has no corresponding record. Successful JSON parsing does not prove that the returned value is the post your page expects.

Check the response status before rendering its contents. Decide whether a missing record should show a not-found page, while a temporary provider failure should show a recoverable error. Those outcomes communicate different things to the visitor. Keep private provider details in server logs rather than displaying a raw error containing internal URLs or tokens.

Add a loading state for work that takes long enough for the visitor to notice. The point is to communicate that the page is responding, without promising a precise completion time. Try your page with the network deliberately slowed and with the endpoint made unavailable in a controlled development setup. Record what the visitor actually sees.

Keep API secrets on the server. A public environment-variable prefix is intended for values that can be delivered to the browser; it is not a way to hide a key. If a client component needs to trigger a privileged operation, design a server boundary with authentication and validation rather than passing the credential as a prop.

How can you practice routing without adding a database?

Build a small reading list with a few local records. Give each record an identifier, a title, a short description, and a category. Render the list on one page and the matching record on a dynamic route. This exercises the same routing ideas as the API example while keeping failures easy to inspect.

Add navigation between the pages and confirm that the active record matches the URL. Type an unknown identifier manually and decide how it should behave. Then add an interactive favorite button as a small client component. Its state may reset on refresh unless you intentionally persist it; explain that limitation in the interface rather than treating temporary state as stored data.

Ask an AI assistant to review this exercise against a specific checklist: correct route names, meaningful headings, keyboard-accessible navigation, and a sensible missing-record response. Read its proposed changes before applying them. A vibe coding workflow works better when you can explain the small project yourself.

What should you check before sharing the deployed link?

Run the production build in addition to opening the development page. Development mode can conceal problems that appear during prerendering or production compilation. After deployment, open the list page and a detail page directly in a fresh browser session; navigation from the homepage alone does not exercise direct route loading.

Check a narrow mobile viewport, keyboard focus, and the page title. Confirm that links still point to your deployed host and that no example address was left in the application. The deployment guide covers the environment boundary, while the HTML guide helps you understand the markup your components produce.

Treat the first project as a learning artifact. A working reading list demonstrates routing and rendering; it does not establish readiness for payments, user accounts, or private data. Add those capabilities one at a time, with a clear check for each new behavior.

What to build next

  • Add a contact form using a Next.js API route (app/api/contact/route.ts)
  • Connect a database using Prisma + PostgreSQL (or Supabase for a hosted option)
  • Add authentication with NextAuth.js or Clerk
  • Deploy to a custom domain on Vercel

explainx.ai is built with Next.js, Prisma, and Tailwind — the same stack you just set up.

Spotted something out of date? Let us know.
Yash Thakker

Written by

Yash Thakker

Yash is an AI expert with over 300K learners. Join his workshops →

View Yash Thakker in People in AI →

Related posts

Jun 27, 2026

What is a Chrome Extension? How to Build Your First One (2026 Beginner Guide)

Chrome extensions are small apps that run inside your browser and can modify any web page. This guide walks you through exactly what they are, how the three required files fit together, and a complete working example you can load into Chrome in under ten minutes.

Apr 24, 2026

React Server Components: Complete Guide to RSC in 2026

React Server Components have become the default architecture for modern React applications in 2026. Learn how RSC enables zero-bundle-size components, automatic code splitting, and seamless server-client integration for better performance and developer experience.

Jun 27, 2026

What Are Environments in Software? Production, Staging, and Development Explained (2026)

Every professional software project runs in three separate environments: development on your laptop, staging as a private mirror of production, and production where real users live. Understanding why — and how environment variables tie it together — is one of the most practical things a beginner can learn.