Web Programming TutorialsGetting Started with NextJS

Getting Started with NextJS

Introduction

Working with a modern JavaScript using a React as the front-end framework comes with its own problems. You want to focus on building and releasing/shipping the application for the user rather than spending too much time configuring and managing code-splitting, determining the content loading architecture, and bundling them together in order to serve it as a web application.

Next.js is a promising React framework that targets above-mentioned problems and is often advertised as a zero-configuration framework for React applications. Often, when you are releasing a public app or a website, you need to render the content for search engines to optimize your website. Next.js tend to solve this problem too by handling server-side rendering for you.

Pre-requisites

To continue with this tutorial, you will need the following:

  • npm installed on your machine.
  • Knowledge of ES6 JavaScript features such anonymous arrow functions =>, import and export statements, async/await and so on.
  • ReactJS

Features

Some of the important features NextJS has:

  • Hot Code Reloading: Next.js reloads the page when it detects any change saved to disk
  • Automatic Routing: any URL is mapped to the filesystem. Just put files in the pages folder
  • Single File Components: using styled-jsx, completely integrated as built by the same team, it’s trivial to add styles scoped to the component
  • Server Rendering: you can (optionally) render React components on the server side, before sending the HTML to the client.
  • Ecosystem Compatibility: Next.js plays well with the rest of the JavaScript, Node and React ecosystem. Automatic Code Splitting: pages are rendered with just the libraries and JavaScript that they need, not more.
  • Dynamic Components: you can import JavaScript modules and React Components dynamically.

Installation & Getting Started

Next.js supports all the major platforms: Linux, macOS, Windows. You can install it using npm.

npm install next react react-dom

Then, to get started add the following script in your package.json file.

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

If you run the below command.

npm run dev

The script will raise an error complaining about not finding the pages folder. This is the only thing that Next.js requires to run. Create an empty pages folder. Then, run the npm run dev command again, as Next.js will start up a server on http://localhost:3000. If you go to that URL now, you will be greeted by a friendly 404 page, with a nice clean design.

Our First Page

In the pages folder create an index.js file with a simple React component.

export default () => (
    <div>
        <p>Hello World!</p>
    </div>
);

If you visit http://localhost:3000, this component will automatically be rendered. Next.js uses a declarative pages structure, which is based on the filesystem structure. Anything inside pages directory is considered as a page to be rendered.

Hot Reloading

Note that you did not have to restart the npm process to load the page. Next.js does this for you under the hood. To prove this further, create a second page in the pages directory called contact.js.

export default () => (
    <div>
        <p>
            <a href="mailto:[email protected]">Contact Me</a>
        </p>
    </div>
);

If you now visit from your browser to http://localhost:3000/contact this page will be rendered.

Client-side Rendering

Navigating inside the website, client-side rendering is key to speed up the page load and improve the user experience. Next.js provides a Link component you can use to build links. Try linking the two pages above. Modify index.js file to reflect new changes.

import Link from 'next/link';

export default () => (
    <div>
        <p>Hello World!</p>
        <Link href="/contact">
            <a>Contact me!</a>
        </Link>
    </div>
);

First, we imported the Link API module from Next.JS and then we used it inline in the midst of our content by making a placeholder for it with the {‘ ‘} syntax. The <Link> component is a Higher Order Component and supports only a couple arguments such as href (and href argument itself supports arguments like query strings and the like) and as for URL masking. The underlying component, in this case, an <a> tag supports other props like style and onClick.

Now go back to the browser and try this link. On clicking, the Contact page loads immediately without a page refresh. This is client-side navigation which is working correctly. The complete support for the History API, which means that the users back button would not break.

CSS-in-JS

Next.js by default provides support for styled-jsx, which is a CSS-in-JS solution provided by the same development team, but you can use whatever library you prefer, like Styled Components. Open, contact.js file and modify it accordingly.

export default () => (
    <div>
        <p>
            <a href="mailto:[email protected]">Contact Me</a>
        </p>
        <style jsx>{`
            p {
                font-family: 'Helvetica Neue';
            }
            a {
                text-decoration: none;
                color: orange;
            }
            a:hover {
                opacity: 0.6;
            }
        `}</style>
    </div>
);

Styles are scoped to the component, but you can also edit global styles adding global to the style element.

export default () => (
    <div>
        <p>
            <a href="mailto:[email protected]">Contact Me</a>
        </p>
        <style jsx global>{`
            body {
                font-family: 'Benton Sans', 'Helvetica Neue';
                margin: 2em;
            }
            h2 {
                font-style: italic;
                color: #373fff;
            }
        `}</style>
    </div>
);

Deploying

Creating a production-ready copy of the application, without source maps or another development tooling that is unneeded in the final build, is easy. At the beginning of this tutorial, you created a package.json file with the scripts as content. Now just add the following content to package.json.

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

You can prepare your app by running npm run build and npm run start in that order. The company behind Next.js provides an awesome hosting service for Node.js applications, called Now. Yes, they integrate both their products so you can deploy Next.js apps seamlessly, once you have Now installed, by running the now command in the application folder. Behind the scenes Now sets up a server for you, and you don’t need to worry about anything, just wait for your application URL to be ready.

Next.js tries to solve the problem as a framework by increasing development speed, taking of care of tooling, and bundling the application files behind the scenes. Rest is your effort with a mixture of imagination and curiosity of what you can build using it. The sole purpose of this tutorial was to give you quick start as learning a new framework can overwhelming at first and make you understand the basic concepts behind it for you to use it to build your next application.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -