Next.js is a minimalistic framework for server-rendered React applications.
Visit learnnextjs.com to get started with Next.js.
- How to use
- Setup
- Automatic code splitting
- CSS
- Static file serving (e.g.: images)
- Populating
<head>
- Fetching data and component lifecycle
- Routing
- Prefetching Pages
- Custom server and routing
- Dynamic Import
- Custom
<Document>
- Custom error handling
- Custom configuration
- Customizing webpack config
- Customizing babel config
- CDN support with Asset Prefix
- Production deployment
- Static HTML export
- Recipes
- FAQ
- Contributing
- Authors
Install it:
npm install --save next react react-dom
Next.js 4 only supports React 16.
We had to drop React 15 support due to the way React 16 works and how we use it.
and add a script to your package.json like this:
{
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
}
After that, the file-system is the main API. Every .js
file becomes a route that gets automatically processed and rendered.
Populate ./pages/index.js
inside your project:
export default () => <div>Welcome to next.js!</div>
and then just run npm run dev
and go to http://localhost:3000
. To use another port, you can run npm run dev -- -p <your port here>
.
So far, we get:
- Automatic transpilation and bundling (with webpack and babel)
- Hot code reloading
- Server rendering and indexing of
./pages
- Static file serving.
./static/
is mapped to/static/
To see how simple this is, check out the sample app - nextgram
Every import
you declare gets bundled and served with each page. That means pages never load unnecessary code!
import cowsay from 'cowsay-browser'
export default () =>
<pre>
{cowsay.say({ text: 'hi there!' })}
</pre>
Examples
We bundle styled-jsx to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately do not support server-rendering and are JS-only.
export default () =>
<div>
Hello world
<p>scoped!</p>
<style jsx>{`
p {
color: blue;
}
div {
background: red;
}
@media (max-width: 600px) {
div {
background: blue;
}
}
`}</style>
<style global jsx>{`
body {
background: black;
}
`}</style>
</div>
Please see the styled-jsx documentation for more examples.
It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
export default () => <p style={{ color: 'red' }}>hi there</p>
To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own custom <Document>
component that wraps each page
Create a folder called static
in your project root directory. From your code you can then reference those files with /static/
URLs:
export default () => <img src="/static/my-image.png" />
Examples
We expose a built-in component for appending elements to the <head>
of the page.
import Head from 'next/head'
export default () =>
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
Note: The contents of <head>
get cleared upon unmounting the component, so make sure each page completely defines what it needs in <head>
, without making assumptions about what other pages added
Examples
When you need state, lifecycle hooks or initial data population you can export a React.Component
(instead of a stateless function, like shown above):
import React from 'react'
export default class extends React.Component {
static async getInitialProps({ req }) {
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
return { userAgent }
}
render() {
return (
<div>
Hello World {this.props.userAgent}
</div>
)
}
}
Notice that to load data when the page loads, we use getInitialProps
which is an async
static method. It can asynchronously fetch anything that resolves to a JavaScript plain Object
, which populates props
.
For the initial page load, getInitialProps
will execute on the server only. getInitialProps
will only be executed on the client when navigating to a different route via the Link
component or using the routing APIs.
Note: getInitialProps
can not be used in children components. Only in pages
.
If you are using some server only modules inside
getInitialProps
, make sure to import them properly. Otherwise, it'll slow down your app.
You can also define the getInitialProps
lifecycle method for stateless components:
const Page = ({ stars }) =>
<div>
Next stars: {stars}
</div>
Page.getInitialProps = async ({ req }) => {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Page
getInitialProps
receives a context object with the following properties:
pathname
- path section of URLquery
- query string section of URL parsed as an objectasPath
-String
of the actual path (including the query) shows in the browserreq
- HTTP request object (server only)res
- HTTP response object (server only)jsonPageRes
- Fetch Response object (client only)err
- Error object if any error is encountered during the rendering
Examples
Client-side transitions between routes can be enabled via a <Link>
component. Consider these two pages:
// pages/index.js
import Link from 'next/link'
export default () =>
<div>
Click{' '}
<Link href="/about">
<a>here</a>
</Link>{' '}
to read more
</div>
// pages/about.js
export default () => <p>Welcome to About!</p>
Note: use <Link prefetch>
for maximum performance, to link and prefetch in the background at the same time
Client-side routing behaves exactly like the browser:
- The component is fetched
- If it defines
getInitialProps
, data is fetched. If an error occurs,_error.js
is rendered - After 1 and 2 complete,
pushState
is performed and the new component rendered
Each top-level component receives a url
property with the following API:
pathname
-String
of the current path excluding the query stringquery
-Object
with the parsed query string. Defaults to{}
asPath
-String
of the actual path (including the query) shows in the browserpush(url, as=url)
- performs apushState
call with the given urlreplace(url, as=url)
- performs areplaceState
call with the given url
The second as
parameter for push
and replace
is an optional decoration of the URL. Useful if you configured custom routes on the server.
Examples
The component <Link>
can also receive an URL object and it will automatically format it to create the URL string.
// pages/index.js
import Link from 'next/link'
export default () =>
<div>
Click{' '}
<Link href={{ pathname: '/about', query: { name: 'Zeit' } }}>
<a>here</a>
</Link>{' '}
to read more
</div>
That will generate the URL string /about?name=Zeit
, you can use every property as defined in the Node.js URL module documentation.
The default behaviour for the <Link>
component is to push
a new url into the stack. You can use the replace
prop to prevent adding a new entry.
// pages/index.js
import Link from 'next/link'
export default () =>
<div>
Click{' '}
<Link href="/about" replace>
<a>here</a>
</Link>{' '}
to read more
</div>
<Link>
supports any component that supports the onClick
event. In case you don't provide an <a>
tag, it will only add the onClick
event handler and won't pass the href
property.
// pages/index.js
import Link from 'next/link'
export default () =>
<div>
Click{' '}
<Link href="/about">
<img src="/static/image.png" />
</Link>
</div>
If child is an <a>
tag and doesn't have a href attribute we specify it so that the repetition is not needed by the user. However, sometimes, you’ll want to pass an <a>
tag inside of a wrapper and the Link
won’t recognize it as a hyperlink, and, consequently, won’t transfer its href
to the child. In cases like that, you should define a boolean passHref
property to the Link
, forcing it to expose its href
property to the child.
import Link from 'next/link'
import Unexpected_A from 'third-library'
export default ({ href, name }) =>
<Link href={href} passHref>
<Unexpected_A>
{name}
</Unexpected_A>
</Link>
You can also do client-side page transitions using the next/router
import Router from 'next/router'
export default () =>
<div>
Click <span onClick={() => Router.push('/about')}>here</span> to read more
</div>
Above Router
object comes with the following API:
route
-String
of the current routepathname
-String
of the current path excluding the query stringquery
-Object
with the parsed query string. Defaults to{}
asPath
-String
of the actual path (including the query) shows in the browserpush(url, as=url)
- performs apushState
call with the given urlreplace(url, as=url)
- performs areplaceState
call with the given url
The second as
parameter for push
and replace
is an optional decoration of the URL. Useful if you configured custom routes on the server.
Note: in order to programmatically change the route without triggering navigation and component-fetching, use props.url.push
and props.url.replace
within a component
You can use an URL object the same way you use it in a <Link>
component to push
and replace
an url.
import Router from 'next/router'
const handler = () =>
Router.push({
pathname: '/about',
query: { name: 'Zeit' }
})
export default () =>
<div>
Click <span onClick={handler}>here</span> to read more
</div>
This uses of the same exact parameters as in the <Link>
component.
You can also listen to different events happening inside the Router. Here's a list of supported events:
routeChangeStart(url)
- Fires when a route starts to changerouteChangeComplete(url)
- Fires when a route changed completelyrouteChangeError(err, url)
- Fires when there's an error when changing routesbeforeHistoryChange(url)
- Fires just before changing the browser's historyappUpdated(nextRoute)
- Fires when switching pages and there's a new version of the app
Here
url
is the URL shown in the browser. If you callRouter.push(url, as)
(or similar), then the value ofurl
will beas
.
Here's how to properly listen to the router event routeChangeStart
:
Router.onRouteChangeStart = url => {
console.log('App is changing to: ', url)
}
If you no longer want to listen to that event, you can simply unset the event listener like this:
Router.onRouteChangeStart = null
If a route load is cancelled (for example by clicking two links rapidly in succession), routeChangeError
will fire. The passed err
will contained a cancelled
property set to true
.
Router.onRouteChangeError = (err, url) => {
if (err.cancelled) {
console.log(`Route to ${url} was cancelled!`)
}
}
If you change a route while in between a new deployment, we can't navigate the app via client side. We need to do a full browser navigation. We do it automatically for you.
But you can customize that via Route.onAppUpdated
event like this:
Router.onAppUpdated = nextUrl => {
// persist the local state
location.href = nextUrl
}
Examples
Shallow routing allows you to change the URL without running getInitialProps
. You'll receive the updated pathname
and the query
via the url
prop of the same page that's loaded, without losing state.
You can do this by invoking either Router.push
or Router.replace
with the shallow: true
option. Here's an example:
// Current URL is "/"
const href = '/?counter=10'
const as = href
Router.push(href, as, { shallow: true })
Now, the URL is updated to /?counter=10
. You can see the updated URL with this.props.url
inside the Component
.
You can watch for URL changes via componentWillReceiveProps
hook as shown below:
componentWillReceiveProps(nextProps) {
const { pathname, query } = nextProps.url
// fetch data based on the new query
}
NOTES:
Shallow routing works only for same page URL changes. For an example, let's assume we've another page called
about
, and you run this:Router.push('/about?counter=10', '/about?counter=10', { shallow: true })Since that's a new page, it'll unload the current page, load the new one and call
getInitialProps
even though we asked to do shallow routing.
Examples
If you want to access the router
object inside any component in your app, you can use the withRouter
Higher-Order Component. Here's how to use it:
import { withRouter } from 'next/router'
const ActiveLink = ({ children, router, href }) => {
const style = {
marginRight: 10,
color: router.pathname === href? 'red' : 'black'
}
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
return (
<a href={href} onClick={handleClick} style={style}>
{children}
</a>
)
}
export default withRouter(ActiveLink)
The above router
object comes with an API similar to next/router
.
(This is a production only feature)
Examples
Next.js has an API which allows you to prefetch pages.
Since Next.js server-renders your pages, this allows all the future interaction paths of your app to be instant. Effectively Next.js gives you the great initial download performance of a website, with the ahead-of-time download capabilities of an app. Read more.
With prefetching Next.js only downloads JS code. When the page is getting rendered, you may need to wait for the data.
You can add prefetch
prop to any <Link>
and Next.js will prefetch those pages in the background.
import Link from 'next/link'
// example header component
export default () =>
<nav>
<ul>
<li>
<Link prefetch href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link prefetch href="/about">
<a>About</a>
</Link>
</li>
<li>
<Link prefetch href="/contact">
<a>Contact</a>
</Link>
</li>
</ul>
</nav>
Most prefetching needs are addressed by <Link />
, but we also expose an imperative API for advanced usage:
import Router from 'next/router'
export default ({ url }) =>
<div>
<a onClick={() => setTimeout(() => url.pushTo('/dynamic'), 100)}>
A route transition will happen after 100ms
</a>
{// but we can prefetch it!
Router.prefetch('/dynamic')}
</div>
Examples
Typically you start your next server with next start
. It's possible, however, to start a server 100% programmatically in order to customize routes, use route patterns, etc
This example makes /a
resolve to ./pages/b
, and /b
resolve to ./pages/a
:
// This file doesn't not go through babel or webpack transformation.
// Make sure the syntax and sources this file requires are compatible with the current node version you are running
// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (pathname === '/a') {
app.render(req, res, '/b', query)
} else if (pathname === '/b') {
app.render(req, res, '/a', query)
} else {
handle(req, res, parsedUrl)
}
}).listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
The next
API is as follows:
next(path: string, opts: object)
-path
is where the Next project is locatednext(opts: object)
Supported options:
dev
(bool
) whether to launch Next.js in dev mode - defaultfalse
dir
(string
) where the Next project is located - default'.'
quiet
(bool
) Hide error messages containing server information - defaultfalse
conf
(object
) the same object you would use innext.config.js
- default{}
Then, change your start
script to NODE_ENV=production node server.js
.
Examples
Next.js supports TC39 dynamic import proposal for JavaScript. With that, you could import JavaScript modules (inc. React Components) dynamically and work with them.
You can think dynamic imports as another way to split your code into manageable chunks. Since Next.js supports dynamic imports with SSR, you could do amazing things with it.
Here are a few ways to use dynamic imports.
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(import('../components/hello'))
export default () =>
<div>
<Header />
<DynamicComponent />
<p>HOME PAGE is here!</p>
</div>
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
import('../components/hello2'),
{
loading: () => <p>...</p>
}
)
export default () =>
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), {
ssr: false
})
export default () =>
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
import dynamic from 'next/dynamic'
const HelloBundle = dynamic({
modules: props => {
const components = {
Hello1: import('../components/hello1'),
Hello2: import('../components/hello2')
}
// Add remove components based on props
return components
},
render: (props, { Hello1, Hello2 }) =>
<div>
<h1>
{props.title}
</h1>
<Hello1 />
<Hello2 />
</div>
})
export default () => <HelloBundle title="Dynamic Bundle" />
Pages in Next.js
skip the definition of the surrounding document's markup. For example, you never include <html>
, <body>
, etc. To override that default behavior, you must create a file at ./pages/_document.js
, where you can extend the Document
class:
// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage()
const styles = flush()
return { html, head, errorHtml, chunks, styles }
}
render() {
return (
<html>
<Head>
<style>{`body { margin: 0 } /* custom! */`}</style>
</Head>
<body className="custom_class">
{this.props.customValue}
<Main />
<NextScript />
</body>
</html>
)
}
}
The ctx
object is equivalent to the one received in all getInitialProps
hooks, with one addition:
renderPage
(Function
) a callback that executes the actual React rendering logic (synchronously). It's useful to decorate this function in order to support server-rendering wrappers like Aphrodite'srenderStatic
Note: React-components outside of <Main />
will not be initialised by the browser. If you need shared components in all your pages (like a menu or a toolbar), do not add application logic here, but take a look at this example.