DEV Community

Cover image for How To Create a Website with Next.js and React
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

How To Create a Website with Next.js and React

Written by Nick Major✏️

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

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.

LogRocket Free Trial Banner

Step 1 — Bootstrap a Next.js application

To create a Next.js web application, 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
Enter fullscreen mode Exit fullscreen mode

Add cd into your new directory:

cd your-project
Enter fullscreen mode Exit fullscreen mode

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

npm init -y
Enter fullscreen mode Exit fullscreen mode

The npm init -y 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 --save next react react-dom
Enter fullscreen mode Exit fullscreen mode

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.

Since we used the --save flag on your npm install command, the three dependencies will be listed in the “dependencies” section of your package.json file.

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 npm 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"
},
Enter fullscreen mode Exit fullscreen mode

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.

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

npm run dev
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

We’ll fix that error in the next section.

Step 2 — Create your first page

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
Enter fullscreen mode Exit fullscreen mode

Add cd into it with this command:

cd pages
Enter fullscreen mode Exit fullscreen mode

Then, add a new file called index.js:

touch index.js
Enter fullscreen mode Exit fullscreen mode

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 /pages/index.js file is the only exception as it serves as the homepage at the / path.

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>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 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 --save isomorphic-unfetch
Enter fullscreen mode Exit fullscreen mode

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 {
  static async getInitialProps() {
    const res = await fetch("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
    const data = await res.json()

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

  render () {
    return (
      <div>
        <div>
          {this.props.title}
        </div>
        <div>
          <img src={this.props.imageUrl} />
        </div>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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 getInitialProps() function is run on the server, and its results are sent back to the page where it was called.

Inside your getInitialProps() 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 populate 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.

First, we 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",
  "build": "next build",
  "start": "next start"
},
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!


Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are difficult 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.

Alt Text

LogRocket is like a DVR for web apps, recording literally everything that happens on your React 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 React apps — start monitoring for free.


The post How To Create a Website with Next.js and React appeared first on LogRocket Blog.

Top comments (0)