DEV Community

Cover image for How to Set Up Next.js Project
Niraj Narkhede
Niraj Narkhede

Posted on • Edited on

How to Set Up Next.js Project

Are you a beginner looking to dive into the world of Next.js development? Look no further! In this step-by-step tutorial, we'll guide you through setting up a Next.js project locally. Whether you're new to web development or just getting started with Next.js, this easy-to-follow guide will have you up and running in no time. Let's get started!

Introduction

Welcome to the step-by-step tutorial on setting up a Next.js project locally for beginners. Whether you are new to web development or looking to expand your knowledge, this article will guide you through the process of creating a Next.js project on your local machine.

Next.js is an open-source React framework that provides server-side rendering and helps build modern applications with ease. It is gaining popularity among developers due to its flexibility, performance, and easy integration with other technologies.

In this tutorial, we will cover all the necessary steps required to create a basic Next.js project from scratch. We will start by installing Node.js and NPM (Node Package Manager) as they are essential for building any JavaScript application. Then, we will install Next.js globally on our system to access it from anywhere.

We will then move on to adding pages and routes to our application using Next.js's file-based routing system. This makes navigation between pages seamless without having to configure any complex routing logic.

Furthermore, we will learn about styling options available in Next.js such as CSS modules and styled-jsx which allows us to write scoped styles for each component separately.

We will deploy our project on Vercel - an excellent hosting platform specifically designed for Next.js projects.

By the end of this tutorial, you'll have a fully functional Next.js application running locally on your machine ready for deployment! So let's get started and build something amazing with Next.js.

Prerequisites

Before we dive into setting up a Next.js project locally, there are a few prerequisites that you should have in place. These are essential tools and requirements that will ensure a smooth and successful setup process.

1. Node.js and npm

To run a Next.js project locally, you will need to have Node.js installed on your computer.Node.js is an open-source JavaScript runtime environment that allows you to execute JavaScript code outside of a web browser. It comes with its own package manager, npm (Node Package Manager), which is used to install and manage dependencies for your project.

To check if you have Node.js installed, open your terminal or command prompt and type in node -v. If it returns the version number, then you have Node.js installed. Otherwise, go to the official Node.js website and follow the instructions for installation.

2. Text Editor or IDE

Next, you will need a text editor or integrated development environment (IDE) for writing your code. There are many options available such as Visual Studio Code, Sublime Text, Atom, etc., so choose one that works best for you.

3. Basic Knowledge of HTML/CSS/JavaScript

While this tutorial is aimed at beginners, having some basic knowledge of HTML/CSS/JavaScript will be beneficial in understanding the concepts involved in setting up a Next.js project locally. You should be familiar with creating HTML elements, styling them with CSS, and writing simple JavaScript functions.

4. Familiarity with Command Line Interface (CLI)

Most of the steps involved in setting up a Next.js project locally require using commands in your terminal or command prompt. It would be helpful if you are familiar with navigating through directories and executing commands using CLI.

5. Git Version Control System (Optional)

Using Git can help keep track of changes made to your project files and collaborate with others on the same project effectively. While it is not a requirement, we highly recommend using Git for version control.

By having these prerequisites in place, you will be well-equipped to follow along with this tutorial and successfully set up a Next.js project locally. In the next section, we will go through the step-by-step process of setting up our project.

Installing Next.js

Next.js is a popular JavaScript framework that allows developers to easily build modern and performant web applications. In this section, we will walk you through the steps of installing Next.js on your local machine.

1. Initialize a new npm project

To get started with Next.js, we first need to create a new project directory. Open your terminal or command prompt and navigate to the location where you want to create your project folder. Once there, use the following command to initialize a new npm project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file in your project directory which contains all the information about your project and its dependencies.

2. Install React and ReactDOM

Next, we need to install Next.js as a dependency for our project using npm:

npm install next@latest react@latest react-dom@latest
Enter fullscreen mode Exit fullscreen mode

This command will install Next.js along with its two required dependencies - React and ReactDOM.

3. Creating pages folder

Next.js follows a convention-based approach for creating pages in our application. All page components should be placed inside a folder named pages. So let's go ahead and create this folder inside our project directory.

4. Adding scripts to package.json

To run our application using Next.js, we need to add some scripts in our package.json file. Open the file in any text editor of your choice and add the following code under "scripts":

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}
Enter fullscreen mode Exit fullscreen mode

These scripts will allow us to run our development server, build our application for production, and start the built application respectively.

5. Running the development server

We are ready to run our Next.js application! Use the following command to start your development server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

This will start a local server at http://localhost:3000 where you can view your application in the browser. Any changes you make to your code will automatically be reflected on the page without having to refresh.

Congratulations, you have successfully installed Next.js and set up a project locally! In the next section, we will learn about creating our first page using Next.js.

Creating a New Next.js Project

To get started with Next.js, the first step is to create a new project. This can be done easily using the Create Next App command line tool or by manually setting up a new Next.js project.

Option 1: Using Create Next App

The easiest and quickest way to set up a new Next.js project is by using the Create Next App command line tool. This tool will automatically install all the necessary dependencies and set up boilerplate code for your project, allowing you to start coding right away.

To use this method, make sure you have Node.js installed on your system. Then, open your terminal and run the following command:

npx create-next-app my-next-project
Enter fullscreen mode Exit fullscreen mode

This will create a new folder called my-next-project which contains all the files needed for your next.js project. Once the installation process is complete, navigate to this folder in your terminal and run
npm run dev to start running your project locally.

Option 2: Manual Setup

If you prefer more control over your project's setup, you can also choose to manually set up a new Next.js project. To do this, first create an empty directory where you want to store your project's files. Then, navigate into this directory in your terminal and run npm init -y to initialize a package.json file.

Next, we need to install some dependencies required for our Next.js project. Run the following command in your terminal:

npm install --save react react-dom next
Enter fullscreen mode Exit fullscreen mode

Once these dependencies are installed, we need to set up our basic folder structure and files. Inside our root directory (the one containing package.json), create two additional folders named pages and public. The pages folder will contain all of our application's pages while any static assets such as images or fonts should be placed inside the public folder.

Now that our basic setup is complete, we can start creating our first page. In the pages folder, create a file named index.js and add the following code:

import React from 'react';

const IndexPage = () => {
  return (
    <h1>Hello World!</h1>
  )
}

export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

We need to add a script to package.json so that we can run our project locally. Inside the scripts object, add a new property called dev and set its value to next dev.

Now, in your terminal, run npm run dev to start your Next.js project on your local server. You can access it by navigating to http://localhost:3000 in your browser.

Congratulations! You have successfully created a new Next.js project using either of these methods. From here, you can continue building and customizing your application according to your needs.

Navigating Pages and Routes

In this section, we will discuss how to navigate through pages and routes in a Next.js project. Navigation is an essential part of any web application, and understanding how it works in Next.js is crucial for building a successful project.

Next.js uses a file-based routing system, meaning that each page in your project corresponds to a specific file inside the pages directory. For example, if you create a file called about.js inside the pages directory, it will automatically be rendered as the /about route on your website.

To navigate between pages within your project, you can use the component provided by Next.js. This component allows you to create links between pages without having to reload the entire page. It also ensures that all necessary data is prefetched for better performance.

Let's take an example of how we can use the <Link> component in our project. Suppose we have two pages - index.js and about.js In our index page, we want to create a link that navigates us to our about page. We can do so by importing the Link component from next/link and wrapping our anchor tag around it.

import Link from 'next/link';

function Home() {
  return (
    <>
      <h1>Welcome to my Website</h1>
      <Link href="/about">
        <a>About Me</a>
      </Link>
    </>
  )
}

export default Home;
Enter fullscreen mode Exit fullscreen mode

As you can see, all we need to do is specify the route we want to link to inside the href attribute of our <Link> component. When clicked, this link will take us directly to our about page without reloading the entire website.

Styling in Next.js

One of the great features of Next.js is its built-in support for CSS and styling. In this section, we will explore the different ways you can style your Next.js project.

1. Inline Styling

Next.js allows you to add inline styles to your components using the style attribute. This works just like regular HTML where you can add CSS properties and their values as key-value pairs within double curly braces.

For example:

<div style={{ color: "blue", fontSize: "20px" }}>Hello World!</div>
Enter fullscreen mode Exit fullscreen mode

2. Global Stylesheets

If you prefer to keep your styles separate from your components, Next.js also supports global stylesheets. You can create a new folder called styles at the root of your project and place all your CSS files inside it.

To use these styles in your components, you need to import them using the import statement at the top of your component file.

For example:

// Importing a global stylesheet
import "../styles/global.css";

const App = () => {
  return (
    <div className="container">
      <h1>Hello World!</h1>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

3. Styled JSX

Styled JSX is another way of adding CSS styles to individual React components in Next.js. It allows us to write CSS directly within our JavaScript code by using tagged template literals.

For example:

const Button = () => {
  return (
    <button className="btn">Click Me</button>
    <style jsx>{`
      .btn {
        background: blue;
        color: white;
        font-size: 16px;
        padding: 10px;
      }
    `}</style>
  );
};
Enter fullscreen mode Exit fullscreen mode

4. CSS Modules

CSS Modules are a popular way of organizing and scoping CSS in React applications. Next.js provides built-in support for CSS Modules by default. To use them, you need to create a CSS file with the .module.css extension and import it into your component.

For example:

// styles.module.css
.container {
  background: red;
  color: white;
}

// Component using CSS Modules
import styles from "./styles.module.css";

const App = () => {
  return (
    <div className={styles.container}>
      <h1>Hello World!</h1>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Next.js offers a variety of options for styling your project, including inline styling, global stylesheets, styled JSX, and CSS modules. Each approach has its own advantages and can be used based on personal preference or project requirements. With these styling options at hand, you can easily make your Next.js application visually appealing and well-designed.

Deploying a Next.js Project

Once you have set up your Next.js project locally, the next step is to deploy it so that it can be accessed by others. Deployment refers to the process of making your website or application live on the internet. In this section, we will guide you through the steps of deploying a Next.js project.

1. Choose a Hosting Provider

The first step in deploying your Next.js project is to choose a hosting provider. A hosting provider is a company that provides server space for websites and applications to be stored and accessed on the internet. Some popular options for hosting providers include Vercel, Heroku, and AWS.

2. Prepare Your Project for Deployment

Before you can deploy your Next.js project, there are some preparations that need to be made. First, make sure all necessary files and dependencies are included in your project folder. It is also important to check that your code is optimized and error-free before deployment.

3. Configure Your Environment Variables

Next.js projects often require environment variables such as API keys or database credentials to function properly. These variables should not be hard-coded into your codebase for security reasons. Instead, they should be stored in an .env file which will need to be configured accordingly before deployment.

4. Deploy Using Vercel:

For this tutorial, we will use Vercel as our hosting provider for deploying our Next.js project.

  • Create an account on Vercel's website if you do not already have one.
  • Once logged in, click on Import Project and follow the prompts to select your local project folder.
  • After selecting your project folder, Vercel will automatically detect the type of application it is (in this case Next.js) and provide you with recommended settings.
  • Review these settings and click Deploy when ready.
  • Your Next.js project will now begin building and deploying onto Vercel's servers. This process may take a few minutes.
  • Once the deployment is complete, Vercel will provide you with a unique URL where your project can be accessed live on the internet.

5. Other Hosting Providers:

If you choose to use a different hosting provider, the process of deploying your Next.js project may be slightly different. However, most hosting providers will have similar features and steps for deployment. It is important to carefully follow their instructions and documentation for successful deployment.

Congratulations! You have now successfully deployed your Next.js project and it can be accessed by anyone with an internet connection. Remember to regularly test and update your deployed site to ensure optimal performance for your users. Happy coding!

Conclusion

Now that you have followed this step-by-step tutorial, you should feel confident in setting up a Next.js project locally. With its powerful features and ease of use, it is an excellent choice for building modern web applications. By following these simple steps, you are on your way to creating dynamic and efficient projects with Next.js. So go ahead and give it a try, and don't forget to share your amazing projects with us! We can't wait to see what you will create using the Next.js framework.

Top comments (0)