So you’ve tried Create React App, and maybe you’re thinking, “Sure, it’s nice and all, but what if I want code splitting, universal architecture, and a powerful router with zero configuration cost?” If so you’re in luck.
Enter Next.js from the next-level engineers at Zeit, a dead simple boilerplate for hitting the ground running with some of React’s most desireable features, tax free.
Start things off the usual way, namely by making a directory for your project and initializing it with a package.json
. You’ll want to add the following scripts to that file:
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
Now go ahead and add a few directories: pages
, static
, and components
.
That last one’s not strictly required, but it’ll come in handy momentarily. 🐿
$ npm install next --save
And that’s it. You’re configured with all the bells and whistles. Let’s dig into how it works.
The first thing to note is that every .js
file in the pages
directory will be routed automatically — index.js
routes to /
; bite.js
routes to /bite
; and so on. This is also where your code splitting happens, with each discrete page getting a discrete bundle complete with scoped dependencies and server rendering where applicable.
Next uses a CDN to leverage the browser’s cache for efficiency in serving React. 🚀 It has a local fallback and can be turned off.
We could leave it there, and things would be cool as they stand, but wait, there’s more.
import Link from 'next/link';
...
<Link href={`about?story=${assets.story}`}>About This Site</Link>
And therein lies your lazy-loading. Use Next’s Link
component where applicable and the machinery beneath will take it from there. Furthermore, the astute observer would take note of that query string on the href
, and that astute eye would be rewarded. Clicked Link
s receive a prop called url
, on which the query
can be accessed.
This is a fine moment to revisit that components
directory. With pages doing all this heavy lifting you’ll want a place to stow your more modular odds and ends to keep your routing clean.
Another cool trick up Next’s sleeve is this bad boy:
import React from 'react';
import Head from 'next/head';
export default ({title}) => {
return <Head>
<title>{title}</title>
<link rel="stylesheet" href="static/styles.css" />
</Head>
}
The Head
component allows you to dynamically reconfigure the document head. Mighty useful.
import React from 'react';
import css from 'next/css';
let p = css({
color: '#858576',
fontSize: 32
});
export default ({caption}) => <p {...p}>{caption}</p>
Similarly useful is the team’s inclusion of the Glamor inline CSS module. The old ways work, too, all the way to vanilla objects and require
statements, but it’s a nice touch.
⚠️️ It’s worth noting that Next is approaching a major release (2.x.x) that will change aspects of its API and that the readme on Github is out of sync with the version you’re installing via npm (^1.2.3).
And for our final trick, let’s bring it all together with a little data fetching. Next.js holds out getInitialProps
in all its async/await
glory for your data gathering needs but makes no prescriptions for what other tools you use. All that really matters is you use something equally suited to the browser and the server since it’ll run on both.
import React from 'react';
import axios from 'axios';
export default class extends React.Component {
static async getInitialProps () {
const res = await axios.get('https://api.npmjs.org/downloads/point/last-week/next');
return {nextNpmDownloads: res.data.downloads};
}
render () {
return <div>
{`Did you know Next has had ${this.props.nextNpmDownloads} on npm in the last month?`}
</div>
}
}
All that remains is to fire up your dev server care of npm run dev
, point your browser to port 3000, and say hello to simplicity in its most sophisticated form.
👉 If you think that’s cool, wait till we deploy it.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!