DEV Community

Cover image for Comprehensive Step-by-Step Guide to Setting Up a Next.js Project
TD!
TD!

Posted on

Comprehensive Step-by-Step Guide to Setting Up a Next.js Project

Next.js is one of the most popular frameworks for building modern web applications. Built on top of React.js, Next.js offers server-side rendering, static site generation, file-based routing, and other powerful features to streamline the web development process.

1. What is Next.js?

Before diving into the setup, it’s crucial to understand what makes Next.js different from other React frameworks:

  • Server-Side Rendering (SSR): Pages are pre-rendered on the server, enhancing performance and SEO.
  • Static Site Generation (SSG): Pre-renders pages at build time for lightning-fast performance.
  • File-Based Routing: Routes are automatically generated based on the files in the pages directory.
  • API Routes: Define backend endpoints directly within the same Next.js project.
  • Full Stack Capabilities: Supports hybrid static & server-side rendering, with a flexible deployment system.

2. Setting Up a Next.js Project

Next.js is constantly evolving, and in 2024, it’s easier than ever to set up and start building your application.

Step 1: Prerequisites

Ensure that you have the following prerequisites installed:

Node.js: Version 18.x or higher. You can check your version by running:

node -v
Enter fullscreen mode Exit fullscreen mode

If you don't have Node.js, download it from nodejs.org.

npm or yarn: npm comes bundled with Node.js, but you can also use yarn as a package manager if preferred.

Step 2: Creating a New Next.js Project

Next.js provides a command-line tool called create-next-app that streamlines the setup process.

  1. Navigate to the folder where you want to create your project:
cd /path/to/your/directory
Enter fullscreen mode Exit fullscreen mode
  1. Run the command to create a Next.js app: If you're using npm, run:
npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

For yarn, use:

yarn create next-app
Enter fullscreen mode Exit fullscreen mode

Follow the prompts:

  • Project Name: Give your project a name (e.g., nextjs-app).
  • Typescript: Decide whether to use TypeScript or JavaScript.
  • ESLint: Enable or disable linting (recommended to enable).
  • Tailwind CSS: You can choose to add Tailwind CSS during the setup, or add it later manually.
  • Import Alias: Decide whether to configure import aliases for cleaner file imports.

After this, the Next.js starter project will be created with all the essential configurations.

Step 3: Exploring the Folder Structure

Once your project is created, the structure will look like this:

nextjs-app/
├── node_modules/
├── pages/
│   ├── api/
│   │   └── hello.js
│   ├── _app.js
│   ├── index.js
├── public/
├── styles/
│   ├── globals.css
│   ├── Home.module.css
├── .eslintrc.json
├── next.config.js
├── package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode
  • pages/: This is where the routes and page components are defined.
  • pages/api/: API routes are stored here; hello.js is an example.
  • public/: Static assets (e.g., images, fonts) are placed here.
  • styles/: Global and module-specific stylesheets.

Step 4: Running the Development Server

Navigate into your project directory:


cd nextjs-app
Enter fullscreen mode Exit fullscreen mode

Start the development server:


npm run dev
Enter fullscreen mode Exit fullscreen mode

or


yarn dev
Enter fullscreen mode Exit fullscreen mode

This will start the Next.js server at http://localhost:3000. You can now open your browser and visit http://localhost:3000 to see the default Next.js page.

3. Core Features of Next.js

A. File-Based Routing

Next.js uses a file-based routing system, meaning every file in the pages/ directory automatically becomes a route.

  • Create a new page:

Create a new file called about.js inside the pages/ directory:


touch pages/about.js
Enter fullscreen mode Exit fullscreen mode
  • Add the following content to the file:

const About = () => {
  return <h1>About Us</h1>;
}

export default About;
Enter fullscreen mode Exit fullscreen mode

Access the page: Open your browser and visit http://localhost:3000/about, and you’ll see the content from the About component.

B. Linking Between Pages

Next.js comes with a built-in Link component to handle client-side navigation.

Modify your index.js file to include a link to the About page:


import Link from 'next/link';

const Home = () => {
  return (
    <div>
      <h1>Welcome to the Home Page</h1>
      <Link href="/about">Go to About Page</Link>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Now, when you click on the "Go to About Page" link, you will be routed to the about page.

C. CSS and Styling in Next.js

Next.js allows you to import CSS files globally or use CSS modules for component-level styles.

Global CSS:

In the styles/globals.css file, you can add global styles:


body {
  font-family: Arial, sans-serif;
  margin: 0;
}
Enter fullscreen mode Exit fullscreen mode

Import this file in your _app.js component:


import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

CSS Modules: For component-specific styles, Next.js supports CSS Modules. Modify Home.module.css:


.title {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Then, import it in your index.js file:


import styles from '../styles/Home.module.css';

const Home = () => {
  return <h1 className={styles.title}>Welcome to the Home Page</h1>;
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

4. Data Fetching in Next.js

Next.js offers multiple ways to fetch data for pages.

A. Static Site Generation (SSG)

Pre-render the page at build time by using the getStaticProps function:


export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  return {
    props: {
      data
    }
  };
}

const Home = ({ data }) => {
  return (
    <div>
      <h1>Data from API:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

B. Server-Side Rendering (SSR)

Fetch data at request time using the getServerSideProps function:


export async function getServerSideProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  return {
    props: {
      data
    }
  };
}

const Home = ({ data }) => {
  return (
    <div>
      <h1>Server-Side Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

5. API Routes in Next.js

Next.js allows you to define backend routes within the same project. These routes are created inside the pages/api/ folder.

Create a file called hello.js inside pages/api/:


export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js API!' });
}
Enter fullscreen mode Exit fullscreen mode

Access the API endpoint at http://localhost:3000/api/hello.

6. Deployment in Next.js

Next.js projects can be deployed on various platforms like Vercel, Netlify, or any Node.js server. Here's how to deploy on Vercel:

Install Vercel CLI:


npm install -g vercel
Enter fullscreen mode Exit fullscreen mode

Deploy: From your project directory, run:


vercel
Enter fullscreen mode Exit fullscreen mode

PS: Localhost is not a URL you can access over the internet; it only works on your local computer. It refers to the server running on your machine, typically at http://localhost, and is used for development purposes.

Top comments (0)