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!
Before you begin this guide you’ll need the following:
You can follow the instructions on the Node.js official download page to install Node.js.
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 create-next-app@latest # 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.
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!
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
.
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.
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
.
You have now finished creating a website with Next.js and React. You should now be able to:
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!
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 — start monitoring for free.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowAngular’s two-way data binding has evolved with signals, offering improved performance, simpler syntax, and better type inference.
Fix sticky positioning issues in CSS, from missing offsets to overflow conflicts in flex, grid, and container height constraints.
From basic syntax and advanced techniques to practical applications and error handling, here’s how to use node-cron.
The Angular tree view can be hard to get right, but once you understand it, it can be quite a powerful visual representation.
6 Replies to "Creating a website with Next.js and React"
Thanks for the article!
Currently NASA is returning a YouTube video url…
Learned something, thanks
Thanks for Article. I just started learn Next.JS 😀
You have to give a name on index.js
“export default class somename extends Component {”
Otherwise, when running
> npm run build
Threw Error: Component definition is missing display name react/display-name
root cause here https://www.akashmittal.com/component-definition-missing-display-name/
Thanks,
G
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
Thanks for pointing out that typo. It’s been fixed.