Learn Next.js Β· 1/15

Next.js Genesis: Setup and "Hello World"

7 min read

Next.js Genesis: Setup and "Hello World"

Welcome, future Next.js navigator! 🧭 You're about to embark on a journey to build powerful, performant, and scalable web applications. But before we launch into the cosmos of code, let's start with the big bang of your Next.js universe: understanding why it exists and how to get your first project off the ground.

1. The "Why" Before the "How": React vs Next.js

So, you've probably heard of React. It's that super popular JavaScript library for building user interfaces. Think of it as a fantastic box of LEGOs. You get all the essential bricks (components), and you can build amazing things with them. However, when you want to build a whole city (a full-fledged web application), you realize you need more than just the bricks. You need roads (routing), a postal service (data fetching), and city planning (an organized structure).

This is where the limitations of using only React can surface. Out of the box, React is a library, not a framework, which means it doesn't provide solutions for everything. For instance:

  • Search Engine Optimization (SEO): Standard React apps render on the client-side (in the browser). This means when a search engine crawler visits your site, it might see a blank page before all the JavaScript loads, which can be bad for your search rankings.
  • Performance: The initial page load can be slow as the browser has to download, parse, and execute a bundle of JavaScript before the user sees anything.
  • Manual Setup: For a production-ready application, you need to set up routing, state management, and build optimizations yourself, which can be complex and time-consuming.

Enter Next.js! 🦸

Next.js is a React framework. It's not here to replace React; it's here to supercharge it. Imagine getting that same box of LEGOs, but now it comes with a pre-built city layout, a high-speed monorail system, and an instant delivery drone network.

Here's how Next.js solves the problems mentioned above:

  • Server-Side Rendering (SSR) and Static Site Generation (SSG): Next.js can pre-render your pages on the server before they even reach the user's browser. This means search engines get a fully-formed HTML page, which is great for SEO, and users see the content much faster.
  • Built-in Routing: No need to install a separate library for routing. Next.js has a powerful and intuitive file-system-based router.
  • Performance Optimizations: Next.js comes with a bundle of performance goodies out of the box, like automatic code splitting (only loading the JavaScript needed for the current page), image optimization, and route pre-fetching.

🧠 Fun Fact: Next.js is created by Vercel, a cloud platform that makes deploying Next.js applications incredibly simple. It's like the company that makes the LEGOs also built the perfect display case for your creations.

2. App Router vs Pages Router: The Modern Paradigm

For a while, Next.js had a way of handling routing called the Pages Router. You'd create files in a pages directory, and the file path would become the URL. Simple and effective.

However, with the release of Next.js 13, a new and more powerful way was introduced: the App Router. This is now the recommended and modern approach to building Next.js applications.

So, what's the big deal?

Think of the Pages Router as a city with a simple grid system. It's easy to navigate, but every intersection looks the same. The App Router, on the other hand, is like a futuristic city with dedicated zones for different activities, shared public spaces, and smart transportation.

Here are the key advantages of the App Router:

  • Server Components by Default: This is a game-changer. In the App Router, your React components are rendered on the server by default. This reduces the amount of JavaScript sent to the browser, leading to faster load times. You can still use client-side interactivity by adding a simple "use client"; directive at the top of a file.
  • Layouts: The App Router introduces a layout.js (or layout.tsx) file. This allows you to create UI that is shared across multiple pages, like a header and a footer, without having to re-render it on every page navigation. This improves performance and state management.
  • Nested Routing and Layouts: You can nest folders to create nested routes, and each nested route can have its own layout, creating a more organized and scalable application structure.
  • Enhanced Data Fetching: The way you fetch data is now more integrated with React itself, often using familiar async/await syntax directly within your server components.

πŸ˜… A little humor: Migrating a large app from the Pages Router to the App Router can feel like trying to change the engine of a car while it's still running. That's why for new projects, it's highly recommended to start with the App Router to take advantage of all the latest features.

3. Your First Next.js App: Using create-next-app

Enough talk, let's build! The easiest and recommended way to start a new Next.js project is by using create-next-app. This is a command-line interface (CLI) tool that sets up everything you need.

Prerequisites:

Before you start, make sure you have Node.js installed on your computer (version 18.x or later is recommended). You can download it from the official Node.js website.

Let's Get Started!

  1. Open your terminal and navigate to the directory where you want to create your project.

  2. Run the following command:

    bash
    npx create-next-app@latest

    This command will kick off an interactive setup process.

  3. You'll be asked a series of questions:

    • What is your project named? Give your project a cool name.
    • Would you like to use TypeScript? It's highly recommended for larger projects, but for now, you can choose 'No'.
    • Would you like to use ESLint? Choose 'Yes'. This will help you write cleaner code.
    • Would you like to use Tailwind CSS? This is a popular CSS framework. You can choose 'No' for now to keep things simple.
    • Would you like to use src/ directory? Choose 'Yes'. This helps in organizing your application code separately from configuration files.
    • Would you like to use App Router (recommended)? Absolutely 'Yes'!
    • Would you like to customize the default import alias? You can press Enter for the default.
  4. Once the installation is complete, navigate into your new project's directory:

    bash
    cd your-project-name
  5. Start the development server:

    bash
    npm run dev
  6. Open your browser and go to http://localhost:3000. You should see the default Next.js welcome page.

Congratulations! πŸŽ‰ You've just created your first Next.js application. That wasn't so hard, was it? You now have a live-reloading development environment, which means any changes you make to your code will be instantly visible in the browser.

4. Demystifying the Project File Structure

Now that you have your Next.js app running, let's take a peek under the hood at the file structure that create-next-app generated for us. It might look a bit intimidating at first, but it's quite logical.

Here's a breakdown of the most important files and folders (assuming you chose to use the src directory):

gradle
your-project-name/
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ next.svg
β”‚   └── vercel.svg
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ favicon.ico
β”‚   β”‚   β”œβ”€β”€ globals.css
β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   └── page.tsx
β”œβ”€β”€ .eslintrc.json
β”œβ”€β”€ .gitignore
β”œβ”€β”€ next.config.mjs
β”œβ”€β”€ package.json
└── tsconfig.json
  • public/: This is where you put static assets like images, fonts, and other files that don't need to be processed by the build system. You can reference them directly in your code.

  • src/: This directory contains all your application's source code.

  • src/app/: The heart of the App Router! This is where you'll define your application's routes and pages.

    • layout.tsx: This is the root layout for your entire application. It's where you'll define the <html> and <body> tags and any UI that should be shared across all pages, like a navigation bar or a footer.
    • page.tsx: This is the main page component for the root of your application (the homepage).
    • globals.css: A global stylesheet that applies to your entire application.
  • next.config.mjs: This file is for configuring Next.js. You can use it to add plugins, set up redirects, and customize the build process.

  • package.json: This file lists your project's dependencies and scripts (like npm run dev).

  • tsconfig.json: If you're using TypeScript, this file contains the configuration for the TypeScript compiler.

And that's the basic anatomy of a Next.js project! As you build more complex applications, you'll add more files and folders, but this gives you a solid foundation to start from.


πŸ“š Extra Reading & References

Challenge

Challenge: Build the Core App Router Files

You have just scaffolded a new Next.js project using create-next-app with TypeScript, the src/ directory, and the App Router. Your task is to write the code for the two most fundamental files: the root layout (src/app/layout.tsx) and the homepage (src/app/page.tsx).

Combine the code for both files into a single response, using comments to separate them as indicated in the initial code.

Requirements for src/app/layout.tsx:

  1. Import the Metadata type from next.
  2. Import the global stylesheet located at ../globals.css.
  3. Export a metadata object with a title set to "My Next.js Site" and a description set to "A challenge to build the core files".
  4. Define and export as default a functional component named RootLayout.
  5. This component must accept a children prop, correctly typed for React components (React.ReactNode).
  6. The component must render the root <html> and <body> tags.
  7. Inside the <body>, render the following in order:
    • A <header> element with an <h1> that says "Global App Header".
    • The {children} prop.
    • A <footer> element with a <p> that says "Copyright 2024".

Requirements for src/app/page.tsx:

  1. Define and export as default a functional component named Home.
  2. This component must be a Server Component (i.e., it should not include the "use client"; directive).
  3. It should return a <main> element that contains:
    • An <h2> element with the text "Welcome to the Homepage".
    • A <p> element with the text "This is the main content area rendered by page.tsx.".

Expected result

The final code should contain two distinct sections separated by comments.

The first section (layout.tsx) should contain:

  • An import statement for Metadata from next.
  • An import statement for ../globals.css.
  • A const export for the metadata object with the required title and description properties.
  • A default exported function RootLayout that takes ({ children }: { children: React.ReactNode }) as its props.
  • The JSX returned by RootLayout must be an <html> tag wrapping a <body> tag. The <body> tag must contain a <header>, {children}, and a <footer> with the specified content.

The second section (page.tsx) should contain:

  • A default exported function Home that takes no props.
  • The component must not contain a "use client"; directive.
  • The JSX returned by Home must be a <main> tag containing an <h2> and a <p> with the exact text specified in the requirements.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.