Next.js is a minimalistic framework for server-rendered React applications.
Visit https://learnnextjs.com to get started with Next.js.
This is the documentation for our latest beta of version 3.0 which comes with static export and dynamic imports. For the documentation of the latest stable release, visit here.
- 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
How to use
Setup
Install it:
npm install next@beta react react-dom --save
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
Automatic code splitting
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>
)
CSS
Built-in CSS support
Examples
We bundle styled-jsx to provide support for isolated scoped CSS. The aim is to support "shadow CSS" resembling of 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.
CSS-in-JS
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
Static file serving (e.g.: images)
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" />
)
<head>
Populating 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
Fetching data and component lifecycle
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 }) {
return req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.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
- the actual url pathreq
- 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
Routing
<Link>
With 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.
With URL object
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.
Replace instead of push url
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>
)
onClick
Using a component that support <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> )