Commit b6b88e5f authored by Tim Neutkens's avatar Tim Neutkens

Merge branch 'canary' of github.com:zeit/next.js into canary

parents e3a9c950 e90f8963
{ {
"presets": [ "presets": [
"env", "env",
"react" "react",
"flow"
], ],
"plugins": [ "plugins": [
"transform-object-rest-spread", "transform-object-rest-spread",
......
[ignore]
<PROJECT_ROOT>/examples/.*
\ No newline at end of file
...@@ -43,7 +43,7 @@ if (!existsSync(join(dir, 'pages'))) { ...@@ -43,7 +43,7 @@ if (!existsSync(join(dir, 'pages'))) {
} }
build(dir) build(dir)
.catch((err) => { .catch((err) => {
console.error(err) console.error(err)
process.exit(1) process.exit(1)
}) })
...@@ -54,12 +54,12 @@ if (!existsSync(join(dir, 'pages'))) { ...@@ -54,12 +54,12 @@ if (!existsSync(join(dir, 'pages'))) {
const srv = new Server({ dir, dev: true }) const srv = new Server({ dir, dev: true })
srv.start(argv.port, argv.hostname) srv.start(argv.port, argv.hostname)
.then(async () => { .then(async () => {
if (!process.env.NOW) { if (!process.env.NOW) {
console.log(`> Ready on http://${argv.hostname ? argv.hostname : 'localhost'}:${argv.port}`) console.log(`> Ready on http://${argv.hostname ? argv.hostname : 'localhost'}:${argv.port}`)
} }
}) })
.catch((err) => { .catch((err) => {
if (err.code === 'EADDRINUSE') { if (err.code === 'EADDRINUSE') {
let errorMessage = `Port ${argv.port} is already in use.` let errorMessage = `Port ${argv.port} is already in use.`
const pkgAppPath = require('find-up').sync('package.json', { const pkgAppPath = require('find-up').sync('package.json', {
...@@ -73,4 +73,4 @@ srv.start(argv.port, argv.hostname) ...@@ -73,4 +73,4 @@ srv.start(argv.port, argv.hostname)
console.error(err) console.error(err)
} }
process.nextTick(() => process.exit(1)) process.nextTick(() => process.exit(1))
}) })
...@@ -46,12 +46,12 @@ const dir = resolve(argv._[0] || '.') ...@@ -46,12 +46,12 @@ const dir = resolve(argv._[0] || '.')
const srv = new Server({ dir }) const srv = new Server({ dir })
srv.start(argv.port, argv.hostname) srv.start(argv.port, argv.hostname)
.then(() => { .then(() => {
if (!process.env.NOW) { if (!process.env.NOW) {
console.log(`> Ready on http://${argv.hostname ? argv.hostname : 'localhost'}:${argv.port}`) console.log(`> Ready on http://${argv.hostname ? argv.hostname : 'localhost'}:${argv.port}`)
} }
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err)
process.exit(1) process.exit(1)
}) })
...@@ -8,7 +8,7 @@ const app = next({ dev }) ...@@ -8,7 +8,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
res.setHeader('Content-Type', 'text/html; charset=iso-8859-2') res.setHeader('Content-Type', 'text/html; charset=iso-8859-2')
...@@ -18,4 +18,4 @@ app.prepare() ...@@ -18,4 +18,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -7,7 +7,7 @@ const app = next({ dev }) ...@@ -7,7 +7,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
server.get('/a', (req, res) => { server.get('/a', (req, res) => {
...@@ -30,4 +30,4 @@ app.prepare() ...@@ -30,4 +30,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -7,7 +7,7 @@ const app = Next({ dev }) ...@@ -7,7 +7,7 @@ const app = Next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = fastify() const server = fastify()
server.get('/a', (req, res) => { server.get('/a', (req, res) => {
...@@ -26,4 +26,4 @@ app.prepare() ...@@ -26,4 +26,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -10,8 +10,8 @@ const server = new Hapi.Server({ ...@@ -10,8 +10,8 @@ const server = new Hapi.Server({
}) })
app app
.prepare() .prepare()
.then(async () => { .then(async () => {
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/a', path: '/a',
...@@ -43,4 +43,4 @@ app ...@@ -43,4 +43,4 @@ app
console.log('Error starting server') console.log('Error starting server')
console.log(error) console.log(error)
} }
}) })
...@@ -8,7 +8,7 @@ const app = next({ dev }) ...@@ -8,7 +8,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = new Koa() const server = new Koa()
const router = new Router() const router = new Router()
...@@ -36,4 +36,4 @@ app.prepare() ...@@ -36,4 +36,4 @@ app.prepare()
server.listen(port, () => { server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -8,7 +8,7 @@ const app = next({ dev }) ...@@ -8,7 +8,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl const { pathname, query } = parsedUrl
...@@ -25,4 +25,4 @@ app.prepare() ...@@ -25,4 +25,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -7,14 +7,14 @@ ...@@ -7,14 +7,14 @@
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
"react": "^16.2.0", "react": "^16.2.0",
"react-dom": "^16.2.0" "react-dom": "^16.2.0",
"@zeit/next-typescript": "0.0.11",
"typescript": "^2.7.1"
}, },
"devDependencies": { "devDependencies": {
"@types/next": "^2.4.7", "@types/next": "^2.4.7",
"@types/react": "^16.0.36", "@types/react": "^16.0.36",
"@zeit/next-typescript": "^0.0.8",
"nodemon": "^1.12.1", "nodemon": "^1.12.1",
"ts-node": "^4.1.0", "ts-node": "^4.1.0"
"typescript": "^2.7.1"
} }
} }
...@@ -8,7 +8,7 @@ const app = next({ dev }) ...@@ -8,7 +8,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl const { pathname, query } = parsedUrl
...@@ -25,4 +25,4 @@ app.prepare() ...@@ -25,4 +25,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -6,7 +6,7 @@ const app = next({ dev }) ...@@ -6,7 +6,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
server.get('/', (req, res) => { server.get('/', (req, res) => {
...@@ -21,8 +21,8 @@ app.prepare() ...@@ -21,8 +21,8 @@ app.prepare()
if (err) throw err if (err) throw err
console.log('> Ready on http://localhost:3000') console.log('> Ready on http://localhost:3000')
}) })
}) })
.catch((ex) => { .catch((ex) => {
console.error(ex.stack) console.error(ex.stack)
process.exit(1) process.exit(1)
}) })
...@@ -11,7 +11,7 @@ const route = pathMatch() ...@@ -11,7 +11,7 @@ const route = pathMatch()
const match = route('/blog/:id') const match = route('/blog/:id')
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const { pathname, query } = parse(req.url, true) const { pathname, query } = parse(req.url, true)
const params = match(pathname) const params = match(pathname)
...@@ -28,4 +28,4 @@ app.prepare() ...@@ -28,4 +28,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -9,7 +9,7 @@ const app = next({ dev }) ...@@ -9,7 +9,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const rootStaticFiles = [ const rootStaticFiles = [
...@@ -28,4 +28,4 @@ app.prepare() ...@@ -28,4 +28,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -14,7 +14,7 @@ const ssrCache = new LRUCache({ ...@@ -14,7 +14,7 @@ const ssrCache = new LRUCache({
}) })
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
// Use the `renderAndCache` utility defined below to serve pages // Use the `renderAndCache` utility defined below to serve pages
...@@ -35,7 +35,7 @@ app.prepare() ...@@ -35,7 +35,7 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
/* /*
* NB: make sure to modify this to take into account anything that should trigger * NB: make sure to modify this to take into account anything that should trigger
......
...@@ -18,7 +18,7 @@ const app = next({ dev }) ...@@ -18,7 +18,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl) handle(req, res, parsedUrl)
...@@ -27,4 +27,4 @@ app.prepare() ...@@ -27,4 +27,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -17,7 +17,7 @@ const app = next({ dev }) ...@@ -17,7 +17,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl) handle(req, res, parsedUrl)
...@@ -26,4 +26,4 @@ app.prepare() ...@@ -26,4 +26,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -11,7 +11,7 @@ const app = next({ dev }) ...@@ -11,7 +11,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl) handle(req, res, parsedUrl)
...@@ -20,4 +20,4 @@ app.prepare() ...@@ -20,4 +20,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
/* eslint-disable */
const withCss = require('@zeit/next-css') const withCss = require('@zeit/next-css')
// fix: prevents error when .css files are required by node // fix: prevents error when .css files are required by node
......
...@@ -49,3 +49,6 @@ export default withReduxSaga(connect(mapStateToProps, null)(Index)); ...@@ -49,3 +49,6 @@ export default withReduxSaga(connect(mapStateToProps, null)(Index));
``` ```
`connect` must go inside `withReduxSaga` otherwise `connect` will not be able to find the store. `connect` must go inside `withReduxSaga` otherwise `connect` will not be able to find the store.
### Note:
In these *with-apollo* examples, the ```withData()``` HOC must wrap a top-level component from within the ```pages``` directory. Wrapping a child component with the HOC will result in a ```Warning: Failed prop type: The prop 'serverState' is marked as required in 'WithData(Apollo(Component))', but its value is 'undefined'``` error. Down-tree child components will have access to Apollo, and can be wrapped with any other sort of ```graphql()```, ```compose()```, etc HOC's.
...@@ -49,3 +49,6 @@ const mapStateToProps = state => ({ ...@@ -49,3 +49,6 @@ const mapStateToProps = state => ({
export default withRedux(connect(mapStateToProps, null)(Index)); export default withRedux(connect(mapStateToProps, null)(Index));
``` ```
### Note:
In these *with-apollo* examples, the ```withData()``` HOC must wrap a top-level component from within the ```pages``` directory. Wrapping a child component with the HOC will result in a ```Warning: Failed prop type: The prop 'serverState' is marked as required in 'WithData(Apollo(Component))', but its value is 'undefined'``` error. Down-tree child components will have access to Apollo, and can be wrapped with any other sort of ```graphql()```, ```compose()```, etc HOC's.
...@@ -66,3 +66,7 @@ It is important to note the use of Apollo's `resetStore()` method after signing ...@@ -66,3 +66,7 @@ It is important to note the use of Apollo's `resetStore()` method after signing
To get this example running locally, you will need to create a graph.cool To get this example running locally, you will need to create a graph.cool
account, and provide [the `project.graphcool` schema](https://github.com/zeit/next.js/blob/master/examples/with-apollo-auth/project.graphcool). account, and provide [the `project.graphcool` schema](https://github.com/zeit/next.js/blob/master/examples/with-apollo-auth/project.graphcool).
### Note:
In these *with-apollo* examples, the ```withData()``` HOC must wrap a top-level component from within the ```pages``` directory. Wrapping a child component with the HOC will result in a ```Warning: Failed prop type: The prop 'serverState' is marked as required in 'WithData(Apollo(Component))', but its value is 'undefined'``` error. Down-tree child components will have access to Apollo, and can be wrapped with any other sort of ```graphql()```, ```compose()```, etc HOC's.
...@@ -48,3 +48,6 @@ In this simple example, we integrate Apollo seamlessly with Next by wrapping our ...@@ -48,3 +48,6 @@ In this simple example, we integrate Apollo seamlessly with Next by wrapping our
On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree). 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, [`getDataFromTree`](http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.
This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend. This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend.
### Note:
In these *with-apollo* examples, the ```withData()``` HOC must wrap a top-level component from within the ```pages``` directory. Wrapping a child component with the HOC will result in a ```Warning: Failed prop type: The prop 'serverState' is marked as required in 'WithData(Apollo(Component))', but its value is 'undefined'``` error. Down-tree child components will have access to Apollo, and can be wrapped with any other sort of ```graphql()```, ```compose()```, etc HOC's.
...@@ -32,9 +32,16 @@ export default ComposedComponent => { ...@@ -32,9 +32,16 @@ export default ComposedComponent => {
// and extract the resulting data // and extract the resulting data
const apollo = initApollo() const apollo = initApollo()
try { try {
// create the url prop which is passed to every page
const url = {
query: ctx.query,
asPath: ctx.asPath,
pathname: ctx.pathname,
};
// Run all GraphQL queries // Run all GraphQL queries
await getDataFromTree( await getDataFromTree(
<ComposedComponent ctx={ctx} {...composedInitialProps} />, <ComposedComponent ctx={ctx} url={url} {...composedInitialProps} />,
{ {
router: { router: {
asPath: ctx.asPath, asPath: ctx.asPath,
......
...@@ -10,7 +10,7 @@ export default connect({ ...@@ -10,7 +10,7 @@ export default connect({
mounted: signal`clock.mounted`, mounted: signal`clock.mounted`,
unMounted: signal`clock.unMounted` unMounted: signal`clock.unMounted`
}, },
class Page extends React.Component { class Page extends React.Component {
componentDidMount () { componentDidMount () {
this.props.mounted() this.props.mounted()
} }
...@@ -29,5 +29,5 @@ export default connect({ ...@@ -29,5 +29,5 @@ export default connect({
</div> </div>
) )
} }
} }
) )
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
RichUtils, RichUtils,
convertToRaw, convertToRaw,
convertFromRaw convertFromRaw
} from 'draft-js' } from 'draft-js'
export default class App extends React.Component { export default class App extends React.Component {
constructor (props) { constructor (props) {
......
...@@ -16,7 +16,7 @@ const firebase = admin.initializeApp({ ...@@ -16,7 +16,7 @@ const firebase = admin.initializeApp({
}, 'server') }, 'server')
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
server.use(bodyParser.json()) server.use(bodyParser.json())
...@@ -61,4 +61,4 @@ app.prepare() ...@@ -61,4 +61,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-google-analytics)
# Example app with analytics
## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```bash
npx create-next-app --example with-google-analytics with-google-analytics-app
# or
yarn create next-app --example with-google-analytics with-google-analytics-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/with-google-analytics
cd with-google-analytics
```
Install it and run:
```bash
yarn
yarn 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 [Next.js](https://github.com/zeit/next.js) along with [Google Analytics](https://developers.google.com/analytics/devguides/collection/gtagjs/). A custom [\_document](https://github.com/zeit/next.js/#custom-document) is used to inject [tracking snippet](https://developers.google.com/analytics/devguides/collection/gtagjs/) and track [pageviews](https://developers.google.com/analytics/devguides/collection/gtagjs/pages) and [event](https://developers.google.com/analytics/devguides/collection/gtagjs/events).
import React from 'react'
import Link from 'next/link'
export default () => (
<header>
<nav>
<ul>
<li>
<Link href='/'>
<a>Home</a>
</Link>
</li>
<li>
<Link href='/about'>
<a>About</a>
</Link>
</li>
<li>
<Link href='/contact'>
<a>Contact</a>
</Link>
</li>
</ul>
</nav>
</header>
)
import React from 'react'
import Router from 'next/router'
import Header from './Header'
import * as gtag from '../lib/gtag'
Router.onRouteChangeComplete = url => {
gtag.pageview(url)
}
export default ({ children }) => (
<div>
<Header />
{children}
</div>
)
export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>'
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
window.gtag('config', GA_TRACKING_ID, {
page_location: url,
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
})
}
{
"name": "with-google-analytics",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
import { GA_TRACKING_ID } from '../lib/gtag'
export default class extends Document {
static getInitialProps ({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage()
const styles = flush()
return { html, head, errorHtml, chunks, styles }
}
render () {
return (
<html>
<Head>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
`}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page>
<h1>This is the About page</h1>
</Page>
)
import React, { Component } from 'react'
import Page from '../components/Page'
import * as gtag from '../lib/gtag'
export default class extends Component {
state = { message: '' }
handleInput = e => {
this.setState({ message: e.target.value })
}
handleSubmit = e => {
e.preventDefault()
gtag.event({
action: 'submit_form',
category: 'Contact',
label: this.state.message
})
this.setState({ message: '' })
}
render () {
return (
<Page>
<h1>This is the Contact page</h1>
<form onSubmit={this.handleSubmit}>
<label>
<span>Message:</span>
<textarea onInput={this.handleInput} value={this.state.message} />
</label>
<button type='submit'>submit</button>
</form>
</Page>
)
}
}
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page>
<h1>This is the Home page</h1>
</Page>
)
...@@ -8,10 +8,10 @@ const app = next({ dev }) ...@@ -8,10 +8,10 @@ const app = next({ dev })
const handler = routes.getRequestHandler(app) const handler = routes.getRequestHandler(app)
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer(handler) createServer(handler)
.listen(port, (err) => { .listen(port, (err) => {
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -8,10 +8,10 @@ const app = next({ dev }) ...@@ -8,10 +8,10 @@ const app = next({ dev })
const handler = routes.getRequestHandler(app) const handler = routes.getRequestHandler(app)
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer(handler) createServer(handler)
.listen(port, (err) => { .listen(port, (err) => {
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-now-env)
# Now-env example
## How to use
### Using `create-next-app`
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```bash
npx create-next-app --example with-now-env with-now-env-app
# or
yarn create next-app --example with-now-env with-now-env-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/with-now-env
cd with-now-env
```
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
```
keep in mind that in order to deploy the app to `now` the env [secrets](https://zeit.co/docs/getting-started/secrets) defined in `now.json` should be listed in your account
## The idea behind the example
This example shows the usage of [now-env](https://github.com/zeit/now-env), it allows to use secrets in development that will be replaced in production by the secrets defined with [now](https://zeit.co/docs/getting-started/secrets)
/**
* After the next require you can use process.env to get your secrets
*/
require('now-env')
console.log({
SECRET: process.env.SECRET,
ANOTHER_SECRET: process.env.ANOTHER_SECRET,
SECRET_FAIL: process.env.SECRET_FAIL
})
/**
* If some of the envs are public, like a google maps key, but you still
* want to keep them secret from the repo, the following code will allow you
* to share some variables with the client, configured at compile time.
*/
module.exports = {
webpack: config => {
config.plugins.forEach(plugin => {
if (plugin.constructor.name === 'DefinePlugin') {
plugin.definitions['process.env.SECRET'] = JSON.stringify(process.env.SECRET)
}
})
return config
}
}
{
"@my-secret-key": "keep-it-secret",
"@my-other-secret-key": "keep-it-secret-too"
}
{
"env": {
"SECRET": "@my-secret-key",
"ANOTHER_SECRET": "@my-other-secret-key",
"SECRET_FAIL": "@this-is-not-defined"
}
}
{
"name": "with-now-env",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"now-env": "^3.0.4"
}
}
export default () => (
<div className='hello'>
<p>
Hello World! Here's a secret shared with the client using webpack
DefinePlugin: <strong>{process.env.SECRET}</strong>, the secret is shared
at compile time, which means every reference to the secret is replaced
with its value
</p>
<style jsx>{`
.hello {
font: 15px Helvetica, Arial, sans-serif;
background: #eee;
padding: 100px;
text-align: center;
transition: 100ms ease-in background;
}
.hello:hover {
background: #ccc;
}
`}</style>
</div>
)
...@@ -8,10 +8,10 @@ const app = next({ dev }) ...@@ -8,10 +8,10 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => handle(req, res, parse(req.url, true).pathname)) createServer((req, res) => handle(req, res, parse(req.url, true).pathname))
.listen(port, (err) => { .listen(port, (err) => {
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
/* eslint no-extend-native: 0 */ /* eslint no-extend-native: 0 */
// core-js comes with Next.js. So, you can import it like below
import includes from 'core-js/library/fn/string/virtual/includes'
import repeat from 'core-js/library/fn/string/virtual/repeat'
// Add your polyfills // Add your polyfills
// This files runs at the very beginning (even before React and Next.js core) // This files runs at the very beginning (even before React and Next.js core)
console.log('Load your polyfills') console.log('Load your polyfills')
// core-js comes with Next.js. So, you can import it like below
import includes from 'core-js/library/fn/string/virtual/includes'
import repeat from 'core-js/library/fn/string/virtual/repeat'
String.prototype.includes = includes String.prototype.includes = includes
String.prototype.repeat = repeat String.prototype.repeat = repeat
...@@ -8,7 +8,7 @@ const app = next({ dev }) ...@@ -8,7 +8,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
Router.forEachPattern((page, pattern, defaultParams) => server.get(pattern, (req, res) => Router.forEachPattern((page, pattern, defaultParams) => server.get(pattern, (req, res) =>
...@@ -17,4 +17,4 @@ app.prepare() ...@@ -17,4 +17,4 @@ app.prepare()
server.get('*', (req, res) => handle(req, res)) server.get('*', (req, res) => handle(req, res))
server.listen(port) server.listen(port)
}) })
...@@ -39,5 +39,5 @@ export default connect( ...@@ -39,5 +39,5 @@ export default connect(
character: state.character, character: state.character,
error: state.error, error: state.error,
isFetchedOnServer: state.isFetchedOnServer isFetchedOnServer: state.isFetchedOnServer
}), })
)(CharacterInfo) )(CharacterInfo)
...@@ -46,5 +46,5 @@ export default withRedux( ...@@ -46,5 +46,5 @@ export default withRedux(
{ {
startFetchingCharacters: actions.startFetchingCharacters, startFetchingCharacters: actions.startFetchingCharacters,
stopFetchingCharacters: actions.stopFetchingCharacters stopFetchingCharacters: actions.stopFetchingCharacters
}, }
)(Counter) )(Counter)
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-analytics) [![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-segment-analytics)
# Example app with analytics # Example app with analytics
...@@ -9,9 +9,9 @@ ...@@ -9,9 +9,9 @@
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example: Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```bash ```bash
npx create-next-app --example with-analytics with-analytics-app npx create-next-app --example with-segment-analytics with-segment-analytics-app
# or # or
yarn create next-app --example with-analytics with-analytics-app yarn create next-app --example with-segment-analytics with-segment-analytics-app
``` ```
### Download manually ### Download manually
...@@ -19,8 +19,8 @@ yarn create next-app --example with-analytics with-analytics-app ...@@ -19,8 +19,8 @@ yarn create next-app --example with-analytics with-analytics-app
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/canary | tar -xz --strip=2 next.js-canary/examples/with-analytics curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-segment-analytics
cd with-analytics cd with-segment-analytics
``` ```
Install it and run: Install it and run:
......
{ {
"name": "with-analytics", "name": "with-segment-analytics",
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
......
...@@ -15,7 +15,7 @@ module.exports = { ...@@ -15,7 +15,7 @@ module.exports = {
query: { id: post.id } query: { id: post.id }
} }
}), }),
{}, {}
) )
// combine the map of post pages with the home // combine the map of post pages with the home
......
...@@ -7,7 +7,7 @@ const app = next({ dev }) ...@@ -7,7 +7,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
const server = express() const server = express()
// custom route for posts // custom route for posts
...@@ -25,4 +25,4 @@ app.prepare() ...@@ -25,4 +25,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -9,7 +9,7 @@ const app = next({ dev }) ...@@ -9,7 +9,7 @@ const app = next({ dev })
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const { pathname } = parsedUrl const { pathname } = parsedUrl
...@@ -25,4 +25,4 @@ app.prepare() ...@@ -25,4 +25,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
"devDependencies": { "devDependencies": {
"@types/next": "^2.4.7", "@types/next": "^2.4.7",
"@types/react": "^16.0.36", "@types/react": "^16.0.36",
"@zeit/next-typescript": "0.0.8", "@zeit/next-typescript": "0.0.11",
"typescript": "^2.7.1" "typescript": "^2.7.1"
} }
} }
...@@ -11,7 +11,7 @@ const route = pathMatch() ...@@ -11,7 +11,7 @@ const route = pathMatch()
const match = route('/about/:name') const match = route('/about/:name')
app.prepare() app.prepare()
.then(() => { .then(() => {
createServer((req, res) => { createServer((req, res) => {
const { pathname } = parse(req.url) const { pathname } = parse(req.url)
const params = match(pathname) const params = match(pathname)
...@@ -26,4 +26,4 @@ app.prepare() ...@@ -26,4 +26,4 @@ app.prepare()
if (err) throw err if (err) throw err
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
...@@ -15,7 +15,7 @@ export default class EventEmitter { ...@@ -15,7 +15,7 @@ export default class EventEmitter {
emit (event, ...data) { emit (event, ...data) {
if (!this.listeners[event]) return if (!this.listeners[event]) return
this.listeners[event].forEach(cb => cb(...data)) this.listeners[event].forEach(cb => cb(...data)) // eslint-disable-line standard/no-callback-literal
} }
off (event, cb) { off (event, cb) {
......
...@@ -2,3 +2,4 @@ export const PHASE_EXPORT = 'phase-export' ...@@ -2,3 +2,4 @@ export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build' export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server' export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server' export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PAGES_MANIFEST = 'pages-manifest.json'
...@@ -355,7 +355,7 @@ export default class Router { ...@@ -355,7 +355,7 @@ export default class Router {
} }
async fetchRoute (route) { async fetchRoute (route) {
return await this.pageLoader.loadPage(route) return this.pageLoader.loadPage(route)
} }
abortComponentLoad (as) { abortComponentLoad (as) {
......
...@@ -113,11 +113,12 @@ ...@@ -113,11 +113,12 @@
"@taskr/esnext": "1.1.0", "@taskr/esnext": "1.1.0",
"@taskr/watch": "1.1.0", "@taskr/watch": "1.1.0",
"@zeit/next-css": "0.0.7", "@zeit/next-css": "0.0.7",
"babel-eslint": "8.0.1", "babel-eslint": "8.2.2",
"babel-jest": "21.2.0", "babel-jest": "21.2.0",
"babel-plugin-istanbul": "4.1.5", "babel-plugin-istanbul": "4.1.5",
"babel-plugin-transform-remove-strict-mode": "0.0.2", "babel-plugin-transform-remove-strict-mode": "0.0.2",
"babel-preset-es2015": "6.24.1", "babel-preset-es2015": "6.24.1",
"babel-preset-flow": "6.23.0",
"benchmark": "2.1.4", "benchmark": "2.1.4",
"cheerio": "0.22.0", "cheerio": "0.22.0",
"chromedriver": "2.32.3", "chromedriver": "2.32.3",
...@@ -139,7 +140,7 @@ ...@@ -139,7 +140,7 @@
"react": "16.2.0", "react": "16.2.0",
"react-dom": "16.2.0", "react-dom": "16.2.0",
"rimraf": "2.6.2", "rimraf": "2.6.2",
"standard": "9.0.2", "standard": "11.0.1",
"taskr": "1.1.0", "taskr": "1.1.0",
"wd": "1.4.1" "wd": "1.4.1"
}, },
......
...@@ -1012,7 +1012,7 @@ module.exports = { ...@@ -1012,7 +1012,7 @@ module.exports = {
Or use a function: Or use a function:
```js ```js
module.exports = (phase, {defaultConfig}){ module.exports = (phase, {defaultConfig}) => {
// //
// https://github.com/zeit/ // https://github.com/zeit/
return { return {
...@@ -1185,6 +1185,7 @@ module.exports = { ...@@ -1185,6 +1185,7 @@ module.exports = {
```js ```js
// pages/index.js // pages/index.js
import getConfig from 'next/config' import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() const {serverRuntimeConfig, publicRuntimeConfig} = getConfig()
console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side
...@@ -1258,7 +1259,7 @@ Simply develop your app as you normally do with Next.js. Then create a custom Ne ...@@ -1258,7 +1259,7 @@ Simply develop your app as you normally do with Next.js. Then create a custom Ne
```js ```js
// next.config.js // next.config.js
module.exports = { module.exports = {
exportPathMap: function() { exportPathMap: function(defaultPathMap) {
return { return {
'/': { page: '/' }, '/': { page: '/' },
'/about': { page: '/about' }, '/about': { page: '/about' },
......
// @flow
import { RawSource } from 'webpack-sources'
import { MATCH_ROUTE_NAME } from '../../utils'
import {PAGES_MANIFEST} from '../../../lib/constants'
// This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/dist/bundles/pages/index.js` when doing SSR
// It's also used by next export to provide defaultPathMap
export default class PagesManifestPlugin {
apply (compiler: any) {
compiler.plugin('emit', (compilation, callback) => {
const {entries} = compilation
const pages = {}
for (const entry of entries) {
const pagePath = MATCH_ROUTE_NAME.exec(entry.name)[1]
if (!pagePath) {
continue
}
const {name} = entry
pages[`/${pagePath.replace(/\\/g, '/')}`] = name
}
compilation.assets[PAGES_MANIFEST] = new RawSource(JSON.stringify(pages))
callback()
})
}
}
...@@ -10,6 +10,7 @@ import PagesPlugin from './plugins/pages-plugin' ...@@ -10,6 +10,7 @@ import PagesPlugin from './plugins/pages-plugin'
import NextJsSsrImportPlugin from './plugins/nextjs-ssr-import' import NextJsSsrImportPlugin from './plugins/nextjs-ssr-import'
import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin' import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin' import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import PagesManifestPlugin from './plugins/pages-manifest-plugin'
import findBabelConfig from './babel/find-config' import findBabelConfig from './babel/find-config'
const nextDir = path.join(__dirname, '..', '..', '..') const nextDir = path.join(__dirname, '..', '..', '..')
...@@ -254,6 +255,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer ...@@ -254,6 +255,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production') 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
}), }),
!dev && new webpack.optimize.ModuleConcatenationPlugin(), !dev && new webpack.optimize.ModuleConcatenationPlugin(),
isServer && new PagesManifestPlugin(),
!isServer && new PagesPlugin(), !isServer && new PagesPlugin(),
!isServer && new DynamicChunksPlugin(), !isServer && new DynamicChunksPlugin(),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
......
...@@ -9,7 +9,7 @@ export async function getPages (dir, {dev, isServer, pageExtensions}) { ...@@ -9,7 +9,7 @@ export async function getPages (dir, {dev, isServer, pageExtensions}) {
return getPageEntries(pageFiles, {isServer, pageExtensions}) return getPageEntries(pageFiles, {isServer, pageExtensions})
} }
async function getPagePaths (dir, {dev, isServer, pageExtensions}) { export async function getPagePaths (dir, {dev, isServer, pageExtensions}) {
let pages let pages
if (dev) { if (dev) {
......
// @flow
import findUp from 'find-up' import findUp from 'find-up'
const cache = new Map() const cache = new Map()
...@@ -11,28 +12,29 @@ const defaultConfig = { ...@@ -11,28 +12,29 @@ const defaultConfig = {
configOrigin: 'default', configOrigin: 'default',
useFileSystemPublicRoutes: true, useFileSystemPublicRoutes: true,
generateEtags: true, generateEtags: true,
pageExtensions: ['jsx', 'js'] // jsx before js because otherwise regex matching will match js first pageExtensions: ['jsx', 'js']
} }
export default function getConfig (phase, dir, customConfig) { export default function getConfig (phase: string, dir: string, customConfig?: ?Object) {
if (!cache.has(dir)) { if (!cache.has(dir)) {
cache.set(dir, loadConfig(phase, dir, customConfig)) cache.set(dir, loadConfig(phase, dir, customConfig))
} }
return cache.get(dir) return cache.get(dir)
} }
export function loadConfig (phase, dir, customConfig) { export function loadConfig (phase: string, dir: string, customConfig?: ?Object) {
if (customConfig && typeof customConfig === 'object') { if (customConfig && typeof customConfig === 'object') {
customConfig.configOrigin = 'server' customConfig.configOrigin = 'server'
return withDefaults(customConfig) return withDefaults(customConfig)
} }
const path = findUp.sync('next.config.js', { const path: string = findUp.sync('next.config.js', {
cwd: dir cwd: dir
}) })
let userConfig = {} let userConfig = {}
if (path && path.length) { if (path && path.length) {
// $FlowFixMe
const userConfigModule = require(path) const userConfigModule = require(path)
userConfig = userConfigModule.default || userConfigModule userConfig = userConfigModule.default || userConfigModule
if (typeof userConfigModule === 'function') { if (typeof userConfigModule === 'function') {
...@@ -44,6 +46,6 @@ export function loadConfig (phase, dir, customConfig) { ...@@ -44,6 +46,6 @@ export function loadConfig (phase, dir, customConfig) {
return withDefaults(userConfig) return withDefaults(userConfig)
} }
function withDefaults (config) { function withDefaults (config: Object) {
return Object.assign({}, defaultConfig, config) return Object.assign({}, defaultConfig, config)
} }
...@@ -5,10 +5,9 @@ import walk from 'walk' ...@@ -5,10 +5,9 @@ import walk from 'walk'
import { extname, resolve, join, dirname, sep } from 'path' import { extname, resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs' import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config' import getConfig from './config'
import {PHASE_EXPORT} from '../lib/constants' import {PHASE_EXPORT, PAGES_MANIFEST} from '../lib/constants'
import { renderToHTML } from './render' import { renderToHTML } from './render'
import { getAvailableChunks } from './utils' import { getAvailableChunks } from './utils'
import { printAndExit } from '../lib/utils'
import { setAssetPrefix } from '../lib/asset' import { setAssetPrefix } from '../lib/asset'
import * as envConfig from '../lib/runtime-config' import * as envConfig from '../lib/runtime-config'
...@@ -17,7 +16,7 @@ export default async function (dir, options, configuration) { ...@@ -17,7 +16,7 @@ export default async function (dir, options, configuration) {
const nextConfig = configuration || getConfig(PHASE_EXPORT, dir) const nextConfig = configuration || getConfig(PHASE_EXPORT, dir)
const nextDir = join(dir, nextConfig.distDir) const nextDir = join(dir, nextConfig.distDir)
log(` using build directory: ${nextDir}`) log(`> using build directory: ${nextDir}`)
if (!existsSync(nextDir)) { if (!existsSync(nextDir)) {
console.error( console.error(
...@@ -27,6 +26,17 @@ export default async function (dir, options, configuration) { ...@@ -27,6 +26,17 @@ export default async function (dir, options, configuration) {
} }
const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8') const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
const pagesManifest = require(join(nextDir, 'dist', PAGES_MANIFEST))
const pages = Object.keys(pagesManifest)
const defaultPathMap = {}
for (const page of pages) {
if (page === '/_document') {
continue
}
defaultPathMap[page] = { page }
}
// Initialize the output directory // Initialize the output directory
const outDir = options.outdir const outDir = options.outdir
...@@ -73,13 +83,13 @@ export default async function (dir, options, configuration) { ...@@ -73,13 +83,13 @@ export default async function (dir, options, configuration) {
// Get the exportPathMap from the `next.config.js` // Get the exportPathMap from the `next.config.js`
if (typeof nextConfig.exportPathMap !== 'function') { if (typeof nextConfig.exportPathMap !== 'function') {
printAndExit( console.log('> No "exportPathMap" found in "next.config.js". Generating map from "./pages"')
'> Could not find "exportPathMap" function inside "next.config.js"\n' + nextConfig.exportPathMap = async (defaultMap) => {
'> "next export" uses that function to build html pages.' return defaultMap
) }
} }
const exportPathMap = await nextConfig.exportPathMap() const exportPathMap = await nextConfig.exportPathMap(defaultPathMap)
const exportPaths = Object.keys(exportPathMap) const exportPaths = Object.keys(exportPathMap)
// Start the rendering process // Start the rendering process
...@@ -115,7 +125,7 @@ export default async function (dir, options, configuration) { ...@@ -115,7 +125,7 @@ export default async function (dir, options, configuration) {
} }
for (const path of exportPaths) { for (const path of exportPaths) {
log(` exporting path: ${path}`) log(`> exporting path: ${path}`)
if (!path.startsWith('/')) { if (!path.startsWith('/')) {
throw new Error(`path "${path}" doesn't start with a backslash`) throw new Error(`path "${path}" doesn't start with a backslash`)
} }
......
/* eslint-disable import/first, no-return-await */
require('@zeit/source-map-support').install() require('@zeit/source-map-support').install()
import { resolve, join, sep } from 'path' import { resolve, join, sep } from 'path'
import { parse as parseUrl } from 'url' import { parse as parseUrl } from 'url'
......
import {join, parse, normalize, sep} from 'path' import {join, posix} from 'path'
import fs from 'mz/fs' import {PAGES_MANIFEST} from '../lib/constants'
export function pageNotFoundError (page) { export function pageNotFoundError (page) {
const err = new Error(`Cannot find module for page: ${page}`) const err = new Error(`Cannot find module for page: ${page}`)
...@@ -18,13 +18,8 @@ export function normalizePagePath (page) { ...@@ -18,13 +18,8 @@ export function normalizePagePath (page) {
page = `/${page}` page = `/${page}`
} }
// Windows compatibility
if (sep !== '/') {
page = page.replace(/\//g, sep)
}
// Throw when using ../ etc in the pathname // Throw when using ../ etc in the pathname
const resolvedPage = normalize(page) const resolvedPage = posix.normalize(page)
if (page !== resolvedPage) { if (page !== resolvedPage) {
throw new Error('Requested and resolved page mismatch') throw new Error('Requested and resolved page mismatch')
} }
...@@ -33,7 +28,8 @@ export function normalizePagePath (page) { ...@@ -33,7 +28,8 @@ export function normalizePagePath (page) {
} }
export function getPagePath (page, {dir, dist}) { export function getPagePath (page, {dir, dist}) {
const pageBundlesPath = join(dir, dist, 'dist', 'bundles', 'pages') const serverBuildPath = join(dir, dist, 'dist')
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
try { try {
page = normalizePagePath(page) page = normalizePagePath(page)
...@@ -42,24 +38,14 @@ export function getPagePath (page, {dir, dist}) { ...@@ -42,24 +38,14 @@ export function getPagePath (page, {dir, dist}) {
throw pageNotFoundError(page) throw pageNotFoundError(page)
} }
const pagePath = join(pageBundlesPath, page) // Path to the page that is to be loaded if (!pagesManifest[page]) {
// Don't allow wandering outside of the bundles directory
const pathDir = parse(pagePath).dir
if (pathDir.indexOf(pageBundlesPath) !== 0) {
console.error('Resolved page path goes outside of bundles path')
throw pageNotFoundError(page) throw pageNotFoundError(page)
} }
return pagePath return join(serverBuildPath, pagesManifest[page])
} }
export default async function requirePage (page, {dir, dist}) { export default async function requirePage (page, {dir, dist}) {
const pagePath = getPagePath(page, {dir, dist}) + '.js' const pagePath = getPagePath(page, {dir, dist})
const fileExists = await fs.exists(pagePath)
if (!fileExists) {
throw pageNotFoundError(page)
}
return require(pagePath) return require(pagePath)
} }
...@@ -2,7 +2,7 @@ import React from 'react' ...@@ -2,7 +2,7 @@ import React from 'react'
export default class AsyncProps extends React.Component { export default class AsyncProps extends React.Component {
static async getInitialProps () { static async getInitialProps () {
return await fetchData() return fetchData()
} }
render () { render () {
......
...@@ -29,7 +29,7 @@ export default (context, render) => { ...@@ -29,7 +29,7 @@ export default (context, render) => {
browser.close() browser.close()
}) })
it('should not show the default HMR error overlay', async() => { it('should not show the default HMR error overlay', async () => {
const browser = await webdriver(context.appPort, '/hmr/about') const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser const text = await browser
.elementByCss('p').text() .elementByCss('p').text()
......
...@@ -70,7 +70,7 @@ describe('Custom Server', () => { ...@@ -70,7 +70,7 @@ describe('Custom Server', () => {
expect($dynamic('img').attr('src')).toBe(`http://127.0.0.1:${context.appPort}/static/myimage.png`) expect($dynamic('img').attr('src')).toBe(`http://127.0.0.1:${context.appPort}/static/myimage.png`)
}) })
it('should support next/asset in client side', async() => { it('should support next/asset in client side', async () => {
const browser = await webdriver(context.appPort, '/') const browser = await webdriver(context.appPort, '/')
await browser await browser
.elementByCss('#go-asset').click() .elementByCss('#go-asset').click()
......
...@@ -18,27 +18,27 @@ export default function (context) { ...@@ -18,27 +18,27 @@ export default function (context) {
expect(filePathLink).toEqual('/file-name.md') expect(filePathLink).toEqual('/file-name.md')
}) })
it('should render a page with getInitialProps', async() => { it('should render a page with getInitialProps', async () => {
const html = await renderViaHTTP(context.port, '/dynamic') const html = await renderViaHTTP(context.port, '/dynamic')
expect(html).toMatch(/cool dynamic text/) expect(html).toMatch(/cool dynamic text/)
}) })
it('should render a dynamically rendered custom url page', async() => { it('should render a dynamically rendered custom url page', async () => {
const html = await renderViaHTTP(context.port, '/dynamic/one') const html = await renderViaHTTP(context.port, '/dynamic/one')
expect(html).toMatch(/next export is nice/) expect(html).toMatch(/next export is nice/)
}) })
it('should render pages with dynamic imports', async() => { it('should render pages with dynamic imports', async () => {
const html = await renderViaHTTP(context.port, '/dynamic-imports') const html = await renderViaHTTP(context.port, '/dynamic-imports')
expect(html).toMatch(/Welcome to dynamic imports/) expect(html).toMatch(/Welcome to dynamic imports/)
}) })
it('should render paths with extensions', async() => { it('should render paths with extensions', async () => {
const html = await renderViaHTTP(context.port, '/file-name.md') const html = await renderViaHTTP(context.port, '/file-name.md')
expect(html).toMatch(/this file has an extension/) expect(html).toMatch(/this file has an extension/)
}) })
it('should give empty object for query if there is no query', async() => { it('should give empty object for query if there is no query', async () => {
const html = await renderViaHTTP(context.port, '/get-initial-props-with-no-query') const html = await renderViaHTTP(context.port, '/get-initial-props-with-no-query')
expect(html).toMatch(/Query is: {}/) expect(html).toMatch(/Query is: {}/)
}) })
......
module.exports = {
test: 'error'
}
\ No newline at end of file
{
"/index": "bundles/pages/index.js",
"/world": "bundles/pages/world.js",
"/_error": "bundles/pages/_error.js",
"/non-existent-child": "bundles/pages/non-existent-child.js"
}
\ No newline at end of file
/* global describe, it, expect */ /* global describe, it, expect */
import { join, sep } from 'path' import { join } from 'path'
import requirePage, {getPagePath, normalizePagePath, pageNotFoundError} from '../../dist/server/require' import requirePage, {getPagePath, normalizePagePath, pageNotFoundError} from '../../dist/server/require'
const dir = '/path/to/some/project' const sep = '/'
const dist = '.next' const pathToBundles = join(__dirname, '_resolvedata', 'dist', 'bundles', 'pages')
const pathToBundles = join(dir, dist, 'dist', 'bundles', 'pages')
describe('pageNotFoundError', () => { describe('pageNotFoundError', () => {
it('Should throw error with ENOENT code', () => { it('Should throw error with ENOENT code', () => {
...@@ -42,17 +40,17 @@ describe('normalizePagePath', () => { ...@@ -42,17 +40,17 @@ describe('normalizePagePath', () => {
describe('getPagePath', () => { describe('getPagePath', () => {
it('Should append /index to the / page', () => { it('Should append /index to the / page', () => {
const pagePath = getPagePath('/', {dir, dist}) const pagePath = getPagePath('/', {dir: __dirname, dist: '_resolvedata'})
expect(pagePath).toBe(join(pathToBundles, `${sep}index`)) expect(pagePath).toBe(join(pathToBundles, `${sep}index.js`))
}) })
it('Should prepend / when a page does not have it', () => { it('Should prepend / when a page does not have it', () => {
const pagePath = getPagePath('_error', {dir, dist}) const pagePath = getPagePath('_error', {dir: __dirname, dist: '_resolvedata'})
expect(pagePath).toBe(join(pathToBundles, `${sep}_error`)) expect(pagePath).toBe(join(pathToBundles, `${sep}_error.js`))
}) })
it('Should throw with paths containing ../', () => { it('Should throw with paths containing ../', () => {
expect(() => getPagePath('/../../package.json', {dir, dist})).toThrow() expect(() => getPagePath('/../../package.json', {dir: __dirname, dist: '_resolvedata'})).toThrow()
}) })
}) })
......
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