Nick Major Nick Major is the founder of Coder Rocket Fuel.

Creating a website with Next.js and React

6 min read 1783

Editor’s note: This post was updated in October 2021.

Next.js is a widely-used framework for building React applications that offer server-side rendering, automatic code-splitting, static exporting options, and easy production builds.

It also relieves a lot of the general headaches involved with creating production-ready React applications.

In this tutorial, we’ll show you how to bootstrap a Next.js web application and add some basic components and features of a typical website.

Through that process, you’ll gain an understanding of how to use the framework.

Let’s get started!

Prerequisites for creating a website with Next.js and React

Before you begin this guide you’ll need the following:

  • Node.js installed on your local development machine.

You can follow the instructions on the Node.js official download page to install Node.js.

Step 1 — Bootstrap a Next.js application

There are two ways to bootstrap a Next.js application. The first one is to use the create-next-app command. Like many popular frameworks, Next.js now has its own command to set up a Next.js project quickly and easily.

To start, we need to open a new terminal window (Ctrl+Alt+T on Linux or Command+Space on Mac) and run:

npx [email protected]
# or
yarn create next-app

Note: if we would like a TypeScript project, we need to add a --typescript flag at the end (i.e., yarn create next-app --typescript).

This command will prompt us for a project name. Once done, our new project will be accessible. We can run our Next.js project by running these commands:

cd your-project

npm run dev
# or
yarn dev

Open your favorite browser and visit http://localhost:3000. We should see “Welcome to Next.js!” displayed on our screen.

The second method to create a Next.js project is to do it manually. To start with, we need to first create a project directory and install the required dependencies using npm (Node.js Package Manager).

Open a new terminal window (Ctrl+Alt+T on Linux or Command+Space on Mac) and execute the command below to create a new project folder that will house your Next.js application (replace “your-project” with the name of your project):

mkdir your-project

Add cd into your new directory:

cd your-project

Next, run this command to create a package.json file in the root of your project:

npm init -y
# or
yarn init -y

This command creates a package.json file in the root of your project directory.

The -y flag initializes the file with default values.

The package.json file will allow you to easily install and use npm package dependencies in your project. It will also make things like sharing your project with other developers easier if you wish to do so in the future.

Check out the npm documentation if you want to learn more about the contents of the package.json file.

Now that we have a package.json file created, we can install the required npm package dependencies for your Next.js website.

To get started, we’ll need the Next, React, and react-dom npm packages.

You can install all of them at once with this command:

npm install next react react-dom
# or 
yarn add next react react-dom

When those finish installing, you’ll notice that a new node_modules directory was created in your project.



This directory stores all of the installed dependencies for your project.

If you look inside, you’ll notice that the three npm packages you installed and all of their sub-dependencies are in there.

In the future when you share your code with others, all of the packages in that list will be installed in the initial setup of the application or when the install command is run.

Now that we have your dependencies installed, we need a way to start your application.

Open your package.json file and replace the “scripts” section with this code:

[label package.json]

"scripts": {
  "dev": "next dev"
},

The "dev" script is used to run the application when you’re in development mode.

This means your code will run with special error handling, hot-reloading, and other features that make the development process more pleasant.

Later on, we’ll add more scripts to this section to handle the production versions of your application.


More great articles from LogRocket:


In your terminal, start the application in development mode with this command:

npm run dev

You’ll see an error when you execute that command:

[label Output]

Couldn't find a `pages` directory. Please create one under the project root

Next.js looked for a /pages directory that holds all the different paths for your website and threw an error when it didn’t find one.

To fix the error and get your website running, we need to create a new directory called /pages and add a page to it that Next.js can render.

First, create a /pages directory in the root of your project:

mkdir pages

Add cd into it with this command:

cd pages

Then, add a new file called index.js:

touch index.js

We need to add some code to your /pages/index.js file to give Next.js something to render.
Open /pages/index.js in your favorite text editor and add this code to the file:

[label /pages/index.js]

import React, { Component } from 'react'

export default class extends Component {
  render () {
    return (
      <div>Your Next.js App</div>
    )
  }
}

The code above creates a React class component and exports it with export default.

Save the changes to the file and restart your application with:

npm run dev

Open your favorite browser and visit http://localhost:3000.

You should see the text “Your Next.js App” displayed.

Congratulations, you have now created a working Next.js website!

Step 2 – Understanding pages folders

The /pages directory will hold all of the pages for your website, and the index.js file will serve as your homepage at the / URL path. The name of each file in the /pages directory will match the URL path in the browser when your website is visited.

For example, a file with the path /pages/articles.js will have a URL that displays as /articles in the browser. All of this is handled automatically by Next.js.

The only exceptions are index.js files whose URL will be named after the root of the directory they are placed in. For example, the /pages/index.js file serves as the homepage at the / path, while /pages/articles/index.js will become /pages/articles.

Step 3 — Retrieve and display data from an external API

One cool thing about Next.js is the server-side rendering features that it provides. You can fetch and receive data from an external API before your web page loads.

To demonstrate this, we’ll use NASA’s public API to display data from their Astronomy Picture of the Day program.

Every day they publish a new photo from the universe with a brief explanation written by an astronomer.

We’ll make requests with an npm package called Isomorphic-Unfetch. This package is great for Next.js because it works in both client and server environments.

Run this command to install the npm package in your project:

npm install isomorphic-unfetch # or
yarn add isomorphic-unfetch

Then, reopen your /pages/index.js file and replace its contents with this code:

[label /pages/index.js]

import React, { Component } from 'react'
import fetch from 'isomorphic-unfetch'

export default class extends Component {
  render () {
    return (
      <div>
        <div>
          {this.props.title}
        </div>
        <div>
          <img src={this.props.imageUrl} />
        </div>
      </div>
    )
  }
}

export async function getStaticProps() {
  const res = await fetch(
    "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
  );
  const data = await res.json();

  return {
    props: {
      title: data.title,
      imageUrl: data.url,
    },
  };
}

You’ll notice that we added a new asynchronous function at the top of your React component called getStaticProps().

This is an internal Next.js function that allows you to fetch data and populate your React component via its props before loading the page.

The code in the getStaticProps() function is run on the server, and its results are sent back to the page where it was called.

Inside your getStaticProps() function, we first make a request to the NASA REST API endpoint for the Astronomy Picture of the Day and convert the data response to an object that we can work with.

Using that data, we then populate the React component’s props with the title and imageUrl data.

Then, we added some <div> elements for both of the items and populated them with data using the this.props React method.

Save the file and view the changes in your browser.

You should see the title and the image of the day displayed on the page.

Step 4 — build your application for production

Next.js makes the deployment process easy and pain-free. If you manually built your Next.js project, you need to add both a “build” and “start” script to the package.json file.

Open your package.json file and make the “scripts” section look like this:

[label package.json]

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start"
},

The “build” script will compile your code into server and browser code that will run on a server in production. The “start” script is how you start that production code in the production environment.

To build the application, run the command:

npm run build

It will take a few moments to finish running.

When it’s done, notice that a new directory called /.next was created. There are a lot of different directories and files that Next.js adds to that directory.

For this tutorial, all you need to know is that it’s an optimized version of the code you have been running in development mode. To start the application in production mode and run the code inside the /.next directory, run this command:

npm start

The production-ready version of your website should now be running at http://localhost:3000.

Conclusion

You have now finished creating a website with Next.js and React. You should now be able to:

  • Bootstrap a new Next.js application
  • Create new pages in a Next.js application
  • Fetch data from an external API and display it on a Next.js page
  • Build and run a Next.js application in production

The website we built in this tutorial can be greatly expanded upon.

You can add custom styling using CSS, add more pages to the /pages directory, fetch data from another API you or someone else has built, and/or deploy the application to a server and make it accessible to the world.

These are just a few examples of what you could do to enhance your Next.js application.

Have fun exploring and happy coding!

LogRocket: Full visibility into your production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket combines session replay, product analytics, and error tracking – empowering software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay problems as if they happened in your own browser to quickly understand what went wrong.

No more noisy alerting. Smart error tracking lets you triage and categorize issues, then learns from this. Get notified of impactful user issues, not false positives. Less alerts, way more useful signal.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

LogRocket: Full visibility into production Next.js apps

Debugging Next applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Next.js app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your Next.js apps — .

Nick Major Nick Major is the founder of Coder Rocket Fuel.

6 Replies to “Creating a website with Next.js and React”

  1. npm installnext react react-dom

    This command is wrong, you need to type a space between ‘install’ and ‘next’
    -> npm install next react react-dom

Leave a Reply