Commit 52ccc140 authored by Tim Neutkens's avatar Tim Neutkens

Merge branch 'canary'

# Conflicts:
#	examples/with-markdown/readme.md
#	lib/page-loader.js
#	package.json
#	server/build/plugins/pages-plugin.js
parents 67643e25 2a6557d6
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
language: "node_js", language: "node_js",
node_js: ["6"], node_js: ["6"],
cache: { cache: {
directories: ["node-modules"] directories: ["node_modules"]
}, },
before_install: [ before_install: [
"rm yarn.lock", "rm yarn.lock",
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
deploy: { deploy: {
provider: "npm", provider: "npm",
email: "leo@zeit.co", email: "leo@zeit.co",
tag: "canary",
api_key: { api_key: {
secure: secure:
"br9gLncKeLSoL7iOq0PXFeD1Gp3jRI8QMCSNIrGdZg/MuLeuwYPv36kmMgf7aGIfpjFLtU2/eVrOHSB+T5g1nKgOsqmWsfZE1tQYWph0//ookd/sj+IyxIx8nVLbUV/C4ctYOhX/efotRgNn56w5Av5hWc1IQLmW9mSN8ijrQnM+GzRI8QitiofeY2EP3N1eO8vC8E2oGkOsAdcypiX6lFG908zyWt7X2SD+iOsK2eAHjxoAEUdrxE5a8gTDhcTH6qnmtBs9rCeEKbO3JZjEy5dvccxlX3Nd+2GC1rckayk6o5L/zveTilsUx6Auqqbwn1dT5ffQuYsV4RPofs8IMrhnizc8y+OfUcCCpBJ4ia4w7N8FEP56TnRNTFoFBGJL5Y6NfeT0HHAlClxUWMG9pRGWGN+sskODDQ9FEntGZoqwV396ogs+3YhkxbY0AIr84QOctflsFcPtOgr/CoBeOsjbB+o9+Rlsqwlf3u3B7qhtU9eV6KcMfK4x9qW+2cwTllK+gD8S9wILx5BChkfx99g/7u/Rg1PCym64tTsDOBtqTVC2YCqeYYvjmpw4Vl3ofLrFsoNQnbmb6Q5+JSpOcJ/bEj7P/FuZdlU0fNV28tFhElu5caKhSCJz/avUlXG7NeveW1Ee8gjhURC4V/l4ryacyjA2vcDY/4RRkWtHNr4=" "br9gLncKeLSoL7iOq0PXFeD1Gp3jRI8QMCSNIrGdZg/MuLeuwYPv36kmMgf7aGIfpjFLtU2/eVrOHSB+T5g1nKgOsqmWsfZE1tQYWph0//ookd/sj+IyxIx8nVLbUV/C4ctYOhX/efotRgNn56w5Av5hWc1IQLmW9mSN8ijrQnM+GzRI8QitiofeY2EP3N1eO8vC8E2oGkOsAdcypiX6lFG908zyWt7X2SD+iOsK2eAHjxoAEUdrxE5a8gTDhcTH6qnmtBs9rCeEKbO3JZjEy5dvccxlX3Nd+2GC1rckayk6o5L/zveTilsUx6Auqqbwn1dT5ffQuYsV4RPofs8IMrhnizc8y+OfUcCCpBJ4ia4w7N8FEP56TnRNTFoFBGJL5Y6NfeT0HHAlClxUWMG9pRGWGN+sskODDQ9FEntGZoqwV396ogs+3YhkxbY0AIr84QOctflsFcPtOgr/CoBeOsjbB+o9+Rlsqwlf3u3B7qhtU9eV6KcMfK4x9qW+2cwTllK+gD8S9wILx5BChkfx99g/7u/Rg1PCym64tTsDOBtqTVC2YCqeYYvjmpw4Vl3ofLrFsoNQnbmb6Q5+JSpOcJ/bEj7P/FuZdlU0fNV28tFhElu5caKhSCJz/avUlXG7NeveW1Ee8gjhURC4V/l4ryacyjA2vcDY/4RRkWtHNr4="
......
...@@ -27,13 +27,18 @@ const commands = new Set([ ...@@ -27,13 +27,18 @@ const commands = new Set([
]) ])
let cmd = process.argv[2] let cmd = process.argv[2]
let args let args = []
let nodeArgs = []
if (new Set(['--version', '-v']).has(cmd)) { if (new Set(['--version', '-v']).has(cmd)) {
console.log(`next.js v${pkg.version}`) console.log(`next.js v${pkg.version}`)
process.exit(0) process.exit(0)
} }
if (new Set(process.argv).has('--inspect')) {
nodeArgs.push('--inspect')
}
if (new Set(['--help', '-h']).has(cmd)) { if (new Set(['--help', '-h']).has(cmd)) {
console.log(` console.log(`
Usage Usage
...@@ -61,7 +66,7 @@ process.env.NODE_ENV = process.env.NODE_ENV || defaultEnv ...@@ -61,7 +66,7 @@ process.env.NODE_ENV = process.env.NODE_ENV || defaultEnv
const bin = join(__dirname, 'next-' + cmd) const bin = join(__dirname, 'next-' + cmd)
const startProcess = () => { const startProcess = () => {
const proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }) const proc = spawn('node', [...nodeArgs, ...[bin], ...args], { stdio: 'inherit', customFds: [0, 1, 2] })
proc.on('close', (code, signal) => { proc.on('close', (code, signal) => {
if (code !== null) { if (code !== null) {
process.exit(code) process.exit(code)
......
# Build directory not writeable
#### Why This Error Occurred
The filesystem does not allow writing to the specified directory. A common cause for this error is starting a [custom server](https://github.com/zeit/next.js#custom-server-and-routing) in development mode on a production server, for example, [now.sh](https://zeit.co) which [doesn't allow you to write to the filesystem after your app is built](https://zeit.co/docs/deployment-types/node#file-system-specifications).
#### Possible Ways to Fix It
When using a custom server with a server file, for example called `server.js`, make sure you update the scripts key in `package.json` to:
```json
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
and the custom server starts Next in production mode when `NODE_ENV` is `production`
```js
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
```
### Useful Links
- [Custom Server documentation + examples](https://github.com/zeit/next.js#custom-server-and-routing)
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/active-class-name)
# activeClassName example
## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example active-class-name active-class-name-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/active-class-name
cd active-class-name
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
ReactRouter has a convenience property on the `Link` element to allow an author to set the _active_ className on a link. This example replicates that functionality using Next's own `Link`.
import { withRouter } from 'next/router'
import Link from 'next/link'
import React, { Children } from 'react'
const ActiveLink = ({ router, children, ...props }) => {
const child = Children.only(children)
let className = child.props.className || ''
if (router.pathname === props.href && props.activeClassName) {
className = `${className} ${props.activeClassName}`.trim()
}
delete props.activeClassName
return <Link {...props}>{React.cloneElement(child, { className })}</Link>
}
export default withRouter(ActiveLink)
import Link from './Link'
export default () => (
<nav>
<style jsx>{`
.active:after {
content: ' (current page)';
}
.nav-link {
text-decoration: none;
padding: 10px;
display: block;
}
`}</style>
<ul>
<li>
<Link activeClassName='active' href='/'>
<a className='nav-link home-link'>Home</a>
</Link>
</li>
<li>
<Link activeClassName='active' href='/about'>
<a className='nav-link'>About</a>
</Link>
</li>
</ul>
</nav>
)
{
"name": "active-class-name",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"author": "Remy Sharp <remy@leftlogic.com>",
"dependencies": {
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"license": "ISC"
}
import Nav from '../components/Nav'
export default () => (
<div>
<Nav />
<p>Hello, I'm About.js</p>
</div>
)
import Nav from '../components/Nav'
export default () => (
<div>
<Nav />
<p>Hello, I'm the home page</p>
</div>
)
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example basic-css basic-css-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/basic-css curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/basic-css
cd basic-css cd basic-css
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-express custom-server-express-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-express curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-express
cd custom-server-express cd custom-server-express
``` ```
......
...@@ -5,5 +5,6 @@ export default () => ( ...@@ -5,5 +5,6 @@ export default () => (
<ul> <ul>
<li><Link href='/b' as='/a'><a>a</a></Link></li> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<li><Link href='/a' as='/b'><a>b</a></Link></li> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<li><Link href='/posts/2'><a>post #2</a></Link></li>
</ul> </ul>
) )
import React, { Component } from 'react'
export default class extends Component {
static getInitialProps ({ query: { id } }) {
return { postId: id }
}
render () {
return <div>
<h1>My blog post #{this.props.postId}</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
}
}
...@@ -18,6 +18,10 @@ app.prepare() ...@@ -18,6 +18,10 @@ app.prepare()
return app.render(req, res, '/a', req.query) return app.render(req, res, '/a', req.query)
}) })
server.get('/posts/:id', (req, res) => {
return app.render(req, res, '/posts', { id: req.params.id })
})
server.get('*', (req, res) => { server.get('*', (req, res) => {
return handle(req, res) return handle(req, res)
}) })
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-fastify custom-server-fastify-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-fastify curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-fastify
cd custom-server-fastify cd custom-server-fastify
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-hapi custom-server-hapi-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-hapi curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-hapi
cd custom-server-hapi cd custom-server-hapi
``` ```
......
const pathWrapper = (app, pathName, opts) => ({ raw, query }, hapiReply) => const { parse } = require('url')
app.renderToHTML(raw.req, raw.res, pathName, query, opts)
.then(hapiReply)
const defaultHandlerWrapper = app => { const nextHandlerWrapper = app => {
const handler = app.getRequestHandler() const handler = app.getRequestHandler()
return ({ raw, url }, hapiReply) => return async ({ raw, url }, h) => {
handler(raw.req, raw.res, url) await handler(raw.req, raw.res, url)
.then(() => { return h.close
hapiReply.close(false) }
})
} }
module.exports = { pathWrapper, defaultHandlerWrapper } const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }) => {
const { pathname, query } = parse(url, true)
return app.renderToHTML(req, res, pathname, query)
}
const pathWrapper = (app, pathName, opts) => async ({ raw, query, params }) => {
return app.renderToHTML(raw.req, raw.res, pathName, { ...query, ...params }, opts)
}
module.exports = { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper }
...@@ -7,11 +7,9 @@ ...@@ -7,11 +7,9 @@
"start": "NODE_ENV=production node server.js" "start": "NODE_ENV=production node server.js"
}, },
"dependencies": { "dependencies": {
"hapi": "^16.1.0", "hapi": "^17.1.1",
"next": "latest", "next": "latest",
"react": "^16.0.0", "react": "^16.0.0",
"react-dom": "^16.0.0", "react-dom": "^16.0.0"
"good": "^7.1.0",
"good-console": "^6.2.0"
} }
} }
const next = require('next') const next = require('next')
const Hapi = require('hapi') const Hapi = require('hapi')
const Good = require('good') const { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper } = require('./next-wrapper')
const { pathWrapper, defaultHandlerWrapper } = require('./next-wrapper')
const port = parseInt(process.env.PORT, 10) || 3000 const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production' const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev }) const app = next({ dev })
const server = new Hapi.Server() const server = new Hapi.Server({
port
// add request logging (optional) })
const pluginOptions = [
{
register: Good,
options: {
reporters: {
console: [{
module: 'good-console'
}, 'stdout']
}
}
}
]
app.prepare() app
.then(() => { .prepare()
server.connection({ port }) .then(async () => {
server.register(pluginOptions) server.route({
.then(() => { method: 'GET',
server.route({ path: '/a',
method: 'GET', handler: pathWrapper(app, '/a')
path: '/a', })
handler: pathWrapper(app, '/a')
})
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/b', path: '/b',
handler: pathWrapper(app, '/b') handler: pathWrapper(app, '/b')
}) })
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/{p*}', /* catch all route */ path: '/_next/{p*}', /* next specific routes */
handler: defaultHandlerWrapper(app) handler: nextHandlerWrapper(app)
}) })
server.start().catch(error => { server.route({
console.log('Error starting server') method: 'GET',
console.log(error) path: '/{p*}', /* catch all route */
}).then(() => { handler: defaultHandlerWrapper(app)
console.log(`> Ready on http://localhost:${port}`)
})
}) })
try {
await server.start()
console.log(`> Ready on http://localhost:${port}`)
} catch (error) {
console.log('Error starting server')
console.log(error)
}
}) })
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-koa custom-server-koa-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-koa curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-koa
cd custom-server-koa cd custom-server-koa
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-micro custom-server-micro-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server-micro curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-micro
cd custom-server-micro cd custom-server-micro
``` ```
......
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-nodemon)
# Custom server with Nodemon example
## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server-nodemon custom-server-nodemon-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-nodemon
cd custom-server-nodemon
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
The example shows how you can apply [Nodemon](https://nodemon.io/) to a custom server to have live reload of the server code without being affected by the Next.js universal code.
{
"watch": ["server/**/*.js"]
}
{
"scripts": {
"dev": "nodemon server/index.js",
"build": "next build",
"start": "NODE_ENV=production node server/index.js"
},
"dependencies": {
"next": "^4.1.4",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"nodemon": "^1.12.1"
}
}
import React from 'react'
export default () => <div>a</div>
import React from 'react'
export default () => <div>b</div>
import React from 'react'
import Link from 'next/link'
export default () => (
<ul>
<li><Link href='/b' as='/a'><a>a</a></Link></li>
<li><Link href='/a' as='/b'><a>b</a></Link></li>
</ul>
)
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
createServer((req, res) => {
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(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example custom-server custom-server-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
cd custom-server cd custom-server
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example data-fetch data-fetch-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/data-fetch curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/data-fetch
cd data-fetch cd data-fetch
``` ```
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"isomorphic-fetch": "^2.2.1", "isomorphic-unfetch": "^2.0.0",
"next": "latest", "next": "latest",
"react": "^16.0.0", "react": "^16.0.0",
"react-dom": "^16.0.0" "react-dom": "^16.0.0"
......
import React from 'react' import React from 'react'
import Link from 'next/link' import Link from 'next/link'
import 'isomorphic-fetch' import 'isomorphic-unfetch'
export default class MyPage extends React.Component { export default class MyPage extends React.Component {
static async getInitialProps () { static async getInitialProps () {
......
import React from 'react' import React from 'react'
import Link from 'next/link' import Link from 'next/link'
import 'isomorphic-fetch' import 'isomorphic-unfetch'
export default class MyPage extends React.Component { export default class MyPage extends React.Component {
static async getInitialProps () { static async getInitialProps () {
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example form-handler form-handler-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/form-handler curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/form-handler
cd form-handler cd form-handler
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example head-elements head-elements-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/head-elements curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/head-elements
cd head-elements cd head-elements
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example hello-world hello-world-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/hello-world curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/hello-world
cd hello-world cd hello-world
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example layout-component layout-component-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/layout-component curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/layout-component
cd layout-component cd layout-component
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example nested-components nested-components-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/nested-components curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/nested-components
cd nested-components cd nested-components
``` ```
......
# Hello World example
## Only client render for external dependencies
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/only-client-render-external-dependencies
cd only-client-render-external-dependencies
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example shows how to use an external dependency that only allows client-render.
\ No newline at end of file
{
"name": "only-client-render-external-dependencies",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"recharts": "^1.0.0-beta.0"
},
"license": "ISC"
}
import React from 'react'
let LineChart
let Line
class Chart extends React.Component {
constructor () {
super()
this.state = {
chart: false,
data: [
{name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
}
}
componentDidMount () {
LineChart = require('recharts').LineChart
Line = require('recharts').Line
this.setState({
chart: true
})
}
render () {
return (
<div>
<h1>Another chart</h1>
{this.state.chart &&
<LineChart width={400} height={400} data={this.state.data}>
<Line type='monotone' dataKey='uv' stroke='#8884d8' />
</LineChart>
}
</div>
)
}
}
export default Chart
import React from 'react'
import Link from 'next/link'
let LineChart
let Line
class Index extends React.Component {
constructor () {
super()
this.state = {
chart: false,
data: [
{name: 'Page A', uv: 1000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
}
}
componentDidMount () {
LineChart = require('recharts').LineChart
Line = require('recharts').Line
this.setState({
chart: true
})
}
render () {
return (
<div>
<h1>Chart</h1>
<Link href='/chart'><a>Go to another chart</a></Link>
{this.state.chart &&
<LineChart width={400} height={400} data={this.state.data}>
<Line type='monotone' dataKey='uv' stroke='#8884d8' />
</LineChart>
}
</div>
)
}
}
export default Index
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example page-transitions page-transitions-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/page-transitions curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/page-transitions
cd page-transitions cd page-transitions
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example parameterized-routing parameterized-routing-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/parameterized-routing curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/parameterized-routing
cd parameterized-routing cd parameterized-routing
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example progressive-render progressive-render-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/progressive-render curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/progressive-render
cd progressive-render cd progressive-render
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example root-static-files root-static-files-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
cd custom-server cd custom-server
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example shared-modules shared-modules-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/shared-modules curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/shared-modules
cd shared-modules cd shared-modules
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example ssr-caching ssr-caching-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/ssr-caching curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/ssr-caching
cd ssr-caching cd ssr-caching
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example svg-components svg-components-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/svg-components curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/svg-components
cd svg-components cd svg-components
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example using-inferno using-inferno-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-inferno curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-inferno
cd using-inferno cd using-inferno
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example using-preact using-preact-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-preact curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-preact
cd using-preact cd using-preact
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example using-router using-router-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-router curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-router
cd using-router cd using-router
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example using-with-router using-with-router-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/using-with-router curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-with-router
cd using-with-router cd using-with-router
``` ```
......
...@@ -2,10 +2,21 @@ ...@@ -2,10 +2,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-absolute-imports with-absolute-imports-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-absolute-import curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-absolute-import
cd with-absolute-import cd with-absolute-import
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-algolia-react-instantsearch curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-algolia-react-instantsearch
cd with-algolia-react-instantsearch cd with-algolia-react-instantsearch
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-amp with-amp-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js.git): Download the example [or clone the repo](https://github.com/zeit/next.js.git):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-amp curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-amp
cd with-amp cd with-amp
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-ant-design with-ant-design-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-ant-design curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-ant-design
cd with-ant-design cd with-ant-design
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-antd-mobile with-antd-mobile-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-antd-mobile curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-antd-mobile
cd with-antd-mobile cd with-antd-mobile
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-aphrodite with-aphrodite-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-aphrodite curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-aphrodite
cd with-aphrodite cd with-aphrodite
``` ```
......
...@@ -3,10 +3,21 @@ ...@@ -3,10 +3,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-apollo-and-redux with-apollo-and-redux-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo-and-redux curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo-and-redux
cd with-apollo-and-redux cd with-apollo-and-redux
``` ```
......
...@@ -10,6 +10,10 @@ export default ({ pathname }) => ( ...@@ -10,6 +10,10 @@ export default ({ pathname }) => (
<a className={pathname === '/about' && 'is-active'}>About</a> <a className={pathname === '/about' && 'is-active'}>About</a>
</Link> </Link>
<Link prefetch href='/blog'>
<a className={pathname === '/blog' && 'is-active'}>Blog</a>
</Link>
<style jsx>{` <style jsx>{`
header { header {
margin-bottom: 25px; margin-bottom: 25px;
......
import React from 'react'
import { gql, graphql } from 'react-apollo'
import PostUpvoter from './PostUpvoter'
function Post ({ id, data: { loading, error, Post } }) {
return (
<section>
<div key={Post.id}>
<h1>{Post.title}</h1>
<p>ID: {Post.id}<br />URL: {Post.url}</p>
<PostUpvoter id={Post.id} votes={Post.votes} />
</div>
</section>
)
}
const post = gql`
query post($id: ID!) {
Post(id: $id) {
id
title
votes
url
createdAt
}
}
`
// The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList)
// Tip: ownProps is parent component's props
export default graphql(post, {
options: (ownProps) => {
return {
variables: {
id: ownProps.id
}
}
}
})(Post)
import { gql, graphql } from 'react-apollo' import { gql, graphql } from 'react-apollo'
import ErrorMessage from './ErrorMessage' import ErrorMessage from './ErrorMessage'
import PostUpvoter from './PostUpvoter' import PostUpvoter from './PostUpvoter'
import Link from 'next/link'
const POSTS_PER_PAGE = 10 const POSTS_PER_PAGE = 10
...@@ -15,7 +16,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -15,7 +16,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
<li key={post.id}> <li key={post.id}>
<div> <div>
<span>{index + 1}. </span> <span>{index + 1}. </span>
<a href={post.url}>{post.title}</a> <Link href={{ pathname: '/blog/' + post.id }}><a>{post.title}</a></Link>
<PostUpvoter id={post.id} votes={post.votes} /> <PostUpvoter id={post.id} votes={post.votes} />
</div> </div>
</li> </li>
......
import { ApolloClient, createNetworkInterface } from 'react-apollo' import { ApolloClient, createNetworkInterface } from 'react-apollo'
import fetch from 'isomorphic-fetch' import fetch from 'isomorphic-unfetch'
let apolloClient = null let apolloClient = null
......
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
"name": "with-apollo-and-redux", "name": "with-apollo-and-redux",
"version": "2.0.0", "version": "2.0.0",
"scripts": { "scripts": {
"dev": "next", "dev": "node server.js",
"build": "next build", "build": "next build",
"start": "next start" "start": "NODE_ENV=production node server.js"
}, },
"dependencies": { "dependencies": {
"graphql": "^0.9.3", "graphql": "^0.9.3",
"isomorphic-fetch": "^2.2.1", "isomorphic-unfetch": "^2.0.0",
"next": "latest", "next": "latest",
"next-routes": "^1.1.0",
"prop-types": "^15.5.8", "prop-types": "^15.5.8",
"react": "^16.0.0", "react": "^16.0.0",
"react-apollo": "^1.1.3", "react-apollo": "^1.1.3",
......
import App from '../../components/App'
import Header from '../../components/Header'
import Post from '../../components/Post'
import withData from '../../lib/withData'
export default withData((props) => (
<App>
<Header pathname={props.url.pathname} />
<Post id={props.url.query.id} />
</App>
))
import App from '../../components/App'
import Header from '../../components/Header'
import Submit from '../../components/Submit'
import PostList from '../../components/PostList'
import withData from '../../lib/withData'
export default withData((props) => (
<App>
<Header pathname={props.url.pathname} />
<Submit />
<PostList />
</App>
))
import App from '../components/App' import App from '../components/App'
import Header from '../components/Header' import Header from '../components/Header'
import Submit from '../components/Submit'
import PostList from '../components/PostList'
import withData from '../lib/withData' import withData from '../lib/withData'
export default withData((props) => ( export default withData((props) => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header pathname={props.url.pathname} />
<Submit /> <h1>Welcome Home.</h1>
<PostList />
</App> </App>
)) ))
/**
* server.js
*
* You can use the default server.js by simply running `next`,
* but a custom one is required to do paramaterized urls like
* blog/:slug.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BENEVOLENT WEB LLC BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const {createServer} = require('http')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
/**
* Parameterized Routing with next-route
*
* Benefits: Less code, and easily handles complex url structures
*/
const routes = require('next-routes')()
routes.add('blog/entry', '/blog/:id')
const handler = routes.getRequestHandler(app)
app.prepare().then(() => {
createServer(handler)
.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
...@@ -7,10 +7,21 @@ https://next-with-apollo-auth.now.sh ...@@ -7,10 +7,21 @@ https://next-with-apollo-auth.now.sh
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-apollo-auth with-apollo-auth-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo-auth curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo-auth
cd with-apollo-auth cd with-apollo-auth
``` ```
......
import { ApolloClient, createNetworkInterface } from 'react-apollo' import { ApolloClient } from 'apollo-client'
import fetch from 'isomorphic-fetch' import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { setContext } from 'apollo-link-context'
import fetch from 'isomorphic-unfetch'
let apolloClient = null let apolloClient = null
...@@ -9,25 +12,26 @@ if (!process.browser) { ...@@ -9,25 +12,26 @@ if (!process.browser) {
} }
function create (initialState, { getToken }) { function create (initialState, { getToken }) {
const networkInterface = createNetworkInterface({ const httpLink = createHttpLink({
uri: 'https://api.graph.cool/simple/v1/cj3h80ffbllm20162alevpcby' uri: 'https://api.graph.cool/simple/v1/cj5geu3slxl7t0127y8sity9r',
credentials: 'same-origin'
}) })
networkInterface.use([{ const authLink = setContext((_, { headers }) => {
applyMiddleware (req, next) { const token = getToken()
if (!req.options.headers) { return {
req.options.headers = {} // Create the header object if needed. headers: {
...headers,
authorization: token ? `Bearer ${token}` : null
} }
const token = getToken()
req.options.headers.authorization = token ? `Bearer ${token}` : null
next()
} }
}]) })
return new ApolloClient({ return new ApolloClient({
initialState, connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
networkInterface link: authLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState || {})
}) })
} }
...@@ -44,4 +48,4 @@ export default function initApollo (initialState, options) { ...@@ -44,4 +48,4 @@ export default function initApollo (initialState, options) {
} }
return apolloClient return apolloClient
} }
\ No newline at end of file
...@@ -2,13 +2,14 @@ import React from 'react' ...@@ -2,13 +2,14 @@ import React from 'react'
import cookie from 'cookie' import cookie from 'cookie'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { ApolloProvider, getDataFromTree } from 'react-apollo' import { ApolloProvider, getDataFromTree } from 'react-apollo'
import Head from 'next/head'
import initApollo from './initApollo' import initApollo from './initApollo'
function parseCookies (ctx = {}, options = {}) { function parseCookies(context = {}, options = {}) {
return cookie.parse( return cookie.parse(
ctx.req && ctx.req.headers.cookie context.req && context.req.headers.cookie
? ctx.req.headers.cookie ? context.req.headers.cookie
: document.cookie, : document.cookie,
options options
) )
...@@ -21,7 +22,7 @@ export default ComposedComponent => { ...@@ -21,7 +22,7 @@ export default ComposedComponent => {
serverState: PropTypes.object.isRequired serverState: PropTypes.object.isRequired
} }
static async getInitialProps (context) { static async getInitialProps(context) {
let serverState = {} let serverState = {}
// Setup a server-side one-time-use apollo client for initial props and // Setup a server-side one-time-use apollo client for initial props and
...@@ -46,30 +47,32 @@ export default ComposedComponent => { ...@@ -46,30 +47,32 @@ export default ComposedComponent => {
} }
// Provide the `url` prop data in case a graphql query uses it // Provide the `url` prop data in case a graphql query uses it
const url = {query: context.query, pathname: context.pathname} const url = { query: context.query, pathname: context.pathname }
try {
// Run all graphql queries // Run all GraphQL queries
const app = ( const app = (
<ApolloProvider client={apollo}> <ApolloProvider client={apollo}>
<ComposedComponent url={url} {...composedInitialProps} /> <ComposedComponent url={url} {...composedInitialProps} />
</ApolloProvider> </ApolloProvider>
) )
await getDataFromTree(app, { await getDataFromTree(app, {
router: { router: {
query: context.query, query: context.query,
pathname: context.pathname, pathname: context.pathname,
asPath: context.asPath asPath: context.asPath
} }
}) })
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error
}
// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
// Extract query data from the Apollo's store // Extract query data from the Apollo's store
const state = apollo.getInitialState() serverState = apollo.cache.extract()
serverState = {
apollo: { // Make sure to only include Apollo's data state
data: state.data
}
}
} }
return { return {
...@@ -78,7 +81,7 @@ export default ComposedComponent => { ...@@ -78,7 +81,7 @@ export default ComposedComponent => {
} }
} }
constructor (props) { constructor(props) {
super(props) super(props)
// Note: Apollo should never be used on the server side beyond the initial // Note: Apollo should never be used on the server side beyond the initial
// render within `getInitialProps()` above (since the entire prop tree // render within `getInitialProps()` above (since the entire prop tree
...@@ -89,7 +92,7 @@ export default ComposedComponent => { ...@@ -89,7 +92,7 @@ export default ComposedComponent => {
}) })
} }
render () { render() {
return ( return (
<ApolloProvider client={this.apollo}> <ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} /> <ComposedComponent {...this.props} />
...@@ -97,4 +100,4 @@ export default ComposedComponent => { ...@@ -97,4 +100,4 @@ export default ComposedComponent => {
) )
} }
} }
} }
\ No newline at end of file
...@@ -10,13 +10,15 @@ ...@@ -10,13 +10,15 @@
"test": "NODE_ENV=test ava" "test": "NODE_ENV=test ava"
}, },
"dependencies": { "dependencies": {
"apollo-client-preset": "1.0.2",
"apollo-link-context": "1.0.0",
"cookie": "^0.3.1", "cookie": "^0.3.1",
"graphql": "^0.9.3", "graphql": "0.11.7",
"isomorphic-fetch": "^2.2.1", "isomorphic-unfetch": "^2.0.0",
"next": "latest", "next": "latest",
"prop-types": "^15.5.10", "prop-types": "^15.5.10",
"react": "^16.0.0", "react": "^16.0.0",
"react-apollo": "^1.1.3", "react-apollo": "2.0.0",
"react-dom": "^16.0.0" "react-dom": "^16.0.0"
}, },
"devDependencies": { "devDependencies": {
......
...@@ -7,10 +7,21 @@ https://next-with-apollo.now.sh ...@@ -7,10 +7,21 @@ https://next-with-apollo.now.sh
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-apollo with-apollo-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-apollo curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo
cd with-apollo cd with-apollo
``` ```
......
...@@ -3,14 +3,16 @@ export default ({ children }) => ( ...@@ -3,14 +3,16 @@ export default ({ children }) => (
{children} {children}
<style jsx global>{` <style jsx global>{`
* { * {
font-family: Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif; font-family: Menlo, Monaco, 'Lucida Console', 'Liberation Mono',
'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New',
monospace, serif;
} }
body { body {
margin: 0; margin: 0;
padding: 25px 50px; padding: 25px 50px;
} }
a { a {
color: #22BAD9; color: #22bad9;
} }
p { p {
font-size: 14px; font-size: 14px;
...@@ -22,15 +24,15 @@ export default ({ children }) => ( ...@@ -22,15 +24,15 @@ export default ({ children }) => (
} }
button { button {
align-items: center; align-items: center;
background-color: #22BAD9; background-color: #22bad9;
border: 0; border: 0;
color: white; color: white;
display: flex; display: flex;
padding: 5px 7px; padding: 5px 7px;
} }
button:active { button:active {
background-color: #1B9DB7; background-color: #1b9db7;
transition: background-color .3s transition: background-color 0.3s;
} }
button:focus { button:focus {
outline: none; outline: none;
......
export default ({message}) => ( export default ({ message }) => (
<aside> <aside>
{message} {message}
<style jsx>{` <style jsx>{`
......
...@@ -3,13 +3,11 @@ import Link from 'next/link' ...@@ -3,13 +3,11 @@ import Link from 'next/link'
export default ({ pathname }) => ( export default ({ pathname }) => (
<header> <header>
<Link prefetch href='/'> <Link prefetch href='/'>
<a className={pathname === '/' && 'is-active'}>Home</a> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link> </Link>
<Link prefetch href='/about'> <Link prefetch href='/about'>
<a className={pathname === '/about' && 'is-active'}>About</a> <a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link> </Link>
<style jsx>{` <style jsx>{`
header { header {
margin-bottom: 25px; margin-bottom: 25px;
......
...@@ -5,14 +5,17 @@ import PostUpvoter from './PostUpvoter' ...@@ -5,14 +5,17 @@ import PostUpvoter from './PostUpvoter'
const POSTS_PER_PAGE = 10 const POSTS_PER_PAGE = 10
function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMorePosts }) { function PostList ({
data: { loading, error, allPosts, _allPostsMeta },
loadMorePosts
}) {
if (error) return <ErrorMessage message='Error loading posts.' /> if (error) return <ErrorMessage message='Error loading posts.' />
if (allPosts && allPosts.length) { if (allPosts && allPosts.length) {
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
<section> <section>
<ul> <ul>
{allPosts.map((post, index) => {allPosts.map((post, index) => (
<li key={post.id}> <li key={post.id}>
<div> <div>
<span>{index + 1}. </span> <span>{index + 1}. </span>
...@@ -20,9 +23,16 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -20,9 +23,16 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
<PostUpvoter id={post.id} votes={post.votes} /> <PostUpvoter id={post.id} votes={post.votes} />
</div> </div>
</li> </li>
)} ))}
</ul> </ul>
{areMorePosts ? <button onClick={() => loadMorePosts()}> {loading ? 'Loading...' : 'Show More'} </button> : ''} {areMorePosts ? (
<button onClick={() => loadMorePosts()}>
{' '}
{loading ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{` <style jsx>{`
section { section {
padding-bottom: 20px; padding-bottom: 20px;
...@@ -55,7 +65,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -55,7 +65,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
border-style: solid; border-style: solid;
border-width: 6px 4px 0 4px; border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent; border-color: #ffffff transparent transparent transparent;
content: ""; content: '';
height: 0; height: 0;
margin-right: 5px; margin-right: 5px;
width: 0; width: 0;
...@@ -67,7 +77,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore ...@@ -67,7 +77,7 @@ function PostList ({ data: { loading, error, allPosts, _allPostsMeta }, loadMore
return <div>Loading</div> return <div>Loading</div>
} }
const allPosts = gql` export const allPosts = gql`
query allPosts($first: Int!, $skip: Int!) { query allPosts($first: Int!, $skip: Int!) {
allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) { allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) {
id id
...@@ -75,21 +85,22 @@ const allPosts = gql` ...@@ -75,21 +85,22 @@ const allPosts = gql`
votes votes
url url
createdAt createdAt
}, }
_allPostsMeta { _allPostsMeta {
count count
} }
} }
` `
export const allPostsQueryVars = {
skip: 0,
first: POSTS_PER_PAGE
}
// The `graphql` wrapper executes a GraphQL query and makes the results // The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList) // available on the `data` prop of the wrapped component (PostList)
export default graphql(allPosts, { export default graphql(allPosts, {
options: { options: {
variables: { variables: allPostsQueryVars
skip: 0,
first: POSTS_PER_PAGE
}
}, },
props: ({ data }) => ({ props: ({ data }) => ({
data, data,
......
...@@ -20,7 +20,7 @@ function PostUpvoter ({ upvote, votes, id }) { ...@@ -20,7 +20,7 @@ function PostUpvoter ({ upvote, votes, id }) {
border-color: transparent transparent #000000 transparent; border-color: transparent transparent #000000 transparent;
border-style: solid; border-style: solid;
border-width: 0 4px 6px 4px; border-width: 0 4px 6px 4px;
content: ""; content: '';
height: 0; height: 0;
margin-right: 5px; margin-right: 5px;
width: 0; width: 0;
...@@ -42,16 +42,17 @@ const upvotePost = gql` ...@@ -42,16 +42,17 @@ const upvotePost = gql`
export default graphql(upvotePost, { export default graphql(upvotePost, {
props: ({ ownProps, mutate }) => ({ props: ({ ownProps, mutate }) => ({
upvote: (id, votes) => mutate({ upvote: (id, votes) =>
variables: { id, votes }, mutate({
optimisticResponse: { variables: { id, votes },
__typename: 'Mutation', optimisticResponse: {
updatePost: { __typename: 'Mutation',
__typename: 'Post', updatePost: {
id: ownProps.id, __typename: 'Post',
votes: ownProps.votes + 1 id: ownProps.id,
votes: ownProps.votes + 1
}
} }
} })
})
}) })
})(PostUpvoter) })(PostUpvoter)
import { graphql } from 'react-apollo' import { graphql } from 'react-apollo'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import { allPosts, allPostsQueryVars } from './PostList'
function Submit ({ createPost }) { function Submit ({ createPost }) {
function handleSubmit (e) { function handleSubmit (event) {
e.preventDefault() event.preventDefault()
let title = e.target.elements.title.value const form = event.target
let url = e.target.elements.url.value
if (title === '' || url === '') { const formData = new window.FormData(form)
window.alert('Both fields are required.') createPost(formData.get('title'), formData.get('url'))
return false
}
// prepend http if missing from url
if (!url.match(/^[a-zA-Z]+:\/\//)) {
url = `http://${url}`
}
createPost(title, url) form.reset()
// reset form
e.target.elements.title.value = ''
e.target.elements.url.value = ''
} }
return ( return (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<h1>Submit</h1> <h1>Submit</h1>
<input placeholder='title' name='title' /> <input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' /> <input placeholder='url' name='url' type='url' required />
<button type='submit'>Submit</button> <button type='submit'>Submit</button>
<style jsx>{` <style jsx>{`
form { form {
...@@ -63,17 +52,23 @@ const createPost = gql` ...@@ -63,17 +52,23 @@ const createPost = gql`
export default graphql(createPost, { export default graphql(createPost, {
props: ({ mutate }) => ({ props: ({ mutate }) => ({
createPost: (title, url) => mutate({ createPost: (title, url) =>
variables: { title, url }, mutate({
updateQueries: { variables: { title, url },
allPosts: (previousResult, { mutationResult }) => { update: (proxy, { data: { createPost } }) => {
const newPost = mutationResult.data.createPost const data = proxy.readQuery({
return Object.assign({}, previousResult, { query: allPosts,
// Append the new post variables: allPostsQueryVars
allPosts: [newPost, ...previousResult.allPosts] })
proxy.writeQuery({
query: allPosts,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
}) })
} }
} })
})
}) })
})(Submit) })(Submit)
import { ApolloClient } from 'apollo-client' import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http' import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory' import { InMemoryCache } from 'apollo-cache-inmemory'
import fetch from 'isomorphic-fetch' import fetch from 'isomorphic-unfetch'
let apolloClient = null let apolloClient = null
...@@ -10,21 +10,19 @@ if (!process.browser) { ...@@ -10,21 +10,19 @@ if (!process.browser) {
global.fetch = fetch global.fetch = fetch
} }
function create (initialState) { function create(initialState) {
return new ApolloClient({ return new ApolloClient({
connectToDevTools: process.browser, connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
link: new HttpLink({ link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute) uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
opts: { credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers`
credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers`
}
}), }),
cache: new InMemoryCache().restore(initialState || {}), cache: new InMemoryCache().restore(initialState || {})
}) })
} }
export default function initApollo (initialState) { export default function initApollo(initialState) {
// Make sure to create a new client for every server-side request so that data // Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad) // isn't shared between connections (which would be bad)
if (!process.browser) { if (!process.browser) {
......
...@@ -5,19 +5,26 @@ import Head from 'next/head' ...@@ -5,19 +5,26 @@ import Head from 'next/head'
import initApollo from './initApollo' import initApollo from './initApollo'
// Gets the display name of a JSX component for dev tools // Gets the display name of a JSX component for dev tools
function getComponentDisplayName (Component) { function getComponentDisplayName(Component) {
return Component.displayName || Component.name || 'Unknown' return Component.displayName || Component.name || 'Unknown'
} }
export default ComposedComponent => { export default ComposedComponent => {
return class WithData extends React.Component { return class WithData extends React.Component {
static displayName = `WithData(${getComponentDisplayName(ComposedComponent)})` static displayName = `WithData(${getComponentDisplayName(
ComposedComponent
)})`
static propTypes = { static propTypes = {
serverState: PropTypes.object.isRequired serverState: PropTypes.object.isRequired
} }
static async getInitialProps (ctx) { static async getInitialProps(ctx) {
let serverState = {} // Initial serverState with apollo (empty)
let serverState = {
apollo: {
data: {}
}
}
// Evaluate the composed component's getInitialProps() // Evaluate the composed component's getInitialProps()
let composedInitialProps = {} let composedInitialProps = {}
...@@ -30,7 +37,7 @@ export default ComposedComponent => { ...@@ -30,7 +37,7 @@ export default ComposedComponent => {
if (!process.browser) { if (!process.browser) {
const apollo = initApollo() const apollo = initApollo()
// Provide the `url` prop data in case a GraphQL query uses it // Provide the `url` prop data in case a GraphQL query uses it
const url = {query: ctx.query, pathname: ctx.pathname} const url = { query: ctx.query, pathname: ctx.pathname }
try { try {
// Run all GraphQL queries // Run all GraphQL queries
await getDataFromTree( await getDataFromTree(
...@@ -61,12 +68,12 @@ export default ComposedComponent => { ...@@ -61,12 +68,12 @@ export default ComposedComponent => {
} }
} }
constructor (props) { constructor(props) {
super(props) super(props)
this.apollo = initApollo(this.props.serverState.apollo.data) this.apollo = initApollo(this.props.serverState.apollo.data)
} }
render () { render() {
return ( return (
<ApolloProvider client={this.apollo}> <ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} /> <ComposedComponent {...this.props} />
......
...@@ -7,16 +7,16 @@ ...@@ -7,16 +7,16 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"apollo-client-preset": "^1.0.1", "apollo-client-preset": "1.0.4",
"graphql": "^0.11.7", "graphql": "0.11.7",
"graphql-anywhere": "^3.1.0", "graphql-anywhere": "4.0.2",
"graphql-tag": "^2.5.0", "graphql-tag": "2.5.0",
"isomorphic-fetch": "^2.2.1", "isomorphic-unfetch": "2.0.0",
"next": "latest", "next": "latest",
"prop-types": "^15.5.8", "prop-types": "15.6.0",
"react": "^16.0.0", "react": "16.2.0",
"react-apollo": "^2.0.0", "react-apollo": "2.0.1",
"react-dom": "^16.0.0" "react-dom": "16.2.0"
}, },
"author": "", "author": "",
"license": "ISC" "license": "ISC"
......
import App from '../components/App' import App from '../components/App'
import Header from '../components/Header' import Header from '../components/Header'
export default (props) => ( export default props => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header pathname={props.url.pathname} />
<article> <article>
<h1>The Idea Behind This Example</h1> <h1>The Idea Behind This Example</h1>
<p> <p>
<a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that
allows you to easily query the exact data you need from a GraphQL
server. In addition to fetching and mutating data, Apollo analyzes your
queries and their results to construct a client-side cache of your data,
which is kept up to date as further queries and mutations are run,
fetching more results from the server.
</p> </p>
<p> <p>
In this simple example, we integrate Apollo seamlessly with <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages inside a <a href='https://facebook.github.io/react/docs/higher-order-components.html'>higher-order component (HOC)</a>. Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application. In this simple example, we integrate Apollo seamlessly with{' '}
<a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages
inside a{' '}
<a href='https://facebook.github.io/react/docs/higher-order-components.html'>
higher-order component (HOC)
</a>. Using the HOC pattern we're able to pass down a central store of
query result data created by Apollo into our React component hierarchy
defined inside each page of our Next application.
</p> </p>
<p> <p>
On initial page load, while on the server and inside getInitialProps, we invoke the Apollo method, <a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'>getDataFromTree</a>. This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. On initial page load, while on the server and inside getInitialProps, we
invoke the Apollo method,{' '}
<a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'>
getDataFromTree
</a>. This method returns a promise; at the point in which the promise
resolves, our Apollo Client store is completely initialized.
</p> </p>
<p> <p>
This example relies on <a href='http://graph.cool'>graph.cool</a> for its GraphQL backend. This example relies on <a href='http://graph.cool'>graph.cool</a> for
its GraphQL backend.
</p> </p>
</article> </article>
</App> </App>
......
...@@ -4,7 +4,7 @@ import Submit from '../components/Submit' ...@@ -4,7 +4,7 @@ import Submit from '../components/Submit'
import PostList from '../components/PostList' import PostList from '../components/PostList'
import withData from '../lib/withData' import withData from '../lib/withData'
export default withData((props) => ( export default withData(props => (
<App> <App>
<Header pathname={props.url.pathname} /> <Header pathname={props.url.pathname} />
<Submit /> <Submit />
......
...@@ -2,10 +2,21 @@ ...@@ -2,10 +2,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-asset-imports with-asset-imports-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-asset-imports curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-asset-imports
cd with-asset-imports cd with-asset-imports
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-babel-macros with-babel-macros-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-babel-macros curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-babel-macros
cd with-babel-macros cd with-babel-macros
``` ```
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-custom-babel-config curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-custom-babel-config
cd with-custom-babel-config cd with-custom-babel-config
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-cxs with-cxs-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-cxs curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-cxs
cd with-cxs cd with-cxs
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-dotenv with-dotenv-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-dotenv curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-dotenv
cd with-dotenv cd with-dotenv
``` ```
......
...@@ -2,10 +2,21 @@ ...@@ -2,10 +2,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-dynamic-import with-dynamic-import-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-dynamic-import curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-dynamic-import
cd with-dynamic-import cd with-dynamic-import
``` ```
......
...@@ -2,12 +2,23 @@ ...@@ -2,12 +2,23 @@
**You can find a detailed documentation about how to build Electron apps with Next.js [here](https://leo.im/2017/electron-next)!** **You can find a detailed documentation about how to build Electron apps with Next.js [here](https://leo.im/2017/electron-next)!**
## Usage ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-electron with-electron-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-electron curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-electron
cd with-electron cd with-electron
``` ```
......
import {Basic, Combined, Animated, bounce} from '../shared/styles'
const Home = () => (
<div>
<Basic>Cool Styles</Basic>
<Combined>
With <code>:hover</code>.
</Combined>
<Animated animation={bounce}>Let's bounce.</Animated>
</div>
)
export default Home
import React, { Component } from 'react'
import { hydrate } from 'react-emotion'
import { injectGlobalStyles } from '../shared/styles'
const withEmotion = ComposedComponent => {
class HOC extends Component {
componentWillMount () {
if (typeof window !== 'undefined') {
hydrate(window.__NEXT_DATA__.ids)
}
injectGlobalStyles()
}
render () {
return <ComposedComponent />
}
};
return HOC
}
export default withEmotion
{
"name": "with-emotion-fiber",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next"
},
"keywords": [],
"author": "Thomas Greco",
"license": "ISC",
"dependencies": {
"emotion": "^8.0.11",
"emotion-server": "^8.0.11",
"next": "^4.1.4",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"react-emotion": "^8.0.11"
}
}
import Document, { Head, Main, NextScript } from 'next/document'
import { extractCritical } from 'emotion-server'
export default class MyDocument extends Document {
static getInitialProps ({ renderPage }) {
const page = renderPage()
const styles = extractCritical(page.html)
return { ...page, ...styles }
}
constructor (props) {
super(props)
const { __NEXT_DATA__, ids } = props
if (ids) {
__NEXT_DATA__.ids = ids
}
}
render () {
return (
<html>
<Head>
<title>With Emotion</title>
<style dangerouslySetInnerHTML={{ __html: this.props.css }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
import withEmotion from '../hoc/withEmotion.component'
import home from '../features/home.component'
export default withEmotion(home)
import styled, { keyframes, css, injectGlobal } from 'react-emotion'
export const injectGlobalStyles = () => injectGlobal`
html, body {
padding: 3rem 1rem;
margin: 0;
background: papayawhip;
min-height: 100%;
font-family: Helvetica, Arial, sans-serif;
font-size: 24px;
}
`
export const basicStyles = css`
background-color: white;
color: cornflowerblue;
border: 1px solid lightgreen;
border-right: none;
border-bottom: none;
box-shadow: 5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow;
transition: all 0.1s linear;
margin: 3rem 0;
padding: 1rem 0.5rem;
`
export const hoverStyles = css`
&:hover {
color: white;
background-color: lightgray;
border-color: aqua;
box-shadow: -15px -15px 0 0 aqua, -30px -30px 0 0 cornflowerblue;
}
`
export const bounce = keyframes`
from {
transform: scale(1.01);
}
to {
transform: scale(0.99);
}
`
export const Basic = styled('div')`
${basicStyles};
`
export const Combined = styled('div')`
${basicStyles};
${hoverStyles};
& code {
background-color: linen;
}
`
export const Animated = styled('div')`
${basicStyles};
${hoverStyles};
& code {
background-color: linen;
}
animation: ${props => props.animation} 0.2s infinite ease-in-out alternate;
`
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-emotion with-emotion-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-emotion curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-emotion
cd with-emotion cd with-emotion
``` ```
......
...@@ -4,10 +4,21 @@ ...@@ -4,10 +4,21 @@
## How to use ## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```
npm i -g create-next-app
create-next-app --example with-fela with-fela-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js): Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash ```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-fela curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-fela
cd with-fela cd with-fela
``` ```
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment