NextJS To The Moon 🌚

NextJS Is Here

A glorious day of consolation within the JS world is upon us.

Next JS is a React Framework. This distinguishes it from React itself, which is only a front-end rendering library. React handles the rendering in the frontend (and often is rendered on the server as well), but a framework is complete the picture of how to build a full web application.

This is a major development for Node-ecosystem which has historically be fragmented into dozens of different backend frameworks, toolchains, and build systems that JS wizards were expected to know.

Not one tool is right for all projects—- when you need a hammer, you need a hammer. Standardization in web dev is a good thing.

Let’s start by creating the very basic NextJS app.

Start With NextJS create-next-app

npx create-next-app my-great-app --use-npm 

Ok boom you have a fairly empty NextJS app called my-great-app Now what?

Let’s take a quick look at the default NextJS directory structure.

NextJS boiler-plate setup

node_modules are installed by node so we typically don’t go into that directory.

The pages directory is where most of the magic happens, and like many standard web apps a public directory holds our images and a styles directory holds our styles.

On the command line in the directory where the app lives, run

yarn dev

Boom your NextJS dev environment is up and running.

NextJS default screen

As the instructions say, we’re going to get started by editing pages/index.js.

Because I think boiler-plate is bad for learning, let’s rip out all of this file and start again.

Hello World NextJS

Take out everything inside the return of the Home function and replace it with a basic Hello World





So the file will now be just:

export default function Home() {
return (
<>Hello World</>
)
}

A Weather App

The first thing we’re going to do is head over to openweathermap.org and sign up for a free account.

You’ll need to verify your email address.

Then, you’ll create an OpenWeatherMap.org API key on the “My API Keys” page.

This weather app will help us demonstrate a couple of things immediately:

• Your API key is going to be protected by keeping it on the backend. Although not implemented here, you can rate limit your backend requests to only legitimate users of your app and block out anyone who wants to abuse your endpoint.

How Do Routes Work in NextJS

The first thing we need to do is head on over to the docs to understand how routes work in Next JS

https://nextjs.org/docs/api-routes/introduction

The first thing it tells us is:

Next JS Any file inside the folder pages/api is mapped to

Here we have our first important piece of information about how Next JS works: the distinction between server-side bundles and client-side bundles.

Create a file at page/api/weatherInfo.js

export default function handler(req, res) {
res.status(200).json({ forecast: 'Hello API' })
}

Now start your server with yarn dev

Next JS Basics

Notice that <Head> is used instead of the lowercase <head><Head> is a React Component that is built into Next.js. It allows you to modify the <head> of a page.

You can import the Head component from the next/head module.

Your basic <Head/> object looks like this

<Head>
  <title>My Great App</title>
  <link rel="icon" href="/favicon.ico" />
</Head>

What’s important about the Next Head object is:

How Page Transitions Work in NextJS

NextJS has a special way of writing links that may look odd to developers coming from other backgrounds:

In Next, you’re always going to create a link like this:

(remember to import Link from 'next/link' at the top of your file)


<Link href="/">
  <a>Go</a>
</Link>

Unlike normal HTML, the Link component takes the href, not the <a> tag, but the <a> tag still wraps label of your link (in this case, “Go”).

The Link component enables client-side navigation between two pages in the same Next.js app.

Client-side navigation means that the page transition happens using JavaScript, which is faster than the default navigation done by the browser.

— NextJS Docs[ref]

This way means your application will be hella fast!

This way of serving your page has an important effect: your page does not do a full page refresh between transitions.

The NextJS docs also point out these two helpful caveats

Note if you need to link to an external page

But wait, there’s more: Asset Image Optimization Magic

One of the most magic parts of NextJS is the image optimization it will do for you.

  • Ensuring your image is responsive on different screen sizes
  • Optimizing your images with a third-party tool or library
  • Only loading images when they enter the viewport

Next.js also has support for Image Optimization by default. This allows for resizing, optimizing, and serving images in modern formats like WebP when the browser supports it. This avoids shipping large images to devices with a smaller viewport. It also allows Next.js to automatically adopt future image formats and serve them to browsers that support those formats.

Automatic Image Optimization works with any image source. Even if the image is hosted by an external data source, like a CMS, it can still be optimized.

Responsive

Adding Head to first-post.js

On-The-Fly Optimization

Boom: Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Unlike static site generators and static-only solutions, your build times aren’t increased, whether shipping 10 images or 10 million images.

Lazy Loaded

Excited? You should be. These are massive improvements in the build process for web developers. In short, we just can forget having the headache of making an optimized website performant.

Meet your very first Next Image

import Image from 'next/image'

const YourComponent = () => (
  <Image
    src="/images/my-pic.jpg" // Route of the image file
    height={144} // Desired size with correct aspect ratio
    width={144} // Desired size with correct aspect ratio
    alt="Always have alt text"
  />
)




Remember, always import the Next Image object using import Image from 'next/image'

Then, you can use <Image /> inside of your component.

Very important always, always, always:

• Give your images a desired height and width.

• Always specify an alt text attribute for best SEO performance

• Of course, specify the src like you normally would in an <img /> tag

Cumulative Layout Shift — Be Gone!

Have you ever been reading an article online when something suddenly changes on the page? Without warning, the text moves, and you’ve lost your place. Or even worse: you’re about to tap a link or a button, but in the instant before your finger lands—BOOM—the link moves, and you end up clicking something else!

This is what happens when web pages load resources asynchronously and some resources—like images— take a while to load. It can also happen as a side-effect of advertising Javascript that runs on your page. CLS is bad.

Next automatically eliminates Cumulative Layout Shift but the trade-off is that you must specify the height & width of your images. This way, Next is able to appropriately size the image to the page.