How to Build Your First Next.js App: Step-by-Step Tutorial

How to Build Your First Next.js App: Step-by-Step Tutorial

Start Your Next.js Journey: Create a Powerful Web App

Next.js is a popular React framework that enables developers to build fast, SEO-friendly, and scalable web applications. It offers powerful features like server-side rendering, static site generation, and API routes, making it an excellent choice for modern web development. In this step-by-step guide, we'll walk through the process of building your first Next.js application from scratch.

Step 1: Setting Up Your Development Environment

Before we start building, ensure you have Node.js and npm (or Yarn) installed on your machine. You can download and install them from Node.js.

Step 2: Create a New Next.js Application

Next.js provides a boilerplate generator that makes it easy to start a new project. Run the following command to create a new Next.js application:

npx create-next-app my-next-app

Replace my-next-app with your desired project name. This command sets up a new Next.js project with all the necessary files and dependencies.

Step 3: Run the Development Server

Navigate to your project directory and start the development server:

cd my-next-app
npm run dev

Your application should now be running at http://localhost:3000. Open this URL in your browser to see the default Next.js welcome page.

Step 4: Create Your First Page

Next.js uses a file-based routing system where each file in the pages directory corresponds to a route in your application. Let's create a new page called about.js.

  1. Create a new file in the pages directory:
touch pages/about.js
  1. Add the following content to pages/about.js:
// pages/about.js
const About = () => {
  return (
    <div>
      <h1>About Us</h1>
      <p>Welcome to the about page of our Next.js application.</p>
    </div>
  );
};

export default About;

You can now navigate to http://localhost:3000/about to see your new About page.

Step 5: Adding a Navigation Menu

To navigate between pages, let's add a simple navigation menu to our application. We'll do this by creating a layout component.

  1. Create a new directory called components:
mkdir components
  1. Create a new file called components/Layout.js and add the following content:
// components/Layout.js
import Link from 'next/link';

const Layout = ({ children }) => {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <Link href="/">Home</Link>
          </li>
          <li>
            <Link href="/about">About</Link>
          </li>
        </ul>
      </nav>
      <main>{children}</main>
    </div>
  );
};

export default Layout;
  1. Wrap your pages with the Layout component. Modify pages/index.js as follows:
// pages/index.js
import Layout from '../components/Layout';

const Home = () => {
  return (
    <Layout>
      <h1>Home Page</h1>
      <p>Welcome to our Next.js application.</p>
    </Layout>
  );
};

export default Home;
  1. Update pages/about.js to use the Layout component:
// pages/about.js
import Layout from '../components/Layout';

const About = () => {
  return (
    <Layout>
      <h1>About Us</h1>
      <p>Welcome to the about page of our Next.js application.</p>
    </Layout>
  );
};

export default About;

Step 6: Fetching Data with getStaticProps

Next.js supports static site generation, allowing you to fetch data at build time. Let's create a page that fetches and displays a list of posts.

  1. Create a new file called pages/posts.js:
touch pages/posts.js
  1. Add the following content to pages/posts.js:
// pages/posts.js
import Layout from '../components/Layout';

export const getStaticProps = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
};

const Posts = ({ posts }) => {
  return (
    <Layout>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </Layout>
  );
};

export default Posts;

Now, navigate to http://localhost:3000/posts to see the list of posts fetched from the API.

Step 7: Adding API Routes

Next.js allows you to create API routes within your application. These routes can be used to handle backend logic, database interactions, or third-party API requests.

  1. Create a new directory called pages/api.
mkdir pages/api
  1. Create a new file called pages/api/hello.js:
touch pages/api/hello.js
  1. Add the following content to pages/api/hello.js:
// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js API!' });
}

You can now access this API endpoint at http://localhost:3000/api/hello.

Conclusion
Congratulations! You've built your first Next.js application with a home page, about page, navigation menu, data fetching, and API routes. Next.js is a powerful framework that simplifies many aspects of web development, from routing and data fetching to server-side rendering and static site generation.

This guide covers the basics, but Next.js has many more features to explore. Check out the official Next.js documentation for more advanced topics and best practices. Happy coding!

Did you find this article valuable?

Support ByteScrum Technologies by becoming a sponsor. Any amount is appreciated!