Commit 3c97f966 authored by Tim Neutkens's avatar Tim Neutkens

Merge branch 'canary'

parents b75a8879 603b90ce
<!--- Provide a general summary of the issue in the Title above -->
<!--
⚠️ IMPORTANT ⚠️
If you have a question about Next.js please ask it on Spectrum https://spectrum.chat/next-js
or join our Slack community at https://zeit.chat and ask it in the `#next` channel
-->
<!--
Thank you very much for contributing to Next.js by creating an issue! ❤️
To avoid duplicate issues we ask you to check off the following list
-->
<!-- Checked checkbox should look like this: [x] -->
- [ ] I have searched the [issues](https://github.com/zeit/next.js/issues) of this repository and believe that this is not a duplicate.
- [ ] I have searched the [issues](https://github.com/zeit/next.js/issues?q=is%3Aissue) of this repository and believe that this is not a duplicate.
## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
......
......@@ -7,8 +7,9 @@ node_modules
package-lock.json
test/node_modules
# logs
# logs & pids
*.log
pids
# coverage
.nyc_output
......
......@@ -24,8 +24,7 @@
email: "leo@zeit.co",
tag: "canary",
api_key: {
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="
secure: "mvLXMXn1z1ri29wAy5/CCrDuO7ZC3gxckcnY5W00cbL8aFuK5buvpizKr3dz1pYX7vC55I+nZMtVa2vn4oOlTae07dd0BYGmmpiwq692XD4P+PHVs8D5MlbiT62vIJl/ezv/TcyoAbfIVPfUfLXA7H6a04Kodyzj3LffannOYpZNTPRNSdNAtkVtHPCuHksVpZoj6WhmC52MBEWkh0TCV3OdbeQAs6z3m6j81XcTduhXdraO4UmyXi/ML+eAgEBSejH70/7O/RSGludBOtIWMuxSrEey4wB4F4/xpN7k4LjPQRS+EtUBg9DSb3vB5y/hGwbDqwx7gGfN/yP/ssc9j3G8syTevv3fxH4ver9kg5tvltTJ8/gOzV7nF2sK1+Nb8legL4fLwHvgThf4sB9dAgNc7R8dYNgYwivkLUrrAy9WJsu7OsXLhg3NpEb9PcbKH7yFwrAzQjRPguVxg7bC02g41v0c2i1UXTb0D0/1KW5Mdg7HYZEw4uUXRhJCLWZbOcBCWdmiB+hwKSaq+aO49C5aX2UAyIsUPmG0OgqY91H/Y09KP3O6jN4j7ADrIIrdMwcyx15UJDZMwADCHHesnzeelDah7w3H6q+/heOA4nzbWhZaYQEDK4/aouRDINdXMmCmt9NNYjUA50BAI2dPpqetjaqq3gaPSAXsMvzNvRs="
},
skip_cleanup: true,
on: {
......
......@@ -62,7 +62,9 @@ srv.start(argv.port, argv.hostname)
.catch((err) => {
if (err.code === 'EADDRINUSE') {
let errorMessage = `Port ${argv.port} is already in use.`
const pkgAppPath = require('pkg-up').sync('.')
const pkgAppPath = require('find-up').sync('package.json', {
cwd: dir
})
const appPackage = JSON.parse(readFileSync(pkgAppPath, 'utf8'))
const nextScript = Object.entries(appPackage.scripts).find(scriptLine => scriptLine[1] === 'next')
if (nextScript) errorMessage += `\nUse \`npm run ${nextScript[0]} -- -p <some other port>\`.`
......
......@@ -7,6 +7,7 @@ import App from '../lib/app'
import { loadGetInitialProps, getURL } from '../lib/utils'
import PageLoader from '../lib/page-loader'
import * as asset from '../lib/asset'
import * as envConfig from '../lib/runtime-config'
// Polyfill Promise globally
// This is needed because Webpack2's dynamic loading(common chunks) code
......@@ -26,7 +27,8 @@ const {
query,
buildId,
chunks,
assetPrefix
assetPrefix,
runtimeConfig
},
location
} = window
......@@ -36,6 +38,11 @@ const {
__webpack_public_path__ = `${assetPrefix}/_next/webpack/` //eslint-disable-line
// Initialize next/asset with the assetPrefix
asset.setAssetPrefix(assetPrefix)
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig: {},
publicRuntimeConfig: runtimeConfig
})
const asPath = getURL()
......
import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?autoConnect=false'
import 'event-source-polyfill'
import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?autoConnect=false&overlay=false&reload=true'
import Router from '../lib/router'
const {
......@@ -9,8 +10,6 @@ const {
export default () => {
webpackHotMiddlewareClient.setOptionsAndConnect({
overlay: false,
reload: true,
path: `${assetPrefix}/_next/webpack-hmr`
})
......
module.exports = require('./dist/lib/runtime-config')
module.exports = require('./dist/lib/constants')
# Router.onAppUpdated is removed
Due to [this bug fix](https://github.com/zeit/next.js/pull/3849), we had to remove the `Router.onAppUpdated` hook. But the default functionality of this feature is still in effect.
We use this hook to detect a new app deployment when switching pages and act accordingly. Although there are many things you can do in this hook, it's often used to navigate the page via the server as shown below:
```js
Router.onAppUpdated = function(nextRoute) {
location.href = nextRoute
}
```
In this hook, you can't wait for a network request or a promise to get resolved. And you can't block the page navigation. So, the things you can do is limited.
One real use of this hook is to persist your application state to local-storage before the page navigation. For that, you can use the [`window.onbeforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) hook instead.
This is code for that:
```js
window.onbeforeunload = function(e) {
// Get the application state (usually from a store like Redux)
const appState = {}
localStorage.setItem('app-state', JSON.stringify(appState));
};
```
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example active-class-name active-class-name-app
# or
yarn create next-app --example active-class-name active-class-name-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example basic-css basic-css-app
# or
yarn create next-app --example basic-css basic-css-app
```
### Download manually
......
# Running Next.JS and React /inside/ of ActionHero
This server will render dynamic next.js/react pages on some routes, and normal ActionHero API requests on others.
This configuration works with both Next and ActionHero hot reloading of code.
A more detailed example showcasing how to use fetch and web sockets to interact with your API can be found here: https://github.com/actionhero/next-in-actionhero
## To install:
(assuming you have [node](http://nodejs.org/) and NPM installed)
`npm install`
## To Run:
`npm start`
## How does this work?
1. Create an initializer to load next.js and create a handler that can extract the normal node `req` and `res` from the connection
```js
// initializers/next.js
const {Initializer, api} = require('actionhero')
const next = require('next')
module.exports = class NextInitializer extends Initializer {
constructor () {
super()
this.name = 'next'
}
async initialize () {
api.next = {
render: async (connection) => {
if (connection.type !== 'web') { throw new Error('Connections for NEXT apps must be of type "web"') }
const req = connection.rawConnection.req
const res = connection.rawConnection.res
return api.next.handle(req, res)
}
}
api.next.dev = (api.env === 'development')
if (api.next.dev) { api.log('Running next in development mode...') }
api.next.app = next({dev: api.next.dev})
api.next.handle = api.next.app.getRequestHandler()
await api.next.app.prepare()
}
async stop () {
await api.next.app.close()
}
}
```
2. Create an action which will run the above `api.next.render(connection)`. Note that we will not be relying on ActionHero to respond to the client's request in this case, and leave that up to next (via: `data.toRender = false`)
```js
// actions/next.js
const {Action, api} = require('actionhero')
module.exports = class CreateChatRoom extends Action {
constructor () {
super()
this.name = 'render'
this.description = 'I render the next.js react website'
}
async run (data) {
data.toRender = false
return api.next.render(data.connection)
}
}
```
3. Tell ActionHero to use the api rather than the file server as the top-level route in `api.config.servers.web.rootEndpointType = 'api'`. This will allows "/" to listen to API requests. Also update `api.config.general.paths.public = [ path.join(__dirname, '/../static') ]`. In this configuration, the next 'static' renderer will take priority over the ActionHero 'public file' api. Note that any static assets (CSS, fonts, etc) will need to be in "./static" rather than "./public".
Note that this is where the websocket server, if you enable it, will place the `ActionheroWebsocketClient` libraray.
4. Configure a wild-card route at the lowest priority of your GET handler to catch all web requests that aren't caught by other actions:
```js
// config/routes.js
exports['default'] = {
routes: (api) => {
return {
get: [
{ path: '/time', action: 'time' },
{ path: '/', matchTrailingPathParts: true, action: 'render' }
]
}
}
}
```
'use strict'
const {Action, api} = require('actionhero')
module.exports = class CreateChatRoom extends Action {
constructor () {
super()
this.name = 'render'
this.description = 'I render the next.js react website'
}
async run (data) {
data.toRender = false
return api.next.render(data.connection)
}
}
'use strict'
const path = require('path')
exports['default'] = {
general: (api) => {
const packageJSON = require(api.projectRoot + path.sep + 'package.json')
return {
apiVersion: packageJSON.version,
serverName: packageJSON.name,
// id can be set here, or it will be generated dynamically.
// Be sure that every server you run has a unique ID (which will happen when generated dynamically)
// id: 'myActionHeroServer',
// A unique token to your application that servers will use to authenticate to each other
serverToken: 'change-me',
// the redis prefix for actionhero's cache objects
cachePrefix: 'actionhero:cache:',
// the redis prefix for actionhero's cache/lock objects
lockPrefix: 'actionhero:lock:',
// how long will a lock last before it exipres (ms)?
lockDuration: 1000 * 10, // 10 seconds
// Watch for changes in actions and tasks, and reload/restart them on the fly
developmentMode: true,
// How many pending actions can a single connection be working on
simultaneousActions: 5,
// allow connections to be created without remoteIp and remotePort (they will be set to 0)
enforceConnectionProperties: true,
// disables the whitelisting of client params
disableParamScrubbing: false,
// params you would like hidden from any logs
filteredParams: [],
// values that signify missing params
missingParamChecks: [null, '', undefined],
// The default filetype to server when a user requests a directory
directoryFileType: 'index.html',
// What log-level should we use for file requests?
fileRequestLogLevel: 'info',
// The default priority level given to middleware of all types (action, connection, say, and task)
defaultMiddlewarePriority: 100,
// Which channel to use on redis pub/sub for RPC communication
channel: 'actionhero',
// How long to wait for an RPC call before considering it a failure
rpcTimeout: 5000,
// should CLI methods and help include internal ActionHero CLI methods?
cliIncludeInternal: true,
// configuration for your actionhero project structure
paths: {
'action': [path.join(__dirname, '/../actions')],
'task': [path.join(__dirname, '/../tasks')],
'public': [path.join(__dirname, '/../static')],
'pid': [path.join(__dirname, '/../pids')],
'log': [path.join(__dirname, '/../log')],
'server': [path.join(__dirname, '/../servers')],
'cli': [path.join(__dirname, '/../bin')],
'initializer': [path.join(__dirname, '/../initializers')],
'plugin': [path.join(__dirname, '/../node_modules')],
'locale': [path.join(__dirname, '/../locales')]
},
// hash containing chat rooms you wish to be created at server boot
startingChatRooms: {
// format is {roomName: {authKey, authValue}}
// 'secureRoom': {authorized: true},
}
}
}
}
exports.test = {
general: (api) => {
return {
id: 'test-server-' + process.pid,
serverToken: 'serverToken-' + process.pid,
developmentMode: true,
startingChatRooms: {
'defaultRoom': {},
'otherRoom': {}
},
paths: {
'locale': [
// require('os').tmpdir() + require('path').sep + 'locales',
path.join(__dirname, '/../locales')
]
},
rpcTimeout: 3000
}
}
}
exports.production = {
general: (api) => {
return {
fileRequestLogLevel: 'debug',
developmentMode: false
}
}
}
'use strict'
// error messages can be strings of objects
exports['default'] = {
errors: (api) => {
return {
'_toExpand': false,
// ///////////////
// SERIALIZERS //
// ///////////////
serializers: {
servers: {
web: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
websocket: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
socket: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
specHelper: (error) => {
if (error.message) {
return 'Error: ' + String(error.message)
} else {
return error
}
}
}
},
// ///////////
// ACTIONS //
// ///////////
// When a params for an action is invalid
invalidParams: (data, validationErrors) => {
if (validationErrors.length >= 0) { return validationErrors[0] }
return data.connection.localize('actionhero.errors.invalidParams')
},
// When a required param for an action is not provided
missingParams: (data, missingParams) => {
return data.connection.localize(['actionhero.errors.missingParams', {param: missingParams[0]}])
},
// user requested an unknown action
unknownAction: (data) => {
return data.connection.localize('actionhero.errors.unknownAction')
},
// action not useable by this client/server type
unsupportedServerType: (data) => {
return data.connection.localize(['actionhero.errors.unsupportedServerType', {type: data.connection.type}])
},
// action failed because server is mid-shutdown
serverShuttingDown: (data) => {
return data.connection.localize('actionhero.errors.serverShuttingDown')
},
// action failed because this client already has too many pending acitons
// limit defined in api.config.general.simultaneousActions
tooManyPendingActions: (data) => {
return data.connection.localize('actionhero.errors.tooManyPendingActions')
},
dataLengthTooLarge: (maxLength, receivedLength) => {
return api.i18n.localize(['actionhero.errors.dataLengthTooLarge', {maxLength: maxLength, receivedLength: receivedLength}])
},
// ///////////////
// FILE SERVER //
// ///////////////
// The body message to accompany 404 (file not found) errors regarding flat files
// You may want to load in the contnet of 404.html or similar
fileNotFound: (connection) => {
return connection.localize(['actionhero.errors.fileNotFound'])
},
// user didn't request a file
fileNotProvided: (connection) => {
return connection.localize('actionhero.errors.fileNotProvided')
},
// something went wrong trying to read the file
fileReadError: (connection, error) => {
return connection.localize(['actionhero.errors.fileReadError', {error: String(error)}])
},
// ///////////////
// CONNECTIONS //
// ///////////////
verbNotFound: (connection, verb) => {
return connection.localize(['actionhero.errors.verbNotFound', {verb: verb}])
},
verbNotAllowed: (connection, verb) => {
return connection.localize(['actionhero.errors.verbNotAllowed', {verb: verb}])
},
connectionRoomAndMessage: (connection) => {
return connection.localize('actionhero.errors.connectionRoomAndMessage')
},
connectionNotInRoom: (connection, room) => {
return connection.localize(['actionhero.errors.connectionNotInRoom', {room: room}])
},
connectionAlreadyInRoom: (connection, room) => {
return connection.localize(['actionhero.errors.connectionAlreadyInRoom', {room: room}])
},
connectionRoomHasBeenDeleted: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomHasBeenDeleted')
},
connectionRoomNotExist: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomNotExist')
},
connectionRoomExists: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomExists')
},
connectionRoomRequired: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomRequired')
}
}
}
}
exports['default'] = {
i18n: (api) => {
return {
// visit https://github.com/mashpie/i18n-node to see all configuration options
// locale path can be configired from within ./config/api.js
locales: ['en'],
// how would you like your lanaguages to fall back if a translation string is missing?
fallbacks: {
// 'es': 'en'
},
// configure i18n to allow for object-style key lookup
objectNotation: true,
// should actionhero append any missing translations to the locale file?
updateFiles: true,
// this will configure logging and error messages in the log(s)
defaultLocale: 'en',
// the name of the method by which to determine the connection's locale
// by default, every request will be in the 'en' locale
// this method will be called witin the localiazation middleware on all requests
determineConnectionLocale: 'api.i18n.determineConnectionLocale'
}
}
}
exports.test = {
i18n: (api) => {
return {
updateFiles: true
}
}
}
'use strict'
const fs = require('fs')
const cluster = require('cluster')
exports['default'] = {
logger: (api) => {
let logger = {transports: []}
// console logger
if (cluster.isMaster) {
logger.transports.push(function (api, winston) {
return new (winston.transports.Console)({
colorize: true,
level: 'info',
timestamp: function () { return api.id + ' @ ' + new Date().toISOString() }
})
})
}
// file logger
logger.transports.push(function (api, winston) {
if (api.config.general.paths.log.length === 1) {
const logDirectory = api.config.general.paths.log[0]
try {
fs.mkdirSync(logDirectory)
} catch (e) {
if (e.code !== 'EEXIST') {
throw (new Error('Cannot create log directory @ ' + logDirectory))
}
}
}
return new (winston.transports.File)({
filename: api.config.general.paths.log[0] + '/' + api.pids.title + '.log',
level: 'info',
timestamp: function () { return api.id + ' @ ' + new Date().toISOString() }
})
})
// the maximum length of param to log (we will truncate)
logger.maxLogStringLength = 100
// you can optionally set custom log levels
// logger.levels = {good: 0, bad: 1};
// you can optionally set custom log colors
// logger.colors = {good: 'blue', bad: 'red'};
return logger
}
}
exports.test = {
logger: (api) => {
return {
transports: null
}
}
}
exports['default'] = {
plugins: (api) => {
/*
If you want to use plugins in your application, include them here:
return {
'myPlugin': { path: __dirname + '/../node_modules/myPlugin' }
}
You can also toggle on or off sections of a plugin to include (default true for all sections):
return {
'myPlugin': {
path: __dirname + '/../node_modules/myPlugin',
actions: true,
tasks: true,
initializers: true,
servers: true,
public: true,
cli: true
}
}
*/
return {}
}
}
let host = process.env.REDIS_HOST || '127.0.0.1'
let port = process.env.REDIS_PORT || 6379
let db = process.env.REDIS_DB || 0
let password = process.env.REDIS_PASSWORD || null
const maxBackoff = 1000
if (process.env.REDIS_URL) {
password = process.env.REDIS_URL.match(/redis:\/\/.*:(.*)@.*:\d*$/i)[1]
host = process.env.REDIS_URL.match(/redis:\/\/.*:.*@(.*):\d*$/i)[1]
port = parseInt(process.env.REDIS_URL.match(/redis:\/\/.*:.*@.*:(\d*)$/i)[1])
}
exports['default'] = {
redis: (api) => {
// konstructor: The redis client constructor method. All redis methods must be promises
// args: The arguments to pass to the constructor
// buildNew: is it `new konstructor()` or just `konstructor()`?
function retryStrategy (times) {
if (times === 1) {
const error = 'Unable to connect to Redis - please check your Redis config!'
if (process.env.NODE_ENV === 'test') { console.error(error) } else { api.log(error, 'error') }
return 5000
}
return Math.min(times * 50, maxBackoff)
}
return {
enabled: true,
'_toExpand': false,
client: {
konstructor: require('ioredis'),
args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
buildNew: true
},
subscriber: {
konstructor: require('ioredis'),
args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
buildNew: true
},
tasks: {
konstructor: require('ioredis'),
args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
buildNew: true
}
}
}
}
exports['default'] = {
routes: (api) => {
return {
get: [
{ path: '/', matchTrailingPathParts: true, action: 'render' }
]
}
}
}
'use strict'
exports['default'] = {
servers: {
socket: (api) => {
return {
enabled: (process.env.ENABLE_TCP_SERVER !== undefined),
// TCP or TLS?
secure: false,
// Passed to tls.createServer if secure=true. Should contain SSL certificates
serverOptions: {},
// Port or Socket
port: 5000,
// Which IP to listen on (use 0.0.0.0 for all)
bindIP: '0.0.0.0',
// Enable TCP KeepAlive pings on each connection?
setKeepAlive: false,
// Delimiter string for incoming messages
delimiter: '\n',
// Maximum incoming message string length in Bytes (use 0 for Infinite)
maxDataLength: 0
}
}
}
}
exports.test = {
servers: {
socket: (api) => {
return {
enabled: true,
port: 1001 + (process.pid % 64535),
secure: false
}
}
}
}
'use strict'
const os = require('os')
exports['default'] = {
servers: {
web: (api) => {
return {
enabled: true,
// HTTP or HTTPS?
secure: false,
// Passed to https.createServer if secure=true. Should contain SSL certificates
serverOptions: {},
// Should we redirect all traffic to the first host in this array if hte request header doesn't match?
// i.e.: [ 'https://www.site.com' ]
allowedRequestHosts: process.env.ALLOWED_HOSTS ? process.env.ALLOWED_HOSTS.split(',') : [],
// Port or Socket Path
port: process.env.PORT || 8080,
// Which IP to listen on (use '0.0.0.0' for all; '::' for all on ipv4 and ipv6)
// Set to `null` when listening to socket
bindIP: '0.0.0.0',
// Any additional headers you want actionhero to respond with
httpHeaders: {
'X-Powered-By': api.config.general.serverName,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE',
'Access-Control-Allow-Headers': 'Content-Type'
},
// Route that actions will be served from; secondary route against this route will be treated as actions,
// IE: /api/?action=test == /api/test/
urlPathForActions: 'api',
// Route that static files will be served from;
// path (relative to your project root) to serve static content from
// set to `null` to disable the file server entirely
urlPathForFiles: 'public',
// When visiting the root URL, should visitors see 'api' or 'file'?
// Visitors can always visit /api and /public as normal
rootEndpointType: 'api',
// simple routing also adds an 'all' route which matches /api/:action for all actions
simpleRouting: true,
// queryRouting allows an action to be defined via a URL param, ie: /api?action=:action
queryRouting: true,
// The cache or (if etags are enabled) next-revalidation time to be returned for all flat files served from /public; defined in seconds
flatFileCacheDuration: 60,
// Add an etag header to requested flat files which acts as fingerprint that changes when the file is updated;
// Client will revalidate the fingerprint at latest after flatFileCacheDuration and reload it if the etag (and therfore the file) changed
// or continue to use the cached file if it's still valid
enableEtag: true,
// should we save the un-parsed HTTP POST/PUT payload to connection.rawConnection.params.rawBody?
saveRawBody: false,
// How many times should we try to boot the server?
// This might happen if the port is in use by another process or the socketfile is claimed
bootAttempts: 1,
// Settings for determining the id of an http(s) request (browser-fingerprint)
fingerprintOptions: {
cookieKey: 'sessionID',
toSetCookie: true,
onlyStaticElements: false,
settings: {
path: '/',
expires: 3600000
}
},
// Options to be applied to incoming file uploads.
// More options and details at https://github.com/felixge/node-formidable
formOptions: {
uploadDir: os.tmpdir(),
keepExtensions: false,
maxFieldsSize: 1024 * 1024 * 100
},
// Should we pad JSON responses with whitespace to make them more human-readable?
// set to null to disable
padding: 2,
// Options to configure metadata in responses
metadataOptions: {
serverInformation: true,
requesterInformation: true
},
// When true, returnErrorCodes will modify the response header for http(s) clients if connection.error is not null.
// You can also set connection.rawConnection.responseHttpCode to specify a code per request.
returnErrorCodes: true,
// should this node server attempt to gzip responses if the client can accept them?
// this will slow down the performance of actionhero, and if you need this funcionality, it is recommended that you do this upstream with nginx or your load balancer
compress: false,
// options to pass to the query parser
// learn more about the options @ https://github.com/hapijs/qs
queryParseOptions: {}
}
}
}
}
exports.production = {
servers: {
web: (api) => {
return {
padding: null,
metadataOptions: {
serverInformation: false,
requesterInformation: false
}
}
}
}
}
exports.test = {
servers: {
web: (api) => {
return {
secure: false,
port: process.env.PORT || 1000 + (process.pid % 64535),
matchExtensionMime: true,
metadataOptions: {
serverInformation: true,
requesterInformation: true
}
}
}
}
}
'use strict'
// Note that to use the websocket server, you also need the web server enabled
exports['default'] = {
servers: {
websocket: (api) => {
return {
enabled: true,
// you can pass a FQDN (string) here or 'window.location.origin'
clientUrl: 'window.location.origin',
// Directory to render client-side JS.
// Path should start with "/" and will be built starting from api.config..general.paths.public
clientJsPath: 'javascript/',
// the name of the client-side JS file to render. Both `.js` and `.min.js` versions will be created
// do not include the file exension
// set to `undefined` to not render the client-side JS on boot
clientJsName: 'ActionheroWebsocketClient',
// should the server signal clients to not reconnect when the server is shutdown/reboot
destroyClientsOnShutdown: false,
// websocket Server Options:
server: {
// authorization: null,
// pathname: '/primus',
// parser: 'JSON',
// transformer: 'websockets',
// plugin: {},
// timeout: 35000,
// origins: '*',
// methods: ['GET','HEAD','PUT','POST','DELETE','OPTIONS'],
// credentials: true,
// maxAge: '30 days',
// exposed: false,
},
// websocket Client Options:
client: {
apiPath: '/api' // the api base endpoint on your actionhero server
// reconnect: {},
// timeout: 10000,
// ping: 25000,
// pong: 10000,
// strategy: "online",
// manual: false,
// websockets: true,
// network: true,
// transport: {},
// queueSize: Infinity,
}
}
}
}
}
exports['test'] = {
servers: {
websocket: (api) => {
return { clientUrl: null }
}
}
}
exports['default'] = {
tasks: (api) => {
return {
// Should this node run a scheduler to promote delayed tasks?
scheduler: false,
// what queues should the taskProcessors work?
queues: ['*'],
// Logging levels of task workers
workerLogging: {
failure: 'error', // task failure
success: 'info', // task success
start: 'info',
end: 'info',
cleaning_worker: 'info',
poll: 'debug',
job: 'debug',
pause: 'debug',
internalError: 'error',
multiWorkerAction: 'debug'
},
// Logging levels of the task scheduler
schedulerLogging: {
start: 'info',
end: 'info',
poll: 'debug',
enqueue: 'debug',
reEnqueue: 'debug',
working_timestamp: 'debug',
transferred_job: 'debug'
},
// how long to sleep between jobs / scheduler checks
timeout: 5000,
// at minimum, how many parallel taskProcessors should this node spawn?
// (have number > 0 to enable, and < 1 to disable)
minTaskProcessors: 0,
// at maximum, how many parallel taskProcessors should this node spawn?
maxTaskProcessors: 0,
// how often should we check the event loop to spawn more taskProcessors?
checkTimeout: 500,
// how many ms would constitue an event loop delay to halt taskProcessors spawning?
maxEventLoopDelay: 5,
// When we kill off a taskProcessor, should we disconnect that local redis connection?
toDisconnectProcessors: true,
// Customize Resque primitives, replace null with required replacement.
resque_overrides: {
queue: null,
multiWorker: null,
scheduler: null
}
}
}
}
exports.test = {
tasks: (api) => {
return {
timeout: 100,
checkTimeout: 50
}
}
}
'use strict'
const {Initializer, api} = require('actionhero')
const next = require('next')
module.exports = class NextInitializer extends Initializer {
constructor () {
super()
this.name = 'next'
}
async initialize () {
api.next = {
render: async (connection) => {
if (connection.type !== 'web') { throw new Error('Connections for NEXT apps must be of type "web"') }
const req = connection.rawConnection.req
const res = connection.rawConnection.res
return api.next.handle(req, res)
}
}
api.next.dev = (api.env === 'development')
if (api.next.dev) { api.log('Running next in development mode...') }
api.next.app = next({dev: api.next.dev})
api.next.handle = api.next.app.getRequestHandler()
await api.next.app.prepare()
}
async stop () {
await api.next.app.close()
}
}
{
"actionhero": {
"welcomeMessage": "Hello! Welcome to the actionhero api",
"goodbyeMessage": "Bye!",
"cache": {
"objectNotFound": "Object not found",
"objectLocked": "Object locked",
"objectExpired": "Object expired"
},
"errors": {
"invalidParams": "validation error",
"missingParams": "{{param}} is a required parameter for this action",
"unknownAction": "unknown action or invalid apiVersion",
"unsupportedServerType": "this action does not support the {{type}} connection type",
"serverShuttingDown": "the server is shutting down",
"tooManyPendingActions": "you have too many pending requests",
"dataLengthTooLarge": "data length is too big ({{maxLength}} received/{{receivedLength}} max)",
"fileNotFound": "That file is not found",
"fileNotProvided": "file is a required param to send a file",
"fileReadError": "error reading file: {{error}}",
"verbNotFound": "I do not know know to perform this verb ({{verb}})",
"verbNotAllowed": "verb not found or not allowed ({{verb}})",
"connectionRoomAndMessage": "both room and message are required",
"connectionNotInRoom": "connection not in this room ({{room}})",
"connectionAlreadyInRoom": "connection already in this room ({{room}})",
"connectionRoomHasBeenDeleted": "this room has been deleted",
"connectionRoomNotExist": "room does not exist",
"connectionRoomExists": "room exists",
"connectionRoomRequired": "a room is required"
}
},
"Your random number is {{number}}": "Your random number is {{number}}",
"Node Healthy": "Node Healthy"
}
{
"engines": {
"node": ">=8.0.0"
},
"dependencies": {
"actionhero": "^18.1.2",
"ioredis": "^3.2.2",
"isomorphic-fetch": "^2.2.1",
"next": "^5.0.1-canary.9",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"ws": "^4.1.0"
},
"scripts": {
"start": "actionhero start"
}
}
export default () => <div>a</div>
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>
)
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-express custom-server-express-app
# or
yarn create next-app --example custom-server-express custom-server-express-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-fastify custom-server-fastify-app
# or
yarn create next-app --example custom-server-fastify custom-server-fastify-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-hapi custom-server-hapi-app
# or
yarn create next-app --example custom-server-hapi custom-server-hapi-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-koa custom-server-koa-app
# or
yarn create next-app --example custom-server-koa custom-server-koa-app
```
### Download manually
......
......@@ -33,8 +33,7 @@ app.prepare()
})
server.use(router.routes())
server.listen(port, (err) => {
if (err) throw err
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`)
})
})
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-micro custom-server-micro-app
# or
yarn create next-app --example custom-server-micro custom-server-micro-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server-nodemon custom-server-nodemon-app
# or
yarn create next-app --example custom-server-nodemon custom-server-nodemon-app
```
### Download manually
......
[![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-typescript)
# Custom server with TypeScript + Nodemon 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 custom-server-typescript custom-server-typescript-app
# or
yarn create next-app --example custom-server-typescript custom-server-typescript-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-typescript
cd custom-server-typescript
```
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 use [TypeScript](https://typescriptlang.com) on both the server and the client while using [Nodemon](https://nodemon.io/) to live reload the server code without affecting the Next.js universal code.
Server entry point is `server/index.ts` in development and `production-server/index.js` in production.
The second directory should be added to `.gitignore`.
const withTypescript = require('@zeit/next-typescript')
module.exports = withTypescript()
{
"watch": ["server/**/*.ts"],
"execMap": {
"ts": "ts-node --compilerOptions '{\"module\":\"commonjs\"}'"
}
}
{
"scripts": {
"dev": "nodemon server/index.ts",
"build": "next build && tsc --project tsconfig.server.json",
"start": "NODE_ENV=production node production-server/index.js"
},
"dependencies": {
"next": "latest",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"@types/next": "^2.4.7",
"@types/react": "^16.0.36",
"@zeit/next-typescript": "^0.0.8",
"nodemon": "^1.12.1",
"ts-node": "^4.1.0",
"typescript": "^2.7.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='/a' as='/a'><a>a</a></Link></li>
<li><Link href='/b' as='/b'><a>b</a></Link></li>
</ul>
)
import { createServer } from 'http'
import { parse } from 'url'
import * as next from '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, '/a', query)
} else if (pathname === '/b') {
app.render(req, res, '/b', query)
} else {
handle(req, res, parsedUrl)
}
})
.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
{
"compileOnSave": false,
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"jsx": "preserve",
"allowJs": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true,
"baseUrl": ".",
"typeRoots": [
"./node_modules/@types"
],
"lib": [
"dom",
"es2015",
"es2016"
]
}
}
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "production-server/"
},
"include": ["server/**/*.ts"]
}
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example custom-server custom-server-app
# or
yarn create next-app --example custom-server custom-server-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example data-fetch data-fetch-app
# or
yarn create next-app --example data-fetch data-fetch-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example form-handler form-handler-app
# or
yarn create next-app --example form-handler form-handler-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example head-elements head-elements-app
# or
yarn create next-app --example head-elements head-elements-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example hello-world hello-world-app
# or
yarn create next-app --example hello-world hello-world-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example layout-component layout-component-app
# or
yarn create next-app --example layout-component layout-component-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example nested-components nested-components-app
# or
yarn create next-app --example nested-components nested-components-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example page-transitions page-transitions-app
# or
yarn create next-app --example page-transitions page-transitions-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example parameterized-routing parameterized-routing-app
# or
yarn create next-app --example parameterized-routing parameterized-routing-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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
```bash
npx create-next-app --example progressive-render progressive-render-app
# or
yarn create next-app --example progressive-render progressive-render-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example root-static-files root-static-files-app
# or
yarn create next-app --example root-static-files root-static-files-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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
```bash
npx create-next-app --example shared-modules shared-modules-app
# or
yarn create next-app --example shared-modules shared-modules-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example ssr-caching ssr-caching-app
# or
yarn create next-app --example ssr-caching ssr-caching-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example svg-components svg-components-app
# or
yarn create next-app --example svg-components svg-components-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example using-inferno using-inferno-app
# or
yarn create next-app --example using-inferno using-inferno-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-nerv using-nerv-app
```bash
npx create-next-app --example using-nerv using-nerv-app
# or
yarn create next-app --example using-nerv using-nerv-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example using-preact using-preact-app
# or
yarn create next-app --example using-preact using-preact-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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
```bash
npx create-next-app --example using-router using-router-app
# or
yarn create next-app --example using-router using-router-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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
```bash
npx create-next-app --example using-with-router using-with-router-app
# or
yarn create next-app --example using-with-router using-with-router-app
```
### Download manually
......
{
"presets": "next/babel",
"presets": ["next/babel"],
"plugins": [
[
"module-resolver",
......
......@@ -6,9 +6,10 @@
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
```bash
npx create-next-app --example with-absolute-imports with-absolute-imports-app
# or
yarn create next-app --example with-absolute-imports with-absolute-imports-app
```
### Download manually
......@@ -16,8 +17,8 @@ create-next-app --example with-absolute-imports with-absolute-imports-app
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-absolute-import
cd with-absolute-import
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-absolute-imports
cd with-absolute-imports
```
Install it and run:
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
# or
yarn create next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-amp with-amp-app
# or
yarn create next-app --example with-amp with-amp-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-analytics with-analytics-app
```bash
npx create-next-app --example with-analytics with-analytics-app
# or
yarn create next-app --example with-analytics with-analytics-app
```
### Download manually
......
......@@ -6,7 +6,7 @@
"import",
{
"libraryName": "antd",
"style": false
"style": "css"
}
]
]
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-ant-design with-ant-design-app
# or
yarn create next-app --example with-ant-design with-ant-design-app
```
### Download manually
......
......@@ -4,7 +4,7 @@ export default ({ children }) =>
<Head>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<meta charSet='utf-8' />
<link rel='stylesheet' href='https://unpkg.com/antd@3/dist/antd.min.css' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
<style jsx global>{`
body {
......
const withCss = require('@zeit/next-css')
// fix: prevents error when .css files are required by node
if (typeof require !== 'undefined') {
require.extensions['.css'] = (file) => {}
}
module.exports = withCss()
......@@ -7,7 +7,8 @@
"start": "next start"
},
"dependencies": {
"antd": "^3.0.2",
"@zeit/next-css": "^0.1.4",
"antd": "^3.3.1",
"babel-plugin-import": "^1.1.1",
"next": "latest",
"react": "^16.0.0",
......
......@@ -7,9 +7,10 @@
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
```bash
npx create-next-app --example with-antd-mobile with-antd-mobile-app
# or
yarn create next-app --example with-antd-mobile with-antd-mobile-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-aphrodite with-aphrodite-app
# or
yarn create next-app --example with-aphrodite with-aphrodite-app
```
### Download manually
......
[![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-apollo-and-redux)
# Apollo & Redux Saga 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-apollo-and-redux-saga with-apollo-and-redux-saga-app
# or
yarn create next-app --example with-apollo-and-redux-saga with-apollo-and-redux-saga-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-apollo-and-redux-saga
cd with-apollo-and-redux-saga
```
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
In 2.0.0, Apollo Client severs out-of-the-box support for redux in favor of Apollo's client side state management. This example aims to be an amalgamation of the [`with-apollo`](https://github.com/zeit/next.js/tree/master/examples/with-apollo) and [`with-redux-saga`](https://github.com/zeit/next.js/tree/master/examples/with-redux-saga) examples.
Note that you can access the redux store like you normally would using `react-redux`'s `connect`. Here's a quick example:
```js
const mapStateToProps = state => ({
location: state.form.location,
});
export default withReduxSaga(connect(mapStateToProps, null)(Index));
```
`connect` must go inside `withReduxSaga` otherwise `connect` will not be able to find the store.
export default ({ children }) => (
<main>
{children}
<style jsx global>{`
* {
font-family: Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif;
}
body {
margin: 0;
padding: 25px 50px;
}
a {
color: #22BAD9;
}
p {
font-size: 14px;
line-height: 24px;
}
h1 {
font-size: 1.5rem;
}
article {
text-align: left;
margin: 0;
max-width: 650px;
}
button {
align-items: center;
background-color: #22BAD9;
border: 0;
color: white;
display: flex;
padding: 5px 7px;
}
button:active {
background-color: #1B9DB7;
transition: background-color .3s
}
button:focus {
outline: none;
}
`}</style>
</main>
)
import React from 'react'
const pad = n => (n < 10 ? `0${n}` : n)
const format = t => {
const hours = t.getUTCHours()
const minutes = t.getUTCMinutes()
const seconds = t.getUTCSeconds()
return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
}
function Clock ({ lastUpdate, light }) {
return (
<React.Fragment>
<h2>Clock:</h2>
<div className={light ? 'light' : ''}>
{format(new Date(lastUpdate || Date.now()))}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
</React.Fragment>
)
}
export default Clock
export default ({message}) => (
<aside>
{message}
<style jsx>{`
aside {
padding: 1.5em;
font-size: 14px;
color: white;
background-color: red;
}
`}</style>
</aside>
)
import Link from 'next/link'
import { withRouter } from 'next/router'
const Header = ({ router: { pathname } }) => (
<header>
<Link prefetch href='/'>
<a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link>
<Link prefetch href='/about'>
<a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link>
<Link prefetch href='/blog'>
<a className={pathname === '/blog' ? 'is-active' : ''}>Blog</a>
</Link>
<style jsx>{`
header {
margin-bottom: 25px;
}
a {
font-size: 14px;
margin-right: 15px;
text-decoration: none;
}
.is-active {
text-decoration: underline;
}
`}</style>
</header>
)
export default withRouter(Header)
import React from 'react'
import { connect } from 'react-redux'
import PageCount from './PageCount'
import Clock from './Clock'
import Placeholder from './Placeholder'
function Page ({ clock, placeholder, linkTo, title }) {
return (
<React.Fragment>
<h1>{title}</h1>
<Clock lastUpdate={clock.lastUpdate} light={clock.light} />
<PageCount />
<Placeholder placeholder={placeholder} />
</React.Fragment>
)
}
export default connect(state => state)(Page)
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { countIncrease, countDecrease } from '../lib/count/actions'
class PageCount extends Component {
increase = () => {
this.props.dispatch(countIncrease())
}
decrease = () => {
this.props.dispatch(countDecrease())
}
render () {
const { count } = this.props
return (
<div>
<style jsx>{`
div {
padding: 0 0 20px 0;
}
`}</style>
<h1>
PageCount: <span>{count}</span>
</h1>
<button onClick={this.increase}>Increase Count (+1)</button>
<button onClick={this.decrease}>Decrease Count (-1)</button>
</div>
)
}
}
const mapStateToProps = ({ count }) => ({ count })
export default connect(mapStateToProps)(PageCount)
import React from 'react'
export default ({placeholder}) => (
<React.Fragment>
<h2>JSON:</h2>
{placeholder.data && (
<pre>
<code>{JSON.stringify(placeholder.data, null, 2)}</code>
</pre>
)}
{placeholder.error && (
<p style={{ color: 'red' }}>Error: {placeholder.error.message}</p>
)}
<style jsx>{`
aside {
font-size: 14px;
}
`}</style>
</React.Fragment>
)
import React from 'react'
import { withRouter } from 'next/router'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import ErrorMessage from './ErrorMessage'
import PostVoteUp from './PostVoteUp'
import PostVoteDown from './PostVoteDown'
import PostVoteCount from './PostVoteCount'
function Post ({ id, data: { error, Post } }) {
if (error) return <ErrorMessage message='Error loading blog post.' />
if (Post) {
return (
<section>
<div key={Post.id}>
<h1>{Post.title}</h1>
<p>ID: {Post.id}<br />URL: {Post.url}</p>
<span>
<PostVoteUp id={Post.id} votes={Post.votes} />
<PostVoteCount votes={Post.votes} />
<PostVoteDown id={Post.id} votes={Post.votes} />
</span>
</div>
<style jsx>{`
span {
display: flex;
font-size: 14px;
margin-right: 5px;
}
`}</style>
</section>
)
}
return <div>Loading</div>
}
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)
const ComponentWithMutation = graphql(post, {
options: ({ router: { query } }) => ({
variables: {
id: query.id
}
}),
props: ({ data }) => ({
data
})
})(Post)
export default withRouter(ComponentWithMutation)
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { Router } from '../routes'
import ErrorMessage from './ErrorMessage'
import PostVoteUp from './PostVoteUp'
import PostVoteDown from './PostVoteDown'
import PostVoteCount from './PostVoteCount'
const POSTS_PER_PAGE = 10
function handleClick (event, id) {
event.preventDefault()
// With route name and params
// Router.pushRoute('blog/entry', { id: id })
// With route URL
Router.pushRoute(`/blog/${id}`)
}
function PostList ({
data: { loading, error, allPosts, _allPostsMeta },
loadMorePosts
}) {
if (error) return <ErrorMessage message='Error loading posts.' />
if (allPosts && allPosts.length) {
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
<section>
<ul>
{allPosts.map((post, index) => (
<li key={post.id}>
<div>
<span>{index + 1}. </span>
<a
href={`/blog/${post.id}`}
onClick={(event) => handleClick(event, post.id)}
>
{post.title}
</a>
<PostVoteUp id={post.id} votes={post.votes} />
<PostVoteCount votes={post.votes} />
<PostVoteDown id={post.id} votes={post.votes} />
</div>
</li>
))}
</ul>
{areMorePosts ? (
<button onClick={() => loadMorePosts()}>
{' '}
{loading ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{`
section {
padding-bottom: 20px;
}
li {
display: block;
margin-bottom: 10px;
}
div {
align-items: center;
display: flex;
}
a {
font-size: 14px;
margin-right: 10px;
text-decoration: none;
padding-bottom: 0;
border: 0;
}
span {
font-size: 14px;
margin-right: 5px;
}
ul {
margin: 0;
padding: 0;
}
button:before {
align-self: center;
border-style: solid;
border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent;
content: '';
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</section>
)
}
return <div>Loading</div>
}
export const allPosts = gql`
query allPosts($first: Int!, $skip: Int!) {
allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) {
id
title
votes
url
createdAt
}
_allPostsMeta {
count
}
}
`
export const allPostsQueryVars = {
skip: 0,
first: POSTS_PER_PAGE
}
// The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList)
export default graphql(allPosts, {
options: {
variables: allPostsQueryVars
},
props: ({ data }) => ({
data,
loadMorePosts: () => {
return data.fetchMore({
variables: {
skip: data.allPosts.length
},
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult
}
return Object.assign({}, previousResult, {
// Append the new posts results to the old one
allPosts: [...previousResult.allPosts, ...fetchMoreResult.allPosts]
})
}
})
}
})
})(PostList)
export default ({id, votes, onClickHandler, className}) => (
<button className={className} onClick={() => onClickHandler()}>
<style jsx>{`
button {
background-color: transparent;
border: 1px solid #e4e4e4;
color: #000;
}
button:active {
background-color: transparent;
}
button:before {
align-self: center;
border-color: transparent transparent #000000 transparent;
border-style: solid;
border-width: 0 4px 6px 4px;
content: '';
height: 0;
margin-right: 0px;
width: 0;
}
.downvote {
transform: rotate(180deg);
}
.upvote {
transform: rotate(0deg);
}
`}</style>
</button>
)
export default ({votes}) => (
<span>
{votes}
<style jsx>{`
span {
padding: 0.5em 0.5em;
font-size: 14px;
color: inherit;
}
`}</style>
</span>
)
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import PostVoteButton from './PostVoteButton'
function PostVoteDown ({ downvote, votes, id }) {
return (
<PostVoteButton
id={id}
votes={votes}
className='downvote'
onClickHandler={() => downvote(id, votes - 1)}
/>
)
}
const downvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
export default graphql(downvotePost, {
props: ({ ownProps, mutate }) => ({
downvote: (id, votes) =>
mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id: ownProps.id,
votes: ownProps.votes - 1
}
}
})
})
})(PostVoteDown)
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import PostVoteButton from './PostVoteButton'
function PostVoteUp ({ upvote, votes, id }) {
return (
<PostVoteButton
id={id}
votes={votes}
className='upvote'
onClickHandler={() => upvote(id, votes + 1)}
/>
)
}
const upvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
export default graphql(upvotePost, {
props: ({ ownProps, mutate }) => ({
upvote: (id, votes) =>
mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id: ownProps.id,
votes: ownProps.votes + 1
}
}
})
})
})(PostVoteUp)
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { allPosts, allPostsQueryVars } from './PostList'
function Submit ({ createPost }) {
function handleSubmit (event) {
event.preventDefault()
const form = event.target
const formData = new window.FormData(form)
createPost(formData.get('title'), formData.get('url'))
form.reset()
}
return (
<form onSubmit={handleSubmit}>
<h1>Submit</h1>
<input placeholder='title' name='title' type='text' required />
<input placeholder='url' name='url' type='url' required />
<button type='submit'>Submit</button>
<style jsx>{`
form {
border-bottom: 1px solid #ececec;
padding-bottom: 20px;
margin-bottom: 20px;
}
input {
display: block;
margin-bottom: 10px;
}
`}</style>
</form>
)
}
const createPost = gql`
mutation createPost($title: String!, $url: String!) {
createPost(title: $title, url: $url) {
id
title
votes
url
createdAt
}
}
`
export default graphql(createPost, {
props: ({ mutate }) => ({
createPost: (title, url) =>
mutate({
variables: { title, url },
update: (proxy, { data: { createPost } }) => {
const data = proxy.readQuery({
query: allPosts,
variables: allPostsQueryVars
})
proxy.writeQuery({
query: allPosts,
data: {
...data,
allPosts: [createPost, ...data.allPosts]
},
variables: allPostsQueryVars
})
}
})
})
})(Submit)
export const actionTypes = {
START_CLOCK: 'START_CLOCK',
TICK_CLOCK: 'TICK_CLOCK'
}
export function startClock(isServer=true) {
return {
type: actionTypes.START_CLOCK,
light: isServer,
lastUpdate: null
}
}
export function tickClock(isServer) {
return {
type: actionTypes.TICK_CLOCK,
light: !isServer,
lastUpdate: Date.now()
}
}
import { actionTypes } from './actions'
export const initialState = {
lastUpdate: 0,
light: false
}
function reducer(state = initialState, action) {
switch (action.type) {
case actionTypes.TICK_CLOCK:
return {
...state,
...{ lastUpdate: action.lastUpdate, light: !!action.light }
}
default:
return state
}
}
export default reducer
import { delay } from 'redux-saga'
import { call, put, take } from 'redux-saga/effects'
import es6promise from 'es6-promise'
import 'isomorphic-unfetch'
import { actionTypes, tickClock } from './actions'
es6promise.polyfill()
function* runClockSaga() {
yield take(actionTypes.START_CLOCK)
while (true) {
yield put(tickClock(false))
yield call(delay, 800)
}
}
export default call(runClockSaga)
export const actionTypes = {
COUNT_INCREASE: 'COUNT_INCREASE',
COUNT_DECREASE: 'COUNT_DECREASE'
}
export function countIncrease() {
return { type: actionTypes.COUNT_INCREASE }
}
export function countDecrease() {
return { type: actionTypes.COUNT_DECREASE }
}
import { actionTypes } from './actions'
const initialState = 0
function reducer(state = initialState, action) {
switch (action.type) {
case actionTypes.COUNT_INCREASE:
return state + 1
case actionTypes.COUNT_DECREASE:
return state - 1
default:
return state
}
}
export default reducer
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import fetch from 'isomorphic-unfetch'
let apolloClient = null
// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
global.fetch = fetch
}
function create(initialState) {
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'same-origin' // Additional fetch() options like `credentials` or `headers`
}),
cache: new InMemoryCache().restore(initialState || {})
})
}
export default function initApollo(initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!process.browser) {
return create(initialState)
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = create(initialState)
}
return apolloClient
}
export const actionTypes = {
LOAD_DATA: 'LOAD_DATA',
LOAD_DATA_SUCCESS: 'LOAD_DATA_SUCCESS',
LOAD_DATA_ERROR: 'LOAD_DATA_ERROR'
}
export function loadData() {
return { type: actionTypes.LOAD_DATA }
}
export function loadDataSuccess(data) {
return {
type: actionTypes.LOAD_DATA_SUCCESS,
data
}
}
export function loadDataError(error) {
return {
type: actionTypes.LOAD_DATA_ERROR,
error
}
}
import { actionTypes } from './actions'
export const initialState = {
data: null,
error: false
}
function reducer(state = initialState, action) {
switch (action.type) {
case actionTypes.LOAD_DATA_SUCCESS:
return {
...state,
...{ data: action.data }
}
case actionTypes.LOAD_DATA_ERROR:
return {
...state,
...{ error: action.error }
}
default:
return state
}
}
export default reducer
import { put, takeLatest } from 'redux-saga/effects'
import es6promise from 'es6-promise'
import 'isomorphic-unfetch'
import { actionTypes, loadDataSuccess, loadDataError } from './actions'
es6promise.polyfill()
function* loadDataSaga() {
try {
const res = yield fetch('https://jsonplaceholder.typicode.com/users')
const data = yield res.json()
yield put(loadDataSuccess(data))
} catch (err) {
yield put(loadDataError(err))
}
}
export default takeLatest(actionTypes.LOAD_DATA, loadDataSaga)
import { combineReducers } from 'redux'
import clock from './clock/reducers'
import count from './count/reducers'
import placeholder from './placeholder/reducers'
export default combineReducers({
clock,
count,
placeholder
})
import { all } from 'redux-saga/effects'
import clock from './clock/sagas'
import placeholder from './placeholder/sagas'
function* rootSaga() {
yield all([clock, placeholder])
}
export default rootSaga
import React from 'react'
import PropTypes from 'prop-types'
import { ApolloProvider, getDataFromTree } from 'react-apollo'
import Head from 'next/head'
import initApollo from './initApollo'
// Gets the display name of a JSX component for dev tools
function getComponentDisplayName(Component) {
return Component.displayName || Component.name || 'Unknown'
}
export default ComposedComponent => {
return class WithApollo extends React.Component {
static displayName = `WithApollo(${getComponentDisplayName(
ComposedComponent
)})`
static propTypes = {
serverState: PropTypes.object.isRequired
}
static async getInitialProps(ctx) {
// Initial serverState with apollo (empty)
let serverState = {
apollo: {
data: {}
}
}
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
// Run all GraphQL queries in the component tree
// and extract the resulting data
if (!process.browser) {
const apollo = initApollo()
try {
// Run all GraphQL queries
await getDataFromTree(
<ApolloProvider client={apollo}>
<ComposedComponent {...composedInitialProps} />
</ApolloProvider>,
{
router: {
asPath: ctx.asPath,
pathname: ctx.pathname,
query: ctx.query
}
}
)
} 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 store
const state = {}
// Extract query data from the Apollo store
serverState = Object.assign(
state,
{ apollo: { data: apollo.cache.extract() } }
)
}
return {
serverState,
...composedInitialProps
}
}
constructor(props) {
super(props)
this.apollo = initApollo(props.serverState.apollo.data)
}
render() {
return (
<ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} />
</ApolloProvider>
)
}
}
}
import { composeWithDevTools } from 'redux-devtools-extension'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import nextReduxWrapper from 'next-redux-wrapper'
import nextReduxSaga from 'next-redux-saga'
import rootReducer from './rootReducer'
import rootSaga from './rootSaga'
const sagaMiddleware = createSagaMiddleware()
export function configureStore(initialState = {}) {
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(sagaMiddleware))
)
store.sagaTask = sagaMiddleware.run(rootSaga)
return store
}
export default function (BaseComponent) {
return nextReduxWrapper(configureStore)(nextReduxSaga(BaseComponent))
}
{
"name": "with-apollo-and-redux-saga",
"version": "1.0.0",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"apollo-client-preset": "^1.0.4",
"es6-promise": "^4.1.1",
"graphql": "^0.11.7",
"graphql-anywhere": "^4.0.2",
"graphql-tag": "^2.5.0",
"isomorphic-unfetch": "^2.0.0",
"next": "latest",
"next-redux-saga": "^1.0.0",
"next-redux-wrapper": "^1.3.5",
"next-routes": "^1.2.0",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-apollo": "^2.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.0",
"redux": "^3.7.0",
"redux-devtools-extension": "^2.13.2",
"redux-saga": "^0.16.0"
},
"author": "",
"license": "ISC"
}
import App from '../components/App'
import Header from '../components/Header'
export default () => (
<App>
<Header />
<article>
<h1>The Idea Behind This Example</h1>
<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.
</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.
</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.
</p>
<p>
This example relies on <a href='http://graph.cool'>graph.cool</a> for its GraphQL backend.
</p>
</article>
</App>
)
import withApollo from '../../lib/withApollo'
import App from '../../components/App'
import Header from '../../components/Header'
import Post from '../../components/Post'
export default withApollo(() => (
<App>
<Header />
<Post />
</App>
))
import React from 'react'
import withApollo from '../../lib/withApollo'
import withReduxSaga from '../../lib/withReduxSaga'
import { startClock } from '../../lib/clock/actions'
import App from '../../components/App'
import Header from '../../components/Header'
import Submit from '../../components/Submit'
import PostList from '../../components/PostList'
class BlogIndex extends React.Component {
componentDidMount () {
this.props.dispatch(startClock())
}
render () {
return (
<App>
<Header />
<Submit />
<PostList />
</App>
)
}
}
export default withReduxSaga(
withApollo(BlogIndex)
)
import React from 'react'
import withReduxSaga from '../lib/withReduxSaga'
import { startClock } from '../lib/clock/actions'
import { countIncrease } from '../lib/count/actions'
import { loadData } from '../lib/placeholder/actions'
import App from '../components/App'
import Header from '../components/Header'
import Page from '../components/Page'
class PageIndex extends React.Component {
static async getInitialProps ({ store }) {
store.dispatch(countIncrease())
if (!store.getState().placeholder.data) {
store.dispatch(loadData())
}
}
componentDidMount () {
this.props.dispatch(startClock())
}
render () {
return (
<App>
<Header />
<Page title='Home Page' />
</App>
)
}
}
export default withReduxSaga(PageIndex)
/**
* Parameterized Routing with next-route
*
* Benefits: Less code, and easily handles complex url structures
**/
const routes = (module.exports = require('next-routes')())
routes.add('blog/entry', '/blog/:id')
/**
* 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})
const routes = require('./routes')
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,9 +7,10 @@
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
```bash
npx create-next-app --example with-apollo-and-redux with-apollo-and-redux-app
# or
yarn create next-app --example with-apollo-and-redux with-apollo-and-redux-app
```
### Download manually
......
......@@ -50,6 +50,6 @@ const mapDispatchToProps = dispatch => {
}
}
export default withRedux(initStore, null, mapDispatchToProps)(
withApollo(Index)
export default withApollo(
withRedux(initStore, null, mapDispatchToProps)(Index)
)
......@@ -11,9 +11,10 @@ https://next-with-apollo-auth.now.sh
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
```bash
npx create-next-app --example with-apollo-auth with-apollo-auth-app
# or
yarn create next-app --example with-apollo-auth with-apollo-auth-app
```
### Download manually
......
......@@ -11,9 +11,10 @@ https://next-with-apollo.now.sh
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
```bash
npx create-next-app --example with-apollo with-apollo-app
# or
yarn create next-app --example with-apollo with-apollo-app
```
### Download manually
......
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { gql } from 'apollo-boost'
function PostUpvoter ({ upvote, votes, id }) {
return (
......
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloClient } from 'apollo-boost'
import { HttpLink } from 'apollo-boost'
import { InMemoryCache } from 'apollo-boost'
import fetch from 'isomorphic-unfetch'
let apolloClient = null
......
......@@ -20,11 +20,7 @@ export default ComposedComponent => {
static async getInitialProps(ctx) {
// Initial serverState with apollo (empty)
let serverState = {
apollo: {
data: {}
}
}
let serverState
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
......@@ -38,15 +34,14 @@ export default ComposedComponent => {
try {
// Run all GraphQL queries
await getDataFromTree(
<ApolloProvider client={apollo}>
<ComposedComponent {...composedInitialProps} />
</ApolloProvider>,
<ComposedComponent ctx={ctx} {...composedInitialProps} />,
{
router: {
asPath: ctx.asPath,
pathname: ctx.pathname,
query: ctx.query
}
},
client: apollo
}
)
} catch (error) {
......
......@@ -7,15 +7,13 @@
"start": "next start"
},
"dependencies": {
"apollo-client-preset": "1.0.4",
"graphql": "0.11.7",
"graphql-anywhere": "4.0.2",
"graphql-tag": "2.5.0",
"apollo-boost": "^0.1.3",
"graphql": "0.13.2",
"isomorphic-unfetch": "2.0.0",
"next": "latest",
"prop-types": "15.6.0",
"prop-types": "15.6.1",
"react": "16.2.0",
"react-apollo": "2.0.1",
"react-apollo": "2.1.0",
"react-dom": "16.2.0"
},
"author": "",
......
......@@ -6,9 +6,10 @@
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
```bash
npx create-next-app --example with-asset-imports with-asset-imports-app
# or
yarn create next-app --example with-asset-imports with-asset-imports-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-babel-macros with-babel-macros-app
# or
yarn create next-app --example with-babel-macros with-babel-macros-app
```
### Download manually
......
......@@ -9,7 +9,7 @@ Sorry for the extra packages. I belong to the minority camp of writing ES6 code
## How to run it
```
```bash
npm i; npm run build; npm run dev;
```
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-cxs with-cxs-app
# or
yarn create next-app --example with-cxs with-cxs-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-data-prefetch with-data-prefetch-app
```bash
npx create-next-app --example with-data-prefetch with-data-prefetch-app
# or
yarn create next-app --example with-data-prefetch with-data-prefetch-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-dotenv with-dotenv-app
# or
yarn create next-app --example with-dotenv with-dotenv-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-draft-js
```bash
npx create-next-app --example with-draft-js
# or
yarn create next-app --example with-draft-js with-draft-js-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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
```bash
npx create-next-app --example with-dynamic-import with-dynamic-import-app
# or
yarn create next-app --example with-dynamic-import with-dynamic-import-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-electron with-electron-app
# or
yarn create next-app --example with-electron with-electron-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-emotion with-emotion-app
# or
yarn create next-app --example with-emotion with-emotion-app
```
### Download manually
......
import { Component } from 'react'
import PropTypes from 'prop-types'
import { Provider } from 'react-fela'
import getFelaRenderer from './getFelaRenderer'
const clientRenderer = getFelaRenderer()
export default class FelaProvider extends Component {
static contextTypes = {
renderer: PropTypes.object
};
render () {
if (this.context.renderer) {
return this.props.children
}
const renderer = this.props.renderer || clientRenderer
return (
<Provider renderer={renderer}>
{this.props.children}
</Provider>
)
}
}
......@@ -8,9 +8,10 @@
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
```bash
npx create-next-app --example with-fela with-fela-app
# or
yarn create next-app --example with-fela with-fela-app
```
### Download manually
......
import { createRenderer } from 'fela'
import webPreset from 'fela-preset-web'
const felaRenderer = createRenderer({
plugins: [...webPreset]
})
export default felaRenderer
export default function getRenderer () {
return createRenderer({
plugins: [
...webPreset
]
})
}
import { Provider } from 'react-fela'
import felaRenderer from './fela-renderer'
export default ({ children }) =>
<Provider renderer={felaRenderer}>
{children}
</Provider>
......@@ -7,12 +7,12 @@
"start": "next start"
},
"dependencies": {
"fela": "^5.0.1",
"fela-dom": "5.0.2",
"fela-preset-web": "^5.0.2",
"fela": "^6.1.4",
"fela-dom": "^7.0.5",
"fela-preset-web": "^8.0.4",
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-fela": "^5.0.2"
"react-fela": "^7.0.1"
}
}
import Document, { Head, Main, NextScript } from 'next/document'
import { renderToSheetList } from 'fela-dom'
import felaRenderer from '../fela-renderer'
import FelaProvider from '../FelaProvider'
import getFelaRenderer from '../getFelaRenderer'
export default class MyDocument extends Document {
static getInitialProps ({ renderPage }) {
const page = renderPage()
const sheetList = renderToSheetList(felaRenderer)
felaRenderer.clear()
const serverRenderer = getFelaRenderer()
const page = renderPage(App => props => (
<FelaProvider renderer={serverRenderer}>
<App {...props} />
</FelaProvider>
))
const sheetList = renderToSheetList(serverRenderer)
return {
...page,
......@@ -15,13 +23,17 @@ export default class MyDocument extends Document {
}
render () {
const styleNodes = this.props.sheetList.map(({ type, media, css }) =>
const styleNodes = this.props.sheetList.map(
({ type, rehydration, support, media, css }) => (
<style
dangerouslySetInnerHTML={{ __html: css }}
data-fela-rehydration={rehydration}
data-fela-support={support}
data-fela-type={type}
key={`${type}-${media}`}
media={media}
/>,
/>
)
)
return (
......
import { createComponent } from 'react-fela'
import Page from '../layout'
import FelaProvider from '../FelaProvider'
const Container = createComponent(() => ({
maxWidth: 700,
......@@ -20,13 +21,14 @@ const Title = createComponent(
fontSize: size,
color: '#555'
}),
Text,
Text
)
export default () =>
<Page>
export default () => (
<FelaProvider>
<Container>
<Title size={50}>My Title</Title>
<Text>Hi, I am Fela.</Text>
</Container>
</Page>
</FelaProvider>
)
......@@ -8,9 +8,10 @@
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-firebase-authentication with-firebase-authentication-app
```bash
npx create-next-app --example with-firebase-authentication with-firebase-authentication-app
# or
yarn create next-app --example with-firebase-authentication with-firebase-authentication-app
```
### Download manually
......
dist/
\ No newline at end of file
......@@ -6,9 +6,10 @@
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-firebase-hosting with-firebase-hosting-app
```bash
npx create-next-app --example with-firebase-hosting with-firebase-hosting-app
# or
yarn create next-app --example with-firebase-hosting with-firebase-hosting-app
```
### Download manually
......@@ -20,48 +21,56 @@ curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2
cd with-firebase-hosting
```
It is recommended to use a package manager that uses a lockfile and caching for faster dev/test cycles:
- [Yarn](https://github.com/yarnpkg/yarn)
- [npm5.1.x](https://github.com/npm/npm)
- [pnpm](https://github.com/pnpm/pnpm)
Set up firebase:
- install Firebase Tools: `npm i -g firebase-tools`
- create a project through the [firebase web console](https://console.firebase.google.com/)
- grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/<projectId>
- update the `.firebaserc` default project ID to the newly created project
Install project:
* install Firebase Tools: `npm i -g firebase-tools`
* create a project through the [firebase web console](https://console.firebase.google.com/)
* grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/<projectId>
* update the `.firebaserc` default project ID to the newly created project
* login to the Firebase CLI tool with `firebase login`
#### Install project:
```bash
npm install
```
Run Next.js development:
#### Run Next.js development:
```bash
npm run next
npm run dev
```
Run Firebase locally for testing:
#### Run Firebase locally for testing:
Unfortunately I have been unable to get any combination of
```bash
npm run serve
firebase serve --only functions,hosting
```
Deploy it to the cloud with Firebase:
to locally host the built Next.js app as expected. [This issue is where solutions are being explored](https://github.com/firebase/firebase-tools/issues/535) and they will be shared here and on the [Next.js repo's similar issue](https://github.com/zeit/next.js/issues/3167) when discovered.
#### Deploy it to the cloud with Firebase:
```bash
npm run deploy
```
#### Clean dist folder
```bash
npm run clean
```
## The idea behind the example
The goal is to host the Next.js app on Firebase Cloud Functions with Firebase Hosting rewrite rules so our app is served from our Firebase Hosting URL. Each individual `page` bundle is served in a new call to the Cloud Function which performs the initial server render.
This is based off of the work at https://github.com/geovanisouza92/serverless-firebase & https://github.com/jthegedus/firebase-functions-next-example as described [here](https://medium.com/@jthegedus/next-js-on-cloud-functions-for-firebase-with-firebase-hosting-7911465298f2).
## Important / Caveats
## Important
* The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
* `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
* Testing on Firebase locally requires a complete build of the Next.js app. `npm run serve` handles everything required.
* **Any npm modules dependencies used in the Next.js app (`app/` folder) must also be installed as dependencies for the Cloud Functions project (`functions` folder).**
* The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks run most of the npm scripts when `npm run deploy` runs `firebase deploy`. The only scripts you should need are `dev`, `clean` and `deploy`.
{
"name": "app",
"description": "Next.js React SSR App",
"dependencies": {
"next": "latest",
"react": "16.0.0",
"react-dom": "16.0.0"
},
"scripts": {
"dev": "next",
"build": "next build"
}
}
{
"hosting": {
"public": "public",
"public": "dist/public",
"rewrites": [
{
"source": "**/**",
"function": "next"
}
]
],
"predeploy": "npm run build-public"
},
"functions": {
"source": "functions"
"source": "dist/functions",
"predeploy":
"npm run build-funcs && npm run build-app && npm run copy-deps && npm run install-deps"
}
}
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "5.3.0",
"firebase-functions": "0.6.3",
"next": "latest",
"react": "16.0.0",
"react-dom": "16.0.0"
}
}
{
"name": "with-firebase-hosting",
"version": "2.0.0",
"description":
"Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects.",
"version": "3.0.0",
"description": "Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects.",
"scripts": {
"install-app": "cd \"app/\" && npm i",
"install-functions": "cd \"functions/\" && npm i",
"postinstall": "npm run install-app && npm run install-functions",
"next": "cd \"app\" && npm run dev",
"preserve": "npm run build-all",
"serve": "firebase serve",
"predeploy": "npm run build-all",
"dev": "next src/app",
"serve": "echo \"for details see:\n\thttps://github.com/firebase/firebase-tools/issues/535 \n\thttps://github.com/zeit/next.js/issues/3167\";",
"deploy": "firebase deploy",
"build-all": "npm run build-next && npm run build-firebase",
"build-next": "cd \"app\" && npm i && npm run build",
"build-firebase": "cd \"functions\" && npm i"
"clean": "rimraf \"dist/functions\" && rimraf \"dist/public\"",
"build-public": "cpx \"src/public/**/*.*\" \"dist/public\" -C",
"build-funcs": "babel \"src/functions\" --out-dir \"dist/functions\"",
"build-app": "next build \"src/app\"",
"copy-deps": "cpx \"*{package.json,package-lock.json,yarn.lock}\" \"dist/functions\"",
"install-deps": "cd \"dist/functions\" && npm i"
},
"dependencies": {
"firebase-admin": "5.8.1",
"firebase-functions": "^0.8.1",
"next": "^5.0.1-canary.13",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"@babel/cli": "^7.0.0-beta.40",
"@babel/core": "^7.0.0-beta.40",
"@babel/preset-env": "^7.0.0-beta.40",
"@firebase/app-types": "^0.1.2",
"cpx": "^1.5.0",
"prettier": "^1.10.2",
"rimraf": "^2.6.2"
}
}
import React from 'react'
import Header from './Header'
const App = ({ children }) =>
const App = ({ children }) => (
<main>
<Header />
{children}
</main>
)
export default App
import React from 'react'
import Link from 'next/link'
export default ({ pathname }) =>
export default ({ pathname }) => (
<header>
<Link href='/'>
<a className={pathname === '/' && 'is-active'}>Home</a>
<a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link>{' '}
<Link href='/about'>
<a className={pathname === '/about' && 'is-active'}>About</a>
<a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link>
</header>
)
module.exports = {
distDir: '../../dist/functions/next'
}
import App from '../components/App'
export default () =>
export default () => (
<App>
<p>About Page</p>
</App>
)
import App from '../components/App'
export default () =>
export default () => (
<App>
<p>Index Page</p>
</App>
)
{
"presets": [
[
"env",
{
"targets": {
"node": "6.11.5"
}
}
]
]
}
......@@ -7,9 +7,10 @@
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-flow with-flow-app
```bash
npx create-next-app --example with-flow with-flow-app
# or
yarn create next-app --example with-flow with-flow-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-freactal with-freactal-app
```bash
npx create-next-app --example with-freactal with-freactal-app
# or
yarn create next-app --example with-freactal with-freactal-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-glamor with-glamor-app
```bash
npx create-next-app --example with-glamor with-glamor-app
# or
yarn create next-app --example with-glamor with-glamor-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-glamorous with-glamorous-app
```bash
npx create-next-app --example with-glamorous with-glamorous-app
# or
yarn create next-app --example with-glamorous with-glamorous-app
```
### Download manually
......
......@@ -10,9 +10,10 @@ This is an example of how you can include a global stylesheet in a next.js webap
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-global-stylesheet with-global-stylesheet-app
```bash
npx create-next-app --example with-global-stylesheet with-global-stylesheet-app
# or
yarn create next-app --example with-global-stylesheet with-global-stylesheet-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-hashed-statics with-hashed-statics-app
```bash
npx create-next-app --example with-hashed-statics with-hashed-statics-app
# or
yarn create next-app --example with-hashed-statics with-hashed-statics-app
```
### Download manually
......
......@@ -6,11 +6,13 @@
### Using `create-next-app`
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:
```
npm i -g create-next-app
create-next-app --example with-higher-order-component with-higher-order-component-app
```bash
npx create-next-app --example with-higher-order-component with-higher-order-component-app
# or
yarn create next-app --example with-higher-order-component with-higher-order-component-app
```
### Download manually
......@@ -20,18 +22,21 @@ Download the example [or clone the repo](https://github.com/zeit/next.js):
Install it and run:
**npm**
```bash
npm install
npm run dev
```
**yarn**
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
Deploy it to the cloud with [now](https://zeit.co/now)
([download](https://zeit.co/download))
```bash
now
......
import Link from 'next/link'
export const Nav = () => (
<ul>
<li>
<Link href='/'>
<a>Index</a>
</Link>
</li>
<li>
<Link href='/about'>
<a>About</a>
</Link>
</li>
</ul>
)
import React from 'react'
function withApp (Child) {
return class WrappedComponent extends React.Component {
static getInitialProps (context) {
return Child.getInitialProps(context)
}
render () {
return (
<div>
<header>
<h1>Header</h1>
</header>
<main>
<Child greeting='Hello From HOC' {...this.props} />
</main>
<footer>
<h1>Footer</h1>
</footer>
</div>
)
}
}
}
export default withApp
import accepts from 'accepts'
import { getDisplayName } from '../lib/getDisplayName'
export const withLanguages = Page => {
const WithLanguages = props => <Page {...props} />
WithLanguages.getInitialProps = async context => {
const languages = context.req
? accepts(context.req).languages()
: navigator.languages
return {
...(Page.getInitialProps ? await Page.getInitialProps(context) : {}),
languages
}
}
WithLanguages.displayName = `WithLanguages(${getDisplayName(Page)})`
return WithLanguages
}
import { getDisplayName } from '../lib/getDisplayName'
export const withUserAgent = Page => {
const WithUserAgent = props => <Page {...props} />
WithUserAgent.getInitialProps = async context => {
const userAgent = context.req
? context.req.headers['user-agent']
: navigator.userAgent
return {
...(Page.getInitialProps ? await Page.getInitialProps(context) : {}),
userAgent
}
}
WithUserAgent.displayName = `WithUserAgent(${getDisplayName(Page)})`
return WithUserAgent
}
export function getDisplayName(Component) {
return Component.displayName || Component.name || 'Unknown'
}
......@@ -7,9 +7,11 @@
"start": "next start"
},
"dependencies": {
"accepts": "1.3.4",
"lodash.flowright": "3.5.0",
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
"react": "16.2.0",
"react-dom": "16.2.0"
},
"license": "ISC"
}
import flowRight from 'lodash.flowright'
import { Nav } from '../components/Nav'
import { withLanguages } from '../hocs/withLanguages'
import { withUserAgent } from '../hocs/withUserAgent'
const AboutPage = props => (
<div>
<Nav />
<h1>About</h1>
<pre>{JSON.stringify(props, null, 2)}</pre>
</div>
)
export default flowRight([withLanguages, withUserAgent])(AboutPage)
import React from 'react'
import withApp from '../components/withApp'
import flowRight from 'lodash.flowright'
class Index extends React.Component {
static getInitialProps (context) {
const { isServer } = context
return { isServer }
}
render () {
const { greeting } = this.props
return (
import { Nav } from '../components/Nav'
import { withLanguages } from '../hocs/withLanguages'
import { withUserAgent } from '../hocs/withUserAgent'
const IndexPage = props => (
<div>
<h2>Index page</h2>
<h3 style={{ color: 'red' }}>{greeting}</h3>
<Nav />
<h1>Index</h1>
<pre>{JSON.stringify(props, null, 2)}</pre>
</div>
)
}
}
)
export default withApp(Index)
export default flowRight([withLanguages, withUserAgent])(IndexPage)
......@@ -7,9 +7,10 @@
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-i18next with-i18next-app
```bash
npx create-next-app --example with-i18next with-i18next-app
# or
yarn create next-app --example with-i18next with-i18next-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-ioc with-ioc-app
```bash
npx create-next-app --example with-ioc with-ioc-app
# or
yarn create next-app --example with-ioc with-ioc-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-jest with-jest-app
```bash
npx create-next-app --example with-jest with-jest-app
# or
yarn create next-app --example with-jest with-jest-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-kea with-kea-app
```bash
npx create-next-app --example with-kea with-kea-app
# or
yarn create next-app --example with-kea with-kea-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-loading with-loading-app
```bash
npx create-next-app --example with-loading with-loading-app
# or
yarn create next-app --example with-loading with-loading-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-markdown with-markdown
```bash
npx create-next-app --example with-markdown with-markdown
# or
yarn create next-app --example with-markdown with-markdown-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-material-ui-next with-material-ui-next-app
```bash
npx create-next-app --example with-material-ui-next with-material-ui-next-app
# or
yarn create next-app --example with-material-ui-next with-material-ui-next-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-material-ui with-material-ui-app
```bash
npx create-next-app --example with-material-ui with-material-ui-app
# or
yarn create next-app --example with-material-ui with-material-ui-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-mobx with-mobx-app
```bash
npx create-next-app --example with-mobx with-mobx-app
# or
yarn create next-app --example with-mobx with-mobx-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-next-css with-next-css-app
```bash
npx create-next-app --example with-next-css with-next-css-app
# or
yarn create next-app --example with-next-css with-next-css-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-next-routes with-next-routes-app
```bash
npx create-next-app --example with-next-routes with-next-routes-app
# or
yarn create next-app --example with-next-routes with-next-routes-app
```
### Download manually
......
......@@ -9,8 +9,9 @@
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
```bash
npm i -g create-next-app
create-next-app --example with-next-sass with-next-sass-app
npx create-next-app --example with-next-sass with-next-sass-app
# or
yarn create next-app --example with-next-sass with-next-sass-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-noscript with-noscript-app
```bash
npx create-next-app --example with-noscript with-noscript-app
# or
yarn create next-app --example with-noscript with-noscript-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-pkg with-pkg-app
```bash
npx create-next-app --example with-pkg with-pkg-app
# or
yarn create next-app --example with-pkg with-pkg-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-portals with-portals-app
```bash
npx create-next-app --example with-portals with-portals-app
# or
yarn create next-app --example with-portals with-portals-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-prefetching with-prefetching-app
```bash
npx create-next-app --example with-prefetching with-prefetching-app
# or
yarn create next-app --example with-prefetching with-prefetching-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-pretty-url-routing with-pretty-url-routing-app
```bash
npx create-next-app --example with-pretty-url-routing with-pretty-url-routing-app
# or
yarn create next-app --example with-pretty-url-routing with-pretty-url-routing-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-react-ga with-react-ga-app
```bash
npx create-next-app --example with-react-ga with-react-ga-app
# or
yarn create next-app --example with-react-ga with-react-ga-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-react-helmet with-react-helmet-app
```bash
npx create-next-app --example with-react-helmet with-react-helmet-app
# or
yarn create next-app --example with-react-helmet with-react-helmet-app
```
### Download manually
......
import React from 'react'
import { Trans } from 'react-i18next'
export default function ComponentWithTrans () {
return (
<p>
<Trans i18nKey='common:transComponent'>
Alternatively, you can use <code>Trans</code> component.
</Trans>
</p>
)
}
import React from 'react'
import { translate } from 'react-i18next'
function MyComponennt ({ t }) {
return (
<div>
{t('extendedComponent')}
</div>
)
function MyComponent ({ t }) {
return <p>{t('extendedComponent')}</p>
}
const Extended = translate('common')(MyComponennt)
const Extended = translate('common')(MyComponent)
export default Extended
import React from 'react'
// pure component just getting t function by props
export default function PureComponent ({ t }) {
return (
<div>
{t('common:pureComponent')}
</div>
)
return <p>{t('common:pureComponent')}</p>
}
const i18n = require('i18next')
const i18next = require('i18next')
const XHR = require('i18next-xhr-backend')
const LanguageDetector = require('i18next-browser-languagedetector')
......@@ -10,7 +10,7 @@ const options = {
ns: ['common'],
defaultNS: 'common',
debug: true,
debug: process.env.NODE_ENV !== 'production',
saveMissing: true,
interpolation: {
......@@ -23,20 +23,22 @@ const options = {
}
}
const i18nInstance = i18next
// for browser use xhr backend to load translations and browser lng detector
if (process.browser) {
i18n
i18nInstance
.use(XHR)
// .use(Cache)
.use(LanguageDetector)
}
// initialize if not already initialized
if (!i18n.isInitialized) i18n.init(options)
if (!i18nInstance.isInitialized) i18nInstance.init(options)
// a simple helper to getInitialProps passed on loaded i18n data
i18n.getInitialProps = (req, namespaces) => {
if (!namespaces) namespaces = i18n.options.defaultNS
const getInitialProps = (req, namespaces) => {
if (!namespaces) namespaces = i18nInstance.options.defaultNS
if (typeof namespaces === 'string') namespaces = [namespaces]
req.i18n.toJSON = () => null // do not serialize i18next instance and send to client
......@@ -45,7 +47,7 @@ i18n.getInitialProps = (req, namespaces) => {
req.i18n.languages.forEach((l) => {
initialI18nStore[l] = {}
namespaces.forEach((ns) => {
initialI18nStore[l][ns] = req.i18n.services.resourceStore.data[l][ns] || {}
initialI18nStore[l][ns] = (req.i18n.services.resourceStore.data[l] || {})[ns] || {}
})
})
......@@ -56,4 +58,8 @@ i18n.getInitialProps = (req, namespaces) => {
}
}
module.exports = i18n
module.exports = {
getInitialProps,
i18nInstance,
I18n: i18next.default
}
import { translate } from 'react-i18next'
import { getInitialProps, I18n } from '../i18n'
export const withI18next = (namespaces = ['common']) => ComposedComponent => {
const Extended = translate(namespaces, { i18n: I18n, wait: process.browser })(
ComposedComponent
)
Extended.getInitialProps = async (ctx) => {
const composedInitialProps = ComposedComponent.getInitialProps
? await ComposedComponent.getInitialProps(ctx)
: {}
const i18nInitialProps =
ctx.req && !process.browser ? getInitialProps(ctx.req, namespaces) : {}
return {
...composedInitialProps,
...i18nInitialProps
}
}
return Extended
}
{
"integrates_react-i18next": "Dieses Beispiel integriert react-i18next für einfache Übersetzung.",
"pureComponent": "Entweder t Funktion an Komponente via props weiterreichen.",
"extendedComponent": "Oder die Komponente erneut mit dem translate hoc erweiteren."
"extendedComponent": "Oder die Komponente erneut mit dem translate hoc erweiteren.",
"transComponent": "Sonst können Sie auch die Komponente <1>Trans</1> verwenden."
}
{
"integrates_react-i18next": "this sample integrates react-i18next for simple internationalization.",
"integrates_react-i18next": "This example integrates react-i18next for simple internationalization.",
"pureComponent": "You can either pass t function to child components.",
"extendedComponent": "Or wrap your component using the translate hoc provided by react-i18next."
"extendedComponent": "Or wrap your component using the translate hoc provided by react-i18next.",
"transComponent": "Alternatively, you can use <1>Trans</1> component."
}
import React from 'react'
import Link from 'next/link'
import { translate } from 'react-i18next'
import i18n from '../i18n'
import PureComponent from '../components/PureComponent'
import ExtendedComponent from '../components/ExtendedComponent'
import ComponentWithTrans from '../components/ComponentWithTrans'
import { withI18next } from '../lib/withI18next'
function Home ({ t, initialI18nStore }) {
return (
export default withI18next(['home', 'common'])(({ t, initialI18nStore }) => (
<div>
{t('welcome')}
<h1>{t('welcome')}</h1>
<p>{t('common:integrates_react-i18next')}</p>
<PureComponent t={t} />
<ExtendedComponent />
<Link href='/page2'><a>{t('link.gotoPage2')}</a></Link>
<ComponentWithTrans />
<Link href='/page2'>
<a>{t('link.gotoPage2')}</a>
</Link>
</div>
)
}
const Extended = translate(['home', 'common'], { i18n, wait: process.browser })(Home)
// Passing down initial translations
// use req.i18n instance on serverside to avoid overlapping requests set the language wrong
Extended.getInitialProps = async ({ req }) => {
if (req && !process.browser) return i18n.getInitialProps(req, ['home', 'common'])
return {}
}
export default Extended
))
import React from 'react'
import Link from 'next/link'
import { translate } from 'react-i18next'
import i18n from '../i18n'
import PureComponent from '../components/PureComponent'
import ExtendedComponent from '../components/ExtendedComponent'
import ComponentWithTrans from '../components/ComponentWithTrans'
import { withI18next } from '../lib/withI18next'
function Page2 ({ t, initialI18nStore }) {
return (
export default withI18next(['page2', 'common'])(({ t, initialI18nStore }) => (
<div>
{t('welcomePage2')}
<h1>{t('welcomePage2')}</h1>
<p>{t('common:integrates_react-i18next')}</p>
<PureComponent t={t} />
<ExtendedComponent />
<Link href='/'><a>{t('link.gotoPage1')}</a></Link>
<ComponentWithTrans />
<Link href='/'>
<a>{t('link.gotoPage1')}</a>
</Link>
</div>
)
}
const Extended = translate(['page2', 'common'], { i18n, wait: process.browser })(Page2)
// Passing down initial translations
// use req.i18n instance on serverside to avoid overlapping requests set the language wrong
Extended.getInitialProps = async ({ req }) => {
if (req && !process.browser) return i18n.getInitialProps(req, ['page2', 'common'])
return {}
}
export default Extended
))
......@@ -8,11 +8,11 @@ const handle = app.getRequestHandler()
const i18nextMiddleware = require('i18next-express-middleware')
const Backend = require('i18next-node-fs-backend')
const i18n = require('./i18n')
const { i18nInstance } = require('./i18n')
// init i18next with serverside settings
// using i18next-express-middleware
i18n
i18nInstance
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
......@@ -30,13 +30,13 @@ i18n
const server = express()
// enable middleware for i18next
server.use(i18nextMiddleware.handle(i18n))
server.use(i18nextMiddleware.handle(i18nInstance))
// serve locales for client
server.use('/locales', express.static(path.join(__dirname, '/locales')))
// missing keys
server.post('/locales/add/:lng/:ns', i18nextMiddleware.missingKeyHandler(i18n))
server.post('/locales/add/:lng/:ns', i18nextMiddleware.missingKeyHandler(i18nInstance))
// use next.js
server.get('*', (req, res) => handle(req, res))
......
......@@ -7,9 +7,10 @@
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-react-intl with-react-intl-app
```bash
npx create-next-app --example with-react-intl with-react-intl-app
# or
yarn create next-app --example with-react-intl with-react-intl-app
```
### Download manually
......@@ -53,7 +54,7 @@ This app stores translations and default strings in the `lang/` dir. This dir ha
The translated messages files that exist at `lang/*.json` are only used during production, and are automatically provided to the `<IntlProvider>`. During development the `defaultMessage`s defined in the source code are used. To prepare the example app for localization and production run the build script and start the server in production mode:
```
```bash
$ npm run build
$ npm start
```
......
......@@ -10,9 +10,10 @@
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-react-md with-react-md-app
```bash
npx create-next-app --example with-react-md with-react-md-app
# or
yarn create next-app --example with-react-md with-react-md-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-react-native-web
```bash
npx create-next-app --example with-react-native-web
# or
yarn create next-app --example with-react-native-web with-react-native-web-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-react-toolbox with-react-toolbox-app
```bash
npx create-next-app --example with-react-toolbox with-react-toolbox-app
# or
yarn create next-app --example with-react-toolbox with-react-toolbox-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-react-uwp with-react-uwp-app
```bash
npx create-next-app --example with-react-uwp with-react-uwp-app
# or
yarn create next-app --example with-react-uwp with-react-uwp-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-react-with-styles with-react-with-styles-app
```bash
npx create-next-app --example with-react-with-styles with-react-with-styles-app
# or
yarn create next-app --example with-react-with-styles with-react-with-styles-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-reasonml with-reasonml-app
```bash
npx create-next-app --example with-reasonml with-reasonml-app
# or
yarn create next-app --example with-reasonml with-reasonml-app
```
### Download manually
......
......@@ -10,9 +10,10 @@
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-rebass with-rebass-app
```bash
npx create-next-app --example with-rebass with-rebass-app
# or
yarn create next-app --example with-rebass with-rebass-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-recompose with-recompose-app
```bash
npx create-next-app --example with-recompose with-recompose-app
# or
yarn create next-app --example with-recompose with-recompose-app
```
### Download manually
......
......@@ -9,9 +9,10 @@
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-redux-code-splitting with-redux-code-splitting-app
```bash
npx create-next-app --example with-redux-code-splitting with-redux-code-splitting-app
# or
yarn create next-app --example with-redux-code-splitting with-redux-code-splitting-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-redux-observable with-redux-observable-app
```bash
npx create-next-app --example with-redux-observable with-redux-observable-app
# or
yarn create next-app --example with-redux-observable with-redux-observable-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-redux-reselect-recompose with-redux-reselect-recompose-app
```bash
npx create-next-app --example with-redux-reselect-recompose with-redux-reselect-recompose-app
# or
yarn create next-app --example with-redux-reselect-recompose with-redux-reselect-recompose-app
```
### Download manually
......
......@@ -10,9 +10,10 @@
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-redux-saga with-redux-saga-app
```bash
npx create-next-app --example with-redux-saga with-redux-saga-app
# or
yarn create next-app --example with-redux-saga with-redux-saga-app
```
### Download manually
......
[![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-redux-wrapper)
# Redux 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-redux-wrapper with-redux-wrapper-app
# or
yarn create next-app --example with-redux-wrapper with-redux-wrapper-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-redux-wrapper
cd with-redux-wrapper
```
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
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.
![](http://i.imgur.com/JCxtWSj.gif)
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `next-redux-wrapper`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required.
For safety it is recommended to wrap all pages, no matter if they use Redux or not, so that you should not care about it anymore in all child components.
`withRedux` function accepts `makeStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `makeStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here. See the [full example](https://github.com/kirill-konshin/next-redux-wrapper#usage) in the Next Redux Wrapper repository. And there's another package [next-connect-redux](https://github.com/huzidaha/next-connect-redux) available with similar features.
To pass the initial state from the server to the client we pass it as a prop called `initialState` so then it's available when the client takes over.
The trick here for supporting universal redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`
The clock, under `components/Clock.js`, has access to the state using the `connect` function from `react-redux`. In this case Clock is a direct child from the page but it could be deep down the render tree.
The second example, under `components/AddCount.js`, shows a simple add counter function with a class component implementing a common redux pattern of mapping state and props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render second, when you navigate between pages.
For simplicity and readability, Reducers, Actions, and Store creators are all in the same file: `store.js`
import React, {Component} from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { addCount } from '../store'
class AddCount extends Component {
add = () => {
this.props.addCount()
}
render () {
const { count } = this.props
return (
<div>
<style jsx>{`
div {
padding: 0 0 20px 0;
}
`}</style>
<h1>AddCount: <span>{count}</span></h1>
<button onClick={this.add}>Add To Count</button>
</div>
)
}
}
const mapStateToProps = ({ count }) => ({ count })
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddCount)
export default ({ lastUpdate, light }) => {
return (
<div className={light ? 'light' : ''}>
{format(new Date(lastUpdate))}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82FA58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
}
const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = n => n < 10 ? `0${n}` : n
import Link from 'next/link'
import { connect } from 'react-redux'
import Clock from './Clock'
import AddCount from './AddCount'
export default connect(state => state)(({ title, linkTo, lastUpdate, light }) => {
return (
<div>
<h1>{title}</h1>
<Clock lastUpdate={lastUpdate} light={light} />
<AddCount />
<nav>
<Link href={linkTo}><a>Navigate</a></Link>
</nav>
</div>
)
})
{
"name": "with-redux-wrapper",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"next-redux-wrapper": "^1.0.0",
"react": "^16.0.0",
"redux-devtools-extension": "^2.13.2",
"react-dom": "^16.0.0",
"react-redux": "^5.0.1",
"redux": "^3.6.0",
"redux-thunk": "^2.1.0"
},
"license": "ISC"
}
import React from 'react'
import { bindActionCreators } from 'redux'
import { initStore, startClock, addCount, serverRenderClock } from '../store'
import withRedux from 'next-redux-wrapper'
import Page from '../components/Page'
class Counter extends React.Component {
static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}
componentDidMount () {
this.timer = this.props.startClock()
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return (
<Page title='Index Page' linkTo='/other' />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch),
startClock: bindActionCreators(startClock, dispatch)
}
}
export default withRedux(initStore, null, mapDispatchToProps)(Counter)
import React from 'react'
import { bindActionCreators } from 'redux'
import { initStore, startClock, addCount, serverRenderClock } from '../store'
import withRedux from 'next-redux-wrapper'
import Page from '../components/Page'
class Counter extends React.Component {
static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}
componentDidMount () {
this.timer = this.props.startClock()
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return (
<Page title='Other Page' linkTo='/' />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch),
startClock: bindActionCreators(startClock, dispatch)
}
}
export default withRedux(initStore, null, mapDispatchToProps)(Counter)
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
const exampleInitialState = {
lastUpdate: 0,
light: false,
count: 0
}
export const actionTypes = {
ADD: 'ADD',
TICK: 'TICK'
}
// REDUCERS
export const reducer = (state = exampleInitialState, action) => {
switch (action.type) {
case actionTypes.TICK:
return Object.assign({}, state, { lastUpdate: action.ts, light: !!action.light })
case actionTypes.ADD:
return Object.assign({}, state, {
count: state.count + 1
})
default: return state
}
}
// ACTIONS
export const serverRenderClock = (isServer) => dispatch => {
return dispatch({ type: actionTypes.TICK, light: !isServer, ts: Date.now() })
}
export const startClock = () => dispatch => {
return setInterval(() => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }), 1000)
}
export const addCount = () => dispatch => {
return dispatch({ type: actionTypes.ADD })
}
export const initStore = (initialState = exampleInitialState) => {
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
}
......@@ -8,9 +8,10 @@
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-redux with-redux-app
```bash
npx create-next-app --example with-redux with-redux-app
# or
yarn create next-app --example with-redux with-redux-app
```
### Download manually
......@@ -37,17 +38,21 @@ now
## The idea behind the example
This example is based on [full example](https://github.com/kirill-konshin/next-redux-wrapper) which should probably be used for production. The next.js example with this library can be found [here](https://github.com/zeit/next.js/tree/canary/examples/with-redux-wrapper)
The reason for this example is to show an easier to follow and extendable way to include Redux in a next.js app.
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.
![](http://i.imgur.com/JCxtWSj.gif)
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `next-redux-wrapper`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required.
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `withRedux.js`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required.
For safety it is recommended to wrap all pages, no matter if they use Redux or not, so that you should not care about it anymore in all child components.
`withRedux` function accepts `makeStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `makeStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here. See the [full example](https://github.com/kirill-konshin/next-redux-wrapper#usage) in the Next Redux Wrapper repository. And there's another package [next-connect-redux](https://github.com/huzidaha/next-connect-redux) available with similar features.
`withRedux` function accepts `initStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `initStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here.
To pass the initial state from the server to the client we pass it as a prop called `initialState` so then it's available when the client takes over.
......
......@@ -8,7 +8,6 @@
},
"dependencies": {
"next": "latest",
"next-redux-wrapper": "^1.0.0",
"react": "^16.0.0",
"redux-devtools-extension": "^2.13.2",
"react-dom": "^16.0.0",
......
import React from 'react'
import { bindActionCreators } from 'redux'
import { initStore, startClock, addCount, serverRenderClock } from '../store'
import withRedux from 'next-redux-wrapper'
import withRedux from '../utils/withRedux'
import Page from '../components/Page'
class Counter extends React.Component {
......
import React from 'react'
import { bindActionCreators } from 'redux'
import { initStore, startClock, addCount, serverRenderClock } from '../store'
import withRedux from 'next-redux-wrapper'
import withRedux from '../utils/withRedux'
import Page from '../components/Page'
class Counter extends React.Component {
......
import React from 'react'
import { connect, Provider } from 'react-redux'
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
// https://github.com/iliakan/detect-node
const checkServer = () => Object.prototype.toString.call(global.process) === '[object process]'
const getOrCreateStore = (initStore, initialState) => {
// Always make a new store if server
if (checkServer() || typeof window === 'undefined') {
return initStore(initialState)
}
// Store in global variable if client
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = initStore(initialState)
}
return window[__NEXT_REDUX_STORE__]
}
export default (...args) => (Component) => {
// First argument is initStore, the rest are redux connect arguments and get passed
const [initStore, ...connectArgs] = args
const ComponentWithRedux = (props = {}) => {
const { store, initialProps, initialState } = props
// Connect page to redux with connect arguments
const ConnectedComponent = connect.apply(null, connectArgs)(Component)
// Wrap with redux Provider with store
// Create connected page with initialProps
return React.createElement(
Provider,
{ store: store && store.dispatch ? store : getOrCreateStore(initStore, initialState) },
React.createElement(ConnectedComponent, initialProps)
)
}
ComponentWithRedux.getInitialProps = async (props = {}) => {
const isServer = checkServer()
const store = getOrCreateStore(initStore)
// Run page getInitialProps with store and isServer
const initialProps = Component.getInitialProps
? await Component.getInitialProps({ ...props, isServer, store })
: {}
return {
store,
initialState: store.getState(),
initialProps
}
}
return ComponentWithRedux
}
......@@ -8,9 +8,10 @@
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-refnux with-refnux-app
```bash
npx create-next-app --example with-refnux with-refnux-app
# or
yarn create next-app --example with-refnux with-refnux-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-relay-modern with-relay-modern-app
```bash
npx create-next-app --example with-relay-modern with-relay-modern-app
# or
yarn create next-app --example with-relay-modern with-relay-modern-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-semantic-ui with-semantic-ui-app
```bash
npx create-next-app --example with-semantic-ui with-semantic-ui-app
# or
yarn create next-app --example with-semantic-ui with-semantic-ui-app
```
### Download manually
......@@ -37,5 +38,4 @@ now
## The idea behind the example
This example shows how to use Next.js along with [Semantic UI React](http://react.semantic-ui.com). This is intended to show the integration of this
UI toolkit with the Framework,
\ No newline at end of file
This example shows how to use Next.js along with [Semantic UI React](http://react.semantic-ui.com) including handling of external styles and assets. This is intended to show the integration of this UI toolkit with the Framework.
const withCss = require('@zeit/next-css')
module.exports = withCss({
webpack (config) {
config.module.rules.push({
test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
publicPath: './',
outputPath: 'static/',
name: '[name].[ext]'
}
}
})
return config
}
})
......@@ -7,10 +7,14 @@
"start": "next start"
},
"dependencies": {
"@zeit/next-css": "^0.1.2",
"file-loader": "^1.1.9",
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"semantic-ui-react": "^0.68.0"
"semantic-ui-css": "^2.2.12",
"semantic-ui-react": "^0.78.2",
"url-loader": "^0.6.2"
},
"license": "ISC"
}
import 'semantic-ui-css/components/modal.css'
import 'semantic-ui-css/components/header.css'
import 'semantic-ui-css/components/button.css'
import 'semantic-ui-css/components/list.css'
import 'semantic-ui-css/components/icon.css'
import 'semantic-ui-css/themes/default/assets/fonts/icons.eot'
import 'semantic-ui-css/themes/default/assets/fonts/icons.woff'
import 'semantic-ui-css/themes/default/assets/fonts/icons.woff2'
import { Modal, Header, Button, List, Icon } from 'semantic-ui-react'
import Head from 'next/head'
import { Modal, Header, Button, List } from 'semantic-ui-react'
export default () => (
<div>
<Head>
<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
<Modal trigger={<Button>Show Modal</Button>}>
<Modal.Header>Select a Photo</Modal.Header>
......@@ -34,5 +42,7 @@ export default () => (
</List.Content>
</List.Item>
</List>
Hello <Icon name='world' />
</div>
)
......@@ -8,9 +8,10 @@
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-sentry with-sentry-app
```bash
npx create-next-app --example with-sentry with-sentry-app
# or
yarn create next-app --example with-sentry with-sentry-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-shallow-routing with-shallow-routing-app
```bash
npx create-next-app --example with-shallow-routing with-shallow-routing-app
# or
yarn create next-app --example with-shallow-routing with-shallow-routing-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-socket.io with-socket.io-app
```bash
npx create-next-app --example with-socket.io with-socket.io-app
# or
yarn create next-app --example with-socket.io with-socket.io-app
```
### Download manually
......
......@@ -6,9 +6,10 @@
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-static-export with-static-export-app
```bash
npx create-next-app --example with-static-export with-static-export-app
# or
yarn create next-app --example with-static-export with-static-export-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-styled-components with-styled-components-app
```bash
npx create-next-app --example with-styled-components with-styled-components-app
# or
yarn create next-app --example with-styled-components with-styled-components-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-styled-jsx-plugins with-styled-jsx-plugins-app
```bash
npx create-next-app --example with-styled-jsx-plugins with-styled-jsx-plugins-app
# or
yarn create next-app --example with-styled-jsx-plugins with-styled-jsx-plugins-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-styled-jsx-scss with-styled-jsx-scss-app
```bash
npx create-next-app --example with-styled-jsx-scss with-styled-jsx-scss-app
# or
yarn create next-app --example with-styled-jsx-scss with-styled-jsx-scss-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-styletron with-styletron-app
```bash
npx create-next-app --example with-styletron with-styletron-app
# or
yarn create next-app --example with-styletron with-styletron-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-sw-precache with-sw-precache-app
```bash
npx create-next-app --example with-sw-precache with-sw-precache-app
# or
yarn create next-app --example with-sw-precache with-sw-precache-app
```
### Download manually
......
......@@ -10,9 +10,10 @@ This is an example of how you can include a global stylesheet in a next.js webap
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-tailwindcss with-tailwindcss-app
```bash
npx create-next-app --example with-tailwindcss with-tailwindcss-app
# or
yarn create next-app --example with-tailwindcss with-tailwindcss-app
```
### Download manually
......
......@@ -10,9 +10,10 @@ This is a really simple project that show the usage of Next.js with TypeScript.
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-typescript with-typescript-app
```bash
npx create-next-app --example with-typescript with-typescript-app
# or
yarn create next-app --example with-typescript with-typescript-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-universal-configuration-runtime with-universal-configuration-runtime-app
```bash
npx create-next-app --example with-universal-configuration-runtime with-universal-configuration-runtime-app
# or
yarn create next-app --example with-universal-configuration-runtime with-universal-configuration-runtime-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-universal-configuration with-universal-configuration-app
```bash
npx create-next-app --example with-universal-configuration with-universal-configuration-app
# or
yarn create next-app --example with-universal-configuration with-universal-configuration-app
```
### Download manually
......
......@@ -7,9 +7,10 @@
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-url-object-routing with-url-object-routing-app
```bash
npx create-next-app --example with-url-object-routing with-url-object-routing-app
# or
yarn create next-app --example with-url-object-routing with-url-object-routing-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-webpack-bundle-analyzer with-webpack-bundle-analyzer-app
```bash
npx create-next-app --example with-webpack-bundle-analyzer with-webpack-bundle-analyzer-app
# or
yarn create next-app --example with-webpack-bundle-analyzer with-webpack-bundle-analyzer-app
```
### Download manually
......
......@@ -8,9 +8,10 @@
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-webpack-bundle-size-analyzer with-webpack-bundle-size-analyzer-app
```bash
npx create-next-app --example with-webpack-bundle-size-analyzer with-webpack-bundle-size-analyzer-app
# or
yarn create next-app --example with-webpack-bundle-size-analyzer with-webpack-bundle-size-analyzer-app
```
### Download manually
......
......@@ -10,14 +10,14 @@ We also have a set of rules defined in `rules.json` for the proxy.
Now let's start two of our app using:
```
```bash
npm run home
npm run blog
```
Then start the proxy:
```
```bash
npm run proxy
```
......
export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
......@@ -74,9 +74,9 @@ export default class PageLoader {
const script = document.createElement('script')
const url = `${this.assetPrefix}/_next/${encodeURIComponent(this.buildId)}/page${scriptRoute}`
script.src = url
script.type = 'text/javascript'
script.onerror = () => {
const error = new Error(`Error when loading route: ${route}`)
error.code = 'PAGE_LOAD_ERROR'
this.pageRegisterEvents.emit(route, { error })
}
......
/* global window */
import _Router from './router'
import { execOnce } from '../utils'
const SingletonRouter = {
router: null, // holds the actual router instance
......@@ -53,6 +54,18 @@ routerEvents.forEach((event) => {
})
})
const warnAboutRouterOnAppUpdated = execOnce(() => {
console.warn(`Router.onAppUpdated is removed - visit https://err.sh/next.js/no-on-app-updated-hook for more information.`)
})
Object.defineProperty(SingletonRouter, 'onAppUpdated', {
get () { return null },
set () {
warnAboutRouterOnAppUpdated()
return null
}
})
function throwIfNoRouter () {
if (!SingletonRouter.router) {
const message = 'No router instance found.\n' +
......@@ -85,15 +98,6 @@ export const createRouter = function (...args) {
// Export the actual Router class, which is usually used inside the server
export const Router = _Router
export function _notifyBuildIdMismatch (nextRoute) {
if (SingletonRouter.onAppUpdated) {
SingletonRouter.onAppUpdated(nextRoute)
} else {
console.warn(`An app update detected. Loading the SSR version of "${nextRoute}"`)
window.location.href = nextRoute
}
}
export function _rewriteUrlForNextExport (url) {
const [, hash] = url.split('#')
url = url.replace(/#.*/, '')
......
......@@ -5,7 +5,14 @@ import EventEmitter from '../EventEmitter'
import shallowEquals from '../shallow-equals'
import PQueue from '../p-queue'
import { loadGetInitialProps, getURL, warn, execOnce } from '../utils'
import { _notifyBuildIdMismatch, _rewriteUrlForNextExport } from './'
import { _rewriteUrlForNextExport } from './'
const historyUnavailableWarning = execOnce(() => {
warn(`Warning: window.history is not available.`)
})
const historyMethodWarning = execOnce((method) => {
warn(`Warning: window.history.${method} is not available`)
})
export default class Router {
constructor (pathname, query, as, { pageLoader, Component, ErrorComponent, err } = {}) {
......@@ -135,7 +142,7 @@ export default class Router {
if (this.onlyAHashChange(as)) {
this.changeState(method, url, as)
this.scrollToHash(as)
return
return true
}
const { pathname, query } = parse(url, true)
......@@ -185,9 +192,17 @@ export default class Router {
}
changeState (method, url, as, options = {}) {
if (window.frameElement) {
execOnce(warn)(`Warning: You're using Next.js inside an iFrame. Browser history is disabled.`)
} else if (method !== 'pushState' || getURL() !== as) {
if (typeof window.history === 'undefined') {
historyUnavailableWarning()
return
}
if (typeof window.history[method] === 'undefined') {
historyMethodWarning(method)
return
}
if (method !== 'pushState' || getURL() !== as) {
window.history[method]({ url, as, options }, null, as)
}
}
......@@ -212,20 +227,12 @@ export default class Router {
this.components[route] = routeInfo
} catch (err) {
if (err.buildIdMismatched) {
// Now we need to reload the page or do the action asked by the user
_notifyBuildIdMismatch(as)
// We also need to cancel this current route change.
// We do it like this.
err.cancelled = true
return { error: err }
}
if (err.code === 'PAGE_LOAD_ERROR') {
// If we can't load the page it could be one of following reasons
// 1. Page doesn't exists
// 2. Page does exist in a different zone
// 3. Internal error while loading the page
if (err.statusCode === 404) {
// If there's 404 error for the page, it could be due to two reasons.
// 1. Page is not exists
// 2. Page is exists in a different zone
// We are not sure whether this is actual 404 or exists in a different zone.
// So, doing a hard reload is the proper way to deal with this.
window.location.href = as
......
let runtimeConfig
export default () => {
return runtimeConfig
}
export function setConfig (configValue) {
runtimeConfig = configValue
}
{
"name": "next",
"version": "5.0.1-canary.6",
"version": "5.0.1-canary.17",
"description": "Minimalistic framework for server-rendered React applications",
"main": "./dist/server/next.js",
"license": "MIT",
......@@ -19,7 +19,9 @@
"prefetch.js",
"router.js",
"asset.js",
"error.js"
"error.js",
"constants.js",
"config.js"
],
"bin": {
"next": "./dist/bin/next"
......@@ -50,7 +52,7 @@
"bin/*": "standard"
},
"dependencies": {
"@zeit/check-updates": "1.1.0",
"@zeit/check-updates": "1.1.1",
"@zeit/source-map-support": "0.6.2",
"ansi-html": "0.0.7",
"babel-core": "6.26.0",
......@@ -70,6 +72,7 @@
"cross-spawn": "5.1.0",
"del": "3.0.0",
"etag": "1.8.1",
"event-source-polyfill": "0.0.12",
"find-up": "2.1.0",
"fresh": "0.5.2",
"friendly-errors-webpack-plugin": "1.6.1",
......@@ -79,23 +82,19 @@
"htmlescape": "1.1.1",
"http-errors": "1.6.2",
"http-status": "1.0.1",
"json-loader": "0.5.7",
"loader-utils": "1.1.0",
"md5-file": "3.2.3",
"minimist": "1.2.0",
"mkdirp-then": "1.2.0",
"mv": "2.1.1",
"mz": "2.7.0",
"path-to-regexp": "2.1.0",
"pkg-up": "2.0.0",
"prop-types": "15.6.0",
"prop-types-exact": "1.1.1",
"react-hot-loader": "4.0.0-beta.23",
"react-hot-loader": "4.0.0",
"recursive-copy": "2.0.6",
"resolve": "1.5.0",
"send": "0.16.1",
"strip-ansi": "3.0.1",
"styled-jsx": "2.2.5",
"styled-jsx": "2.2.6",
"touch": "3.1.0",
"uglifyjs-webpack-plugin": "1.1.6",
"unfetch": "3.0.0",
......@@ -104,10 +103,9 @@
"walk": "2.3.9",
"webpack": "3.10.0",
"webpack-dev-middleware": "1.12.0",
"webpack-hot-middleware": "2.21.0",
"webpack-hot-middleware": "2.19.1",
"webpack-sources": "1.1.0",
"write-file-webpack-plugin": "4.2.0",
"xss-filters": "1.2.7"
"write-file-webpack-plugin": "4.2.0"
},
"devDependencies": {
"@taskr/babel": "1.1.0",
......
......@@ -4,7 +4,7 @@
[![Build Status](https://travis-ci.org/zeit/next.js.svg?branch=master)](https://travis-ci.org/zeit/next.js)
[![Build status](https://ci.appveyor.com/api/projects/status/gqp5hs71l3ebtx1r/branch/master?svg=true)](https://ci.appveyor.com/project/arunoda/next-js/branch/master)
[![Coverage Status](https://coveralls.io/repos/zeit/next.js/badge.svg?branch=master)](https://coveralls.io/r/zeit/next.js?branch=master)
[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat)
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/next-js)
Next.js is a minimalistic framework for server-rendered React applications.
......@@ -62,7 +62,7 @@ Install it:
npm install --save next react react-dom
```
> Next.js 4 only supports [React 16](https://reactjs.org/blog/2017/09/26/react-v16.0.html).<br/>
> Next.js only supports [React 16](https://reactjs.org/blog/2017/09/26/react-v16.0.html).<br/>
> We had to drop React 15 support due to the way React 16 works and how we use it.
and add a script to your package.json like this:
......@@ -178,7 +178,7 @@ To support importing `.css` `.scss` or `.less` files you can use these modules,
Create a folder called `static` in your project root directory. From your code you can then reference those files with `/static/` URLs:
```jsx
export default () => <img src="/static/my-image.png" />
export default () => <img src="/static/my-image.png" alt="my image" />
```
### Populating `<head>`
......@@ -405,7 +405,7 @@ export default () =>
<div>
Click{' '}
<Link href="/about">
<img src="/static/image.png" />
<img src="/static/image.png" alt="image" />
</Link>
</div>
```
......@@ -428,6 +428,15 @@ export default ({ href, name }) =>
</Link>
```
##### Disabling the scroll changes to top on page
The default behaviour of `<Link>` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, just like a normal `<a>` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `<Link>`:
```jsx
<Link scroll={false} href="/?counter=10"><a>Disables scrolling</a></Link>
<Link href="/?counter=10"><a>Changes with scrolling to top</a></Link>
```
#### Imperatively
<p><details>
......@@ -491,7 +500,6 @@ Here's a list of supported events:
- `onRouteChangeComplete(url)` - Fires when a route changed completely
- `onRouteChangeError(err, url)` - Fires when there's an error when changing routes
- `onBeforeHistoryChange(url)` - Fires just before changing the browser's history
- `onAppUpdated(nextRoute)` - Fires when switching pages and there's a new version of the app
> Here `url` is the URL shown in the browser. If you call `Router.push(url, as)` (or similar), then the value of `url` will be `as`.
......@@ -519,17 +527,6 @@ Router.onRouteChangeError = (err, url) => {
}
```
If you change a route while in between a new deployment, we can't navigate the app via client side. We need to do a full browser navigation. We do it automatically for you.
But you can customize that via `Route.onAppUpdated` event like this:
```js
Router.onAppUpdated = nextUrl => {
// persist the local state
location.href = nextUrl
}
```
##### Shallow Routing
<p><details>
......@@ -563,9 +560,9 @@ componentWillReceiveProps(nextProps) {
> NOTES:
>
> Shallow routing works **only** for same page URL changes. For an example, let's assume we've another page called `about`, and you run this:
> Shallow routing works **only** for same page URL changes. For an example, let's assume we have another page called `about`, and you run this:
> ```js
> Router.push('/about?counter=10', '/about?counter=10', { shallow: true })
> Router.push('/?counter=10', '/about?counter=10', { shallow: true })
> ```
> Since that's a new page, it'll unload the current page, load the new one and call `getInitialProps` even though we asked to do shallow routing.
......@@ -608,7 +605,7 @@ The above `router` object comes with an API similar to [`next/router`](#imperati
### Prefetching Pages
(This is a production only feature)
⚠️ This is a production only feature ⚠️
<p><details>
<summary><b>Examples</b></summary>
......@@ -903,6 +900,9 @@ export default () => <HelloBundle title="Dynamic Bundle" />
Pages in `Next.js` skip the definition of the surrounding document's markup. For example, you never include `<html>`, `<body>`, etc. To override that default behavior, you must create a file at `./pages/_document.js`, where you can extend the `Document` class:
```jsx
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file
// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
......@@ -1009,6 +1009,36 @@ module.exports = {
}
```
Or use a function:
```js
module.exports = (phase, {defaultConfig}){
//
// https://github.com/zeit/
return {
/* config options here */
}
}
```
`phase` is the current context in which the configuration is loaded. You can see all phases here: [constants](./lib/constants.js)
Phases can be imported from `next/constants`:
```js
const {PHASE_DEVELOPMENT_SERVER} = require('next/constants')
module.exports = (phase, {defaultConfig}){
if(phase === PHASE_DEVELOPMENT_SERVER) {
return {
/* development only config options here */
}
}
return {
/* config options for all phases except development here */
}
}
```
#### Setting a custom build directory
You can specify a name to use for a custom build directory. For example, the following config will create a `build` folder instead of a `.next` folder. If no configuration is specified then next will create a `.next` folder.
......@@ -1020,6 +1050,17 @@ module.exports = {
}
```
#### Disabling etag generation
You can disable etag generation for HTML pages depending on your cache strategy. If no configuration is specified then Next will generate etags for every page.
```js
// next.config.js
module.exports = {
generateEtags: false
}
```
#### Configuring the onDemandEntries
Next exposes some options that give you some control over how the server will dispose or keep in memories pages built:
......@@ -1125,6 +1166,35 @@ Here's an example `.babelrc` file:
}
```
#### Exposing configuration to the server / client side
The `config` key allows for exposing runtime configuration in your app. All keys are server only by default. To expose a configuration to both the server and client side you can use the `public` key.
```js
// next.config.js
module.exports = {
serverRuntimeConfig: { // Will only be available on the server side
mySecret: 'secret'
},
publicRuntimeConfig: { // Will be available on both server and client
staticFolder: '/static'
}
}
```
```js
// pages/index.js
import getConfig from 'next/config'
const {serverRuntimeConfig, publicRuntimeConfig} = getConfig()
console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side
console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client
export default () => <div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
```
### CDN support with Asset Prefix
To set up a CDN, you can set up the `assetPrefix` setting and configure your CDN's origin to resolve to the domain that Next.js is hosted on.
......
......@@ -3,11 +3,11 @@ import fs from 'mz/fs'
import uuid from 'uuid'
import webpack from 'webpack'
import getConfig from '../config'
import {PHASE_PRODUCTION_BUILD} from '../../lib/constants'
import getBaseWebpackConfig from './webpack'
import md5File from 'md5-file/promise'
export default async function build (dir, conf = null) {
const config = getConfig(dir, conf)
const config = getConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const buildId = uuid.v4()
try {
......@@ -25,7 +25,6 @@ export default async function build (dir, conf = null) {
await runCompiler(configs)
await writeBuildStats(dir, config)
await writeBuildId(dir, buildId, config)
} catch (err) {
console.error(`> Failed to build`)
......@@ -53,20 +52,6 @@ function runCompiler (compiler) {
})
}
async function writeBuildStats (dir, config) {
// Here we can't use hashes in webpack chunks.
// That's because the "app.js" is not tied to a chunk.
// It's created by merging a few assets. (commons.js and main.js)
// So, we need to generate the hash ourself.
const assetHashMap = {
'app.js': {
hash: await md5File(join(dir, config.distDir, 'app.js'))
}
}
const buildStatsPath = join(dir, config.distDir, 'build-stats.json')
await fs.writeFile(buildStatsPath, JSON.stringify(assetHashMap), 'utf8')
}
async function writeBuildId (dir, buildId, config) {
const buildIdPath = join(dir, config.distDir, 'BUILD_ID')
await fs.writeFile(buildIdPath, buildId, 'utf8')
......
import { ConcatSource } from 'webpack-sources'
// This plugin combines a set of assets into a single asset
// This should be only used with text assets,
// otherwise the result is unpredictable.
export default class CombineAssetsPlugin {
constructor ({ input, output }) {
this.input = input
this.output = output
}
apply (compiler) {
compiler.plugin('compilation', (compilation) => {
// This is triggered after uglify and other optimizers have ran.
compilation.plugin('after-optimize-chunk-assets', (chunks) => {
const concat = new ConcatSource()
this.input.forEach((name) => {
const asset = compilation.assets[name]
if (!asset) return
// We add each matched asset from this.input to a new bundle
concat.add(asset)
// The original assets are kept because they show up when analyzing the bundle using webpack-bundle-analyzer
// See https://github.com/zeit/next.js/tree/canary/examples/with-webpack-bundle-analyzer
})
// Creates a new asset holding the concatted source
compilation.assets[this.output] = concat
})
})
}
}
import { join } from 'path'
import { unlink } from 'mz/fs'
import { IS_BUNDLED_PAGE } from '../../utils'
export default class UnlinkFilePlugin {
constructor () {
......@@ -9,7 +10,7 @@ export default class UnlinkFilePlugin {
apply (compiler) {
compiler.plugin('after-emit', (compilation, callback) => {
const removed = Object.keys(this.prevAssets)
.filter((a) => !compilation.assets[a])
.filter((a) => IS_BUNDLED_PAGE.test(a) && !compilation.assets[a])
this.prevAssets = compilation.assets
......
......@@ -6,7 +6,6 @@ import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import {getPages} from './webpack/utils'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import PagesPlugin from './plugins/pages-plugin'
import NextJsSsrImportPlugin from './plugins/nextjs-ssr-import'
import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin'
......@@ -137,7 +136,13 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
// This saves chunks with the name given via require.ensure()
chunkFilename: '[name]-[chunkhash].js',
strictModuleExceptionHandling: true,
devtoolModuleFilenameTemplate: '[absolute-resource-path]'
devtoolModuleFilenameTemplate (info) {
if (dev) {
return '[absolute-resource-path]'
}
return `${info.absoluteResourcePath.replace(dir, '.').replace(nextDir, './node_modules/next')}`
}
},
performance: { hints: false },
resolve: {
......@@ -239,35 +244,31 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
toplevel: false,
typeofs: false,
unused: false,
conditionals: false,
conditionals: true,
dead_code: true,
evaluate: false
evaluate: true
}
}
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
}),
!isServer && new CombineAssetsPlugin({
input: ['manifest.js', 'react.js', 'commons.js', 'main.js'],
output: 'app.js'
}),
!dev && new webpack.optimize.ModuleConcatenationPlugin(),
!isServer && new PagesPlugin(),
!isServer && new DynamicChunksPlugin(),
isServer && new NextJsSsrImportPlugin(),
// In dev mode, we don't move anything to the commons bundle.
// In production we move common modules into the existing main.js bundle
!isServer && new webpack.optimize.CommonsChunkPlugin({
name: `commons`,
filename: `commons.js`,
name: 'main.js',
filename: 'main.js',
minChunks (module, count) {
// We need to move react-dom explicitly into common chunks.
// Otherwise, if some other page or module uses it, it might
// included in that bundle too.
if (module.context && module.context.indexOf(`${sep}react${sep}`) >= 0) {
// React and React DOM are used everywhere in Next.js. So they should always be common. Even in development mode, to speed up compilation.
if (module.resource && module.resource.includes(`${sep}react-dom${sep}`) && count >= 0) {
return true
}
if (module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
if (module.resource && module.resource.includes(`${sep}react${sep}`) && count >= 0) {
return true
}
......@@ -278,6 +279,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
return false
}
// commons
// If there are one or two pages, only move modules to common if they are
// used in all of the pages. Otherwise, move modules used in at-least
// 1/2 of the total pages into commons.
......@@ -285,28 +287,11 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
return count >= totalPages
}
return count >= totalPages * 0.5
// commons end
}
}),
!isServer && new webpack.optimize.CommonsChunkPlugin({
name: 'react',
filename: 'react.js',
minChunks (module, count) {
if (dev) {
return false
}
if (module.resource && module.resource.includes(`${sep}react-dom${sep}`) && count >= 0) {
return true
}
if (module.resource && module.resource.includes(`${sep}react${sep}`) && count >= 0) {
return true
}
return false
}
}),
!isServer && new webpack.optimize.CommonsChunkPlugin({
// We use a manifest file in development to speed up HMR
dev && !isServer && new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'manifest.js'
})
......
......@@ -10,17 +10,18 @@ const defaultConfig = {
assetPrefix: '',
configOrigin: 'default',
useFileSystemPublicRoutes: true,
generateEtags: true,
pageExtensions: ['jsx', 'js'] // jsx before js because otherwise regex matching will match js first
}
export default function getConfig (dir, customConfig) {
export default function getConfig (phase, dir, customConfig) {
if (!cache.has(dir)) {
cache.set(dir, loadConfig(dir, customConfig))
cache.set(dir, loadConfig(phase, dir, customConfig))
}
return cache.get(dir)
}
function loadConfig (dir, customConfig) {
export function loadConfig (phase, dir, customConfig) {
if (customConfig && typeof customConfig === 'object') {
customConfig.configOrigin = 'server'
return withDefaults(customConfig)
......@@ -34,6 +35,9 @@ function loadConfig (dir, customConfig) {
if (path && path.length) {
const userConfigModule = require(path)
userConfig = userConfigModule.default || userConfigModule
if (typeof userConfigModule === 'function') {
userConfig = userConfigModule(phase, {defaultConfig})
}
userConfig.configOrigin = 'next.config.js'
}
......
......@@ -40,8 +40,8 @@ export class Head extends Component {
getChunkPreloadLink (filename) {
const { __NEXT_DATA__ } = this.context._documentProps
let { buildStats, assetPrefix, buildId } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : buildId
let { assetPrefix, buildId } = __NEXT_DATA__
const hash = buildId
return (
<link
......@@ -58,14 +58,13 @@ export class Head extends Component {
if (dev) {
return [
this.getChunkPreloadLink('manifest.js'),
this.getChunkPreloadLink('commons.js'),
this.getChunkPreloadLink('main.js')
]
}
// In the production mode, we have a single asset with all the JS content.
return [
this.getChunkPreloadLink('app.js')
this.getChunkPreloadLink('main.js')
]
}
......@@ -126,13 +125,12 @@ export class NextScript extends Component {
getChunkScript (filename, additionalProps = {}) {
const { __NEXT_DATA__ } = this.context._documentProps
let { buildStats, assetPrefix, buildId } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : buildId
let { assetPrefix, buildId } = __NEXT_DATA__
const hash = buildId
return (
<script
key={filename}
type='text/javascript'
src={`${assetPrefix}/_next/${hash}/${filename}`}
{...additionalProps}
/>
......@@ -144,14 +142,13 @@ export class NextScript extends Component {
if (dev) {
return [
this.getChunkScript('manifest.js'),
this.getChunkScript('commons.js'),
this.getChunkScript('main.js')
]
}
// In the production mode, we have a single asset with all the JS content.
// So, we can load the script with async
return [this.getChunkScript('app.js', { async: true })]
return [this.getChunkScript('main.js', { async: true })]
}
getDynamicChunks () {
......@@ -163,7 +160,6 @@ export class NextScript extends Component {
<script
async
key={chunk}
type='text/javascript'
src={`${assetPrefix}/_next/webpack/chunks/${chunk}`}
/>
))}
......@@ -204,8 +200,8 @@ export class NextScript extends Component {
`}
`
}} />}
{page !== '/_error' && <script async id={`__NEXT_PAGE__${pathname}`} type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} />}
<script async id={`__NEXT_PAGE__/_error`} type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page/_error.js`} />
{page !== '/_error' && <script async id={`__NEXT_PAGE__${pathname}`} src={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} />}
<script async id={`__NEXT_PAGE__/_error`} src={`${assetPrefix}/_next/${buildId}/page/_error.js`} />
{staticMarkup ? null : this.getDynamicChunks()}
{staticMarkup ? null : this.getScripts()}
</Fragment>
......
......@@ -5,15 +5,17 @@ import walk from 'walk'
import { extname, resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config'
import {PHASE_EXPORT} from '../lib/constants'
import { renderToHTML } from './render'
import { getAvailableChunks } from './utils'
import { printAndExit } from '../lib/utils'
import { setAssetPrefix } from '../lib/asset'
import * as envConfig from '../lib/runtime-config'
export default async function (dir, options, configuration) {
dir = resolve(dir)
const config = configuration || getConfig(dir)
const nextDir = join(dir, config.distDir)
const nextConfig = configuration || getConfig(PHASE_EXPORT, dir)
const nextDir = join(dir, nextConfig.distDir)
log(` using build directory: ${nextDir}`)
......@@ -25,20 +27,12 @@ export default async function (dir, options, configuration) {
}
const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
const buildStats = require(join(nextDir, 'build-stats.json'))
// Initialize the output directory
const outDir = options.outdir
await del(join(outDir, '*'))
await mkdirp(join(outDir, '_next', buildStats['app.js'].hash))
await mkdirp(join(outDir, '_next', buildId))
// Copy files
await cp(
join(nextDir, 'app.js'),
join(outDir, '_next', buildStats['app.js'].hash, 'app.js')
)
// Copy static directory
if (existsSync(join(dir, 'static'))) {
log(' copying "static" directory')
......@@ -49,6 +43,12 @@ export default async function (dir, options, configuration) {
)
}
// Copy main.js
await cp(
join(nextDir, 'main.js'),
join(outDir, '_next', buildId, 'main.js')
)
// Copy .next/static directory
if (existsSync(join(nextDir, 'static'))) {
log(' copying "static build" directory')
......@@ -72,30 +72,40 @@ export default async function (dir, options, configuration) {
await copyPages(nextDir, outDir, buildId)
// Get the exportPathMap from the `next.config.js`
if (typeof config.exportPathMap !== 'function') {
if (typeof nextConfig.exportPathMap !== 'function') {
printAndExit(
'> Could not find "exportPathMap" function inside "next.config.js"\n' +
'> "next export" uses that function to build html pages.'
)
}
const exportPathMap = await config.exportPathMap()
const exportPathMap = await nextConfig.exportPathMap()
const exportPaths = Object.keys(exportPathMap)
// Start the rendering process
const renderOpts = {
dir,
dist: config.distDir,
buildStats,
dist: nextConfig.distDir,
buildId,
nextExport: true,
assetPrefix: config.assetPrefix.replace(/\/$/, ''),
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
dev: false,
staticMarkup: false,
hotReloader: null,
availableChunks: getAvailableChunks(dir, config.distDir)
availableChunks: getAvailableChunks(dir, nextConfig.distDir)
}
const {serverRuntimeConfig, publicRuntimeConfig} = nextConfig
if (publicRuntimeConfig) {
renderOpts.runtimeConfig = publicRuntimeConfig
}
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig
})
// set the assetPrefix to use for 'next/asset'
setAssetPrefix(renderOpts.assetPrefix)
......
......@@ -16,9 +16,11 @@ import {
import Router from './router'
import { getAvailableChunks, isInternalUrl } from './utils'
import getConfig from './config'
import {PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER} from '../lib/constants'
// We need to go up one more level since we are in the `dist` directory
import pkg from '../../package'
import * as asset from '../lib/asset'
import * as envConfig from '../lib/runtime-config'
import { isResSent } from '../lib/utils'
const blockedPages = {
......@@ -33,20 +35,24 @@ export default class Server {
this.quiet = quiet
this.router = new Router()
this.http = null
this.config = getConfig(this.dir, conf)
this.dist = this.config.distDir
const phase = dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER
this.nextConfig = getConfig(phase, this.dir, conf)
this.dist = this.nextConfig.distDir
this.hotReloader = dev ? this.getHotReloader(this.dir, { quiet, config: this.config }) : null
this.hotReloader = dev ? this.getHotReloader(this.dir, { quiet, config: this.nextConfig }) : null
if (dev) {
updateNotifier(pkg, 'next')
}
// Only serverRuntimeConfig needs the default
// publicRuntimeConfig gets it's default in client/index.js
const {serverRuntimeConfig = {}, publicRuntimeConfig, assetPrefix, generateEtags} = this.nextConfig
if (!dev && !fs.existsSync(resolve(dir, this.dist, 'BUILD_ID'))) {
console.error(`> Could not find a valid build in the '${this.dist}' directory! Try building your app with 'next build' before starting the server.`)
process.exit(1)
}
this.buildStats = !dev ? require(join(this.dir, this.dist, 'build-stats.json')) : null
this.buildId = !dev ? this.readBuildId() : '-'
this.renderOpts = {
dev,
......@@ -54,12 +60,24 @@ export default class Server {
dir: this.dir,
dist: this.dist,
hotReloader: this.hotReloader,
buildStats: this.buildStats,
buildId: this.buildId,
availableChunks: dev ? {} : getAvailableChunks(this.dir, this.dist)
availableChunks: dev ? {} : getAvailableChunks(this.dir, this.dist),
generateEtags
}
// Only the `publicRuntimeConfig` key is exposed to the client side
// It'll be rendered as part of __NEXT_DATA__ on the client side
if (publicRuntimeConfig) {
this.renderOpts.runtimeConfig = publicRuntimeConfig
}
this.setAssetPrefix(this.config.assetPrefix)
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig
})
this.setAssetPrefix(assetPrefix)
this.defineRoutes()
}
......@@ -141,36 +159,55 @@ export default class Server {
await this.serveStatic(req, res, p)
},
'/_next/:hash/manifest.js': async (req, res, params) => {
'/_next/:buildId/manifest.js': async (req, res, params) => {
if (!this.dev) return this.send404(res)
this.handleBuildHash('manifest.js', params.hash, res)
this.handleBuildId(params.buildId, res)
const p = join(this.dir, this.dist, 'manifest.js')
await this.serveStatic(req, res, p)
},
'/_next/:hash/main.js': async (req, res, params) => {
'/_next/:buildId/manifest.js.map': async (req, res, params) => {
if (!this.dev) return this.send404(res)
this.handleBuildHash('main.js', params.hash, res)
const p = join(this.dir, this.dist, 'main.js')
this.handleBuildId(params.buildId, res)
const p = join(this.dir, this.dist, 'manifest.js.map')
await this.serveStatic(req, res, p)
},
'/_next/:hash/commons.js': async (req, res, params) => {
if (!this.dev) return this.send404(res)
'/_next/:buildId/main.js': async (req, res, params) => {
if (this.dev) {
this.handleBuildId(params.buildId, res)
const p = join(this.dir, this.dist, 'main.js')
await this.serveStatic(req, res, p)
} else {
const buildId = params.buildId
if (!this.handleBuildId(buildId, res)) {
const error = new Error('INVALID_BUILD_ID')
const customFields = { buildIdMismatched: true }
return await renderScriptError(req, res, '/_error', error, customFields, this.renderOpts)
}
this.handleBuildHash('commons.js', params.hash, res)
const p = join(this.dir, this.dist, 'commons.js')
const p = join(this.dir, this.dist, 'main.js')
await this.serveStatic(req, res, p)
}
},
'/_next/:hash/app.js': async (req, res, params) => {
if (this.dev) return this.send404(res)
'/_next/:buildId/main.js.map': async (req, res, params) => {
if (this.dev) {
this.handleBuildId(params.buildId, res)
const p = join(this.dir, this.dist, 'main.js.map')
await this.serveStatic(req, res, p)
} else {
const buildId = params.buildId
if (!this.handleBuildId(buildId, res)) {
return await this.render404(req, res)
}
this.handleBuildHash('app.js', params.hash, res)
const p = join(this.dir, this.dist, 'app.js')
const p = join(this.dir, this.dist, 'main.js.map')
await this.serveStatic(req, res, p)
}
},
'/_next/:buildId/page/:path*.js.map': async (req, res, params) => {
......@@ -196,9 +233,7 @@ export default class Server {
'/_next/:buildId/page/_error.js': async (req, res, params) => {
if (!this.handleBuildId(params.buildId, res)) {
const error = new Error('INVALID_BUILD_ID')
const customFields = { buildIdMismatched: true }
return await renderScriptError(req, res, '/_error', error, customFields, this.renderOpts)
return await renderScriptError(req, res, '/_error', error)
}
const p = join(this.dir, `${this.dist}/bundles/pages/_error.js`)
......@@ -211,22 +246,19 @@ export default class Server {
if (!this.handleBuildId(params.buildId, res)) {
const error = new Error('INVALID_BUILD_ID')
const customFields = { buildIdMismatched: true }
return await renderScriptError(req, res, page, error, customFields, this.renderOpts)
return await renderScriptError(req, res, page, error)
}
if (this.dev) {
try {
await this.hotReloader.ensurePage(page)
} catch (error) {
return await renderScriptError(req, res, page, error, {}, this.renderOpts)
return await renderScriptError(req, res, page, error)
}
const compilationErr = await this.getCompilationError()
if (compilationErr) {
const customFields = { statusCode: 500 }
return await renderScriptError(req, res, page, compilationErr, customFields, this.renderOpts)
return await renderScriptError(req, res, page, compilationErr)
}
}
......@@ -235,7 +267,7 @@ export default class Server {
// [production] If the page is not exists, we need to send a proper Next.js style 404
// Otherwise, it'll affect the multi-zones feature.
if (!(await fsAsync.exists(p))) {
return await renderScriptError(req, res, page, { code: 'ENOENT' }, {}, this.renderOpts)
return await renderScriptError(req, res, page, { code: 'ENOENT' })
}
await this.serveStatic(req, res, p)
......@@ -265,7 +297,7 @@ export default class Server {
}
}
if (this.config.useFileSystemPublicRoutes) {
if (this.nextConfig.useFileSystemPublicRoutes) {
routes['/:path*'] = async (req, res, params, parsedUrl) => {
const { pathname, query } = parsedUrl
await this.render(req, res, pathname, query)
......@@ -323,7 +355,7 @@ export default class Server {
return
}
if (this.config.poweredByHeader) {
if (this.nextConfig.poweredByHeader) {
res.setHeader('X-Powered-By', `Next.js ${pkg.version}`)
}
return sendHTML(req, res, html, req.method, this.renderOpts)
......@@ -445,20 +477,6 @@ export default class Server {
return Array.from(errors.values())[0][0]
}
handleBuildHash (filename, hash, res) {
if (this.dev) {
res.setHeader('Cache-Control', 'no-store, must-revalidate')
return true
}
if (hash !== this.buildStats[filename].hash) {
throw new Error(`Invalid Build File Hash(${hash}) for chunk: ${filename}`)
}
res.setHeader('Cache-Control', 'max-age=31536000, immutable')
return true
}
send404 (res) {
res.statusCode = 404
res.end('404 - Not Found')
......
......@@ -12,7 +12,8 @@ import Head, { defaultHead } from '../lib/head'
import App from '../lib/app'
import ErrorDebug from '../lib/error-debug'
import { flushChunks } from '../lib/dynamic'
import xssFilters from 'xss-filters'
const logger = console
export async function render (req, res, pathname, query, opts) {
const html = await renderToHTML(req, res, pathname, query, opts)
......@@ -36,9 +37,9 @@ async function doRender (req, res, pathname, query, {
err,
page,
buildId,
buildStats,
hotReloader,
assetPrefix,
runtimeConfig,
availableChunks,
dist,
dir = process.cwd(),
......@@ -54,8 +55,10 @@ async function doRender (req, res, pathname, query, {
const documentPath = join(dir, dist, 'dist', 'bundles', 'pages', '_document')
let Component = requirePage(page, {dir, dist})
let Document = require(documentPath)
let [Component, Document] = await Promise.all([
requirePage(page, {dir, dist}),
require(documentPath)
])
Component = Component.default || Component
Document = Document.default || Document
const asPath = req.url
......@@ -106,8 +109,8 @@ async function doRender (req, res, pathname, query, {
pathname, // the requested path
query,
buildId,
buildStats,
assetPrefix,
runtimeConfig,
nextExport,
err: (err) ? serializeError(dev, err) : null
},
......@@ -120,41 +123,24 @@ async function doRender (req, res, pathname, query, {
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
export async function renderScriptError (req, res, page, error, customFields, { dev }) {
export async function renderScriptError (req, res, page, error) {
// Asks CDNs and others to not to cache the errored page
res.setHeader('Cache-Control', 'no-store, must-revalidate')
// prevent XSS attacks by filtering the page before printing it.
page = xssFilters.uriInSingleQuotedAttr(page)
res.setHeader('Content-Type', 'text/javascript')
if (error.code === 'ENOENT') {
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
var error = new Error('Page does not exist: ${page}')
error.statusCode = 404
return { error: error }
})
`)
res.statusCode = 404
res.end('404 - Not Found')
return
}
const errorJson = {
...serializeError(dev, error),
...customFields
}
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
var error = ${JSON.stringify(errorJson)}
return { error: error }
})
`)
logger.error(error.stack)
res.statusCode = 500
res.end('500 - Internal Error')
}
export function sendHTML (req, res, html, method, { dev }) {
export function sendHTML (req, res, html, method, { dev, generateEtags }) {
if (isResSent(res)) return
const etag = generateETag(html)
const etag = generateEtags && generateETag(html)
if (fresh(req.headers, { etag })) {
res.statusCode = 304
......@@ -168,7 +154,10 @@ export function sendHTML (req, res, html, method, { dev }) {
res.setHeader('Cache-Control', 'no-store, must-revalidate')
}
if (etag) {
res.setHeader('ETag', etag)
}
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
}
......
import {join, parse, normalize, sep} from 'path'
import fs from 'mz/fs'
export function pageNotFoundError (page) {
const err = new Error(`Cannot find module for page: ${page}`)
......@@ -53,11 +54,12 @@ export function getPagePath (page, {dir, dist}) {
return pagePath
}
export default function requirePage (page, {dir, dist}) {
const pagePath = getPagePath(page, {dir, dist})
try {
return require(pagePath)
} catch (err) {
export default async function requirePage (page, {dir, dist}) {
const pagePath = getPagePath(page, {dir, dist}) + '.js'
const fileExists = await fs.exists(pagePath)
if (!fileExists) {
throw pageNotFoundError(page)
}
return require(pagePath)
}
......@@ -2,5 +2,5 @@ import {World} from '../components/world'
import {Hello} from '../components/hello.jsx'
export default () => (
<div><Hello/> <World/></div>
<div><Hello /> <World /></div>
)
aa = 10 //eslint-disable-line
export default () => (
<div>Hello</div>
)
export default () => (
export default () => {
return (
<div className='hmr-about-page'>
<p>
This is the about page.
</p>
</div>
)
)
}
import React from 'react'
export default class extends React.Component {
static getInitialProps () {
const error = new Error('an-expected-error-in-gip')
throw error
}
render () {
return (<div>Hello</div>)
}
}
import Link from 'next/link'
export default () => (
<div>
<Link href='/hmr/error-in-gip'><a id='error-in-gip-link'>Bad Page</a></Link>
</div>
)
/* global describe, it, expect */
import webdriver from 'next-webdriver'
import { join } from 'path'
import { check, File, waitFor } from 'next-test-utils'
export default (context, render) => {
describe('Error Recovery', () => {
it('should detect syntax errors and recover', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('</div>', 'div')
await check(
() => browser.elementByCss('body').text(),
/Unterminated JSX contents/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should not show the default HMR error overlay', async() => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('</div>', 'div')
await check(
() => browser.elementByCss('body').text(),
/Unterminated JSX contents/
)
await waitFor(2000)
// Check for the error overlay
const bodyHtml = await browser.elementByCss('body').getAttribute('innerHTML')
expect(bodyHtml.includes('webpack-hot-middleware-clientOverlay')).toBeFalsy()
aboutPage.restore()
browser.close()
})
it('should show the error on all pages', async () => {
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('</div>', 'div')
const browser = await webdriver(context.appPort, '/hmr/contact')
await check(
() => browser.elementByCss('body').text(),
/Unterminated JSX contents/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the contact page/
)
browser.close()
})
it('should detect runtime errors on the module scope', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('export', 'aa=20;\nexport')
await check(
() => browser.elementByCss('body').text(),
/aa is not defined/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should recover from errors in the render function', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('return', 'throw new Error("an-expected-error");\nreturn')
await check(
() => browser.elementByCss('body').text(),
/an-expected-error/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should recover after exporting an invalid page', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('export default', 'export default "not-a-page"\nexport const fn = ')
await check(
() => browser.elementByCss('body').text(),
/The default export is not a React Component/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should recover after a bad return from the render function', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPage = new File(join(__dirname, '../', 'pages', 'hmr', 'about.js'))
aboutPage.replace('export default', 'export default () => /search/ \nexport const fn = ')
await check(
() => browser.elementByCss('body').text(),
/Objects are not valid as a React child/
)
aboutPage.restore()
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should recover from errors in getInitialProps in client', async () => {
const browser = await webdriver(context.appPort, '/hmr')
await browser.elementByCss('#error-in-gip-link').click()
await check(
() => browser.elementByCss('body').text(),
/an-expected-error-in-gip/
)
const erroredPage = new File(join(__dirname, '../', 'pages', 'hmr', 'error-in-gip.js'))
erroredPage.replace('throw error', 'return {}')
await check(
() => browser.elementByCss('body').text(),
/Hello/
)
erroredPage.restore()
browser.close()
})
it('should recover after an error reported via SSR', async () => {
const browser = await webdriver(context.appPort, '/hmr/error-in-gip')
await check(
() => browser.elementByCss('body').text(),
/an-expected-error-in-gip/
)
const erroredPage = new File(join(__dirname, '../', 'pages', 'hmr', 'error-in-gip.js'))
erroredPage.replace('throw error', 'return {}')
await check(
() => browser.elementByCss('body').text(),
/Hello/
)
erroredPage.restore()
browser.close()
})
it('should recover from 404 after a page has been added', async () => {
const browser = await webdriver(context.appPort, '/hmr/new-page')
await check(
() => browser.elementByCss('body').text(),
/This page could not be found/
)
// Add the page
const newPage = new File(join(__dirname, '../', 'pages', 'hmr', 'new-page.js'))
newPage.write('export default () => (<div>the-new-page</div>)')
await check(
() => browser.elementByCss('body').text(),
/the-new-page/
)
newPage.delete()
browser.close()
})
})
}
......@@ -2,79 +2,10 @@
import webdriver from 'next-webdriver'
import { readFileSync, writeFileSync, renameSync } from 'fs'
import { join } from 'path'
import { waitFor } from 'next-test-utils'
async function check (contentFn, regex) {
while (true) {
try {
const newContent = await contentFn()
if (regex.test(newContent)) break
await waitFor(1000)
} catch (ex) {}
}
}
import { waitFor, check } from 'next-test-utils'
export default (context, render) => {
describe('Hot Module Reloading', () => {
describe('syntax error', () => {
it('should detect the error and recover', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPagePath = join(__dirname, '../', 'pages', 'hmr', 'about.js')
const originalContent = readFileSync(aboutPagePath, 'utf8')
const erroredContent = originalContent.replace('</div>', 'div')
// change the content
writeFileSync(aboutPagePath, erroredContent, 'utf8')
await check(
() => browser.elementByCss('body').text(),
/Unterminated JSX contents/
)
// add the original content
writeFileSync(aboutPagePath, originalContent, 'utf8')
await check(
() => browser.elementByCss('body').text(),
/This is the about page/
)
browser.close()
})
it('should show the error on all pages', async () => {
const aboutPagePath = join(__dirname, '../', 'pages', 'hmr', 'about.js')
const originalContent = readFileSync(aboutPagePath, 'utf8')
const erroredContent = originalContent.replace('</div>', 'div')
// change the content
writeFileSync(aboutPagePath, erroredContent, 'utf8')
const browser = await webdriver(context.appPort, '/hmr/contact')
await check(
() => browser.elementByCss('body').text(),
/Unterminated JSX contents/
)
// add the original content
writeFileSync(aboutPagePath, originalContent, 'utf8')
await check(
() => browser.elementByCss('body').text(),
/This is the contact page/
)
browser.close()
})
})
describe('delete a page and add it back', () => {
it('should load the page properly', async () => {
const browser = await webdriver(context.appPort, '/hmr/contact')
......
......@@ -13,6 +13,7 @@ import {
import rendering from './rendering'
import clientNavigation from './client-navigation'
import hmr from './hmr'
import errorRecovery from './error-recovery'
import dynamic from './dynamic'
import asset from './asset'
......@@ -62,5 +63,6 @@ describe('Basic Features', () => {
clientNavigation(context, (p, q) => renderViaHTTP(context.appPort, p, q))
dynamic(context, (p, q) => renderViaHTTP(context.appPort, p, q))
hmr(context, (p, q) => renderViaHTTP(context.appPort, p, q))
errorRecovery(context, (p, q) => renderViaHTTP(context.appPort, p, q))
asset(context)
})
......@@ -96,11 +96,16 @@ export default function ({ app }, suiteName, render, fetch) {
expect(pre.text()).toMatch(/The default export is not a React Component/)
})
test('error', async () => {
const $ = await get$('/error')
test('error-inside-page', async () => {
const $ = await get$('/error-inside-page')
expect($('pre').text()).toMatch(/This is an expected error/)
})
test('error-in-the-global-scope', async () => {
const $ = await get$('/error-in-the-global-scope')
expect($('pre').text()).toMatch(/aa is not defined/)
})
test('asPath', async () => {
const $ = await get$('/nav/as-path', { aa: 10 })
expect($('.as-path-content').text()).toBe('/nav/as-path?aa=10')
......
......@@ -5,5 +5,11 @@ module.exports = withCSS({
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
cssModules: true
cssModules: true,
serverRuntimeConfig: {
mySecret: 'secret'
},
publicRuntimeConfig: {
staticFolder: '/static'
}
})
import getConfig from 'next/config'
const {serverRuntimeConfig, publicRuntimeConfig} = getConfig()
export default () => <div>
<p id='server-only'>{serverRuntimeConfig.mySecret}</p>
<p id='server-and-client'>{publicRuntimeConfig.staticFolder}</p>
</div>
/* global describe, it, expect */
import webdriver from 'next-webdriver'
import { waitFor } from 'next-test-utils'
export default (context, render) => {
describe('Configuration', () => {
it('should have config available on the client', async () => {
const browser = await webdriver(context.appPort, '/next-config')
// Wait for client side to load
await waitFor(5000)
const serverText = await browser.elementByCss('#server-only').text()
const serverClientText = await browser.elementByCss('#server-and-client').text()
expect(serverText).toBe('')
expect(serverClientText).toBe('/static')
browser.close()
})
})
}
......@@ -11,21 +11,24 @@ import {
// test suits
import rendering from './rendering'
import client from './client'
const context = {}
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
describe('Next Plugins', () => {
describe('Configuration', () => {
beforeAll(async () => {
context.appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort, true)
// pre-build all pages at the start
await Promise.all([
renderViaHTTP(context.appPort, '/next-config'),
renderViaHTTP(context.appPort, '/webpack-css')
])
})
afterAll(() => killApp(context.server))
rendering(context, 'Rendering via HTTP', (p, q) => renderViaHTTP(context.appPort, p, q), (p, q) => fetchViaHTTP(context.appPort, p, q))
client(context, (p, q) => renderViaHTTP(context.appPort, p, q))
})
......@@ -18,5 +18,15 @@ export default function ({ app }, suiteName, render, fetch) {
const $ = await get$('/webpack-css')
expect($('._2pRSkKTPDMGLMnmsEkP__J').text() === 'Hello World')
})
test('renders server config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-only').text() === 'mySecret')
})
test('renders public config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-and-client').text() === '/static')
})
})
}
......@@ -2,5 +2,6 @@ module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
}
},
generateEtags: process.env.GENERATE_ETAGS === 'true'
}
......@@ -7,7 +7,8 @@ import cheerio from 'cheerio'
import {
initNextServerScript,
killApp,
renderViaHTTP
renderViaHTTP,
fetchViaHTTP
} from 'next-test-utils'
import webdriver from 'next-webdriver'
......@@ -18,18 +19,24 @@ jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
const context = {}
describe('Custom Server', () => {
beforeAll(async () => {
const startServer = async (optEnv = {}) => {
const scriptPath = join(appDir, 'server.js')
context.appPort = appPort = await getPort()
const env = clone(process.env)
env.PORT = `${appPort}`
const env = Object.assign(
{},
clone(process.env),
{ PORT: `${appPort}` },
optEnv
)
server = await initNextServerScript(scriptPath, /Ready on/, env)
})
afterAll(() => killApp(server))
}
describe('Custom Server', () => {
describe('with dynamic assetPrefix', () => {
beforeAll(() => startServer())
afterAll(() => killApp(server))
it('should set the assetPrefix dynamically', async () => {
const normalUsage = await renderViaHTTP(appPort, '/asset')
expect(normalUsage).not.toMatch(/127\.0\.0\.1/)
......@@ -83,4 +90,24 @@ describe('Custom Server', () => {
browser2.close()
})
})
describe('with generateEtags enabled', () => {
beforeAll(() => startServer({ GENERATE_ETAGS: 'true' }))
afterAll(() => killApp(server))
it('response includes etag header', async () => {
const response = await fetchViaHTTP(appPort, '/')
expect(response.headers.get('etag')).toBeTruthy()
})
})
describe('with generateEtags disabled', () => {
beforeAll(() => startServer({ GENERATE_ETAGS: 'false' }))
afterAll(() => killApp(server))
it('response does not include etag header', async () => {
const response = await fetchViaHTTP(appPort, '/')
expect(response.headers.get('etag')).toBeNull()
})
})
})
......@@ -39,11 +39,11 @@ describe('Production Usage', () => {
describe('File locations', () => {
it('should build the app within the given `dist` directory', () => {
expect(existsSync(join(__dirname, '/../dist/app.js'))).toBeTruthy()
expect(existsSync(join(__dirname, '/../dist/main.js'))).toBeTruthy()
})
it('should not build the app within the default `.next` directory', () => {
expect(existsSync(join(__dirname, '/../.next/app.js'))).toBeFalsy()
expect(existsSync(join(__dirname, '/../.next/main.js'))).toBeFalsy()
})
})
})
......@@ -127,7 +127,7 @@ describe('Production Usage', () => {
// Let the browser to prefetch the page and error it on the console.
await waitFor(3000)
const browserLogs = await browser.log('browser')
expect(browserLogs[0].message).toMatch(/Page does not exist: \/no-such-page/)
expect(browserLogs[0].message).toMatch(/\/no-such-page.js - Failed to load resource/)
// When we go to the 404 page, it'll do a hard reload.
// So, it's possible for the front proxy to load a page from another zone.
......@@ -165,8 +165,8 @@ describe('Production Usage', () => {
it('should not set it when poweredByHeader==false', async () => {
const req = { url: '/stateless', headers: {} }
const originalConfigValue = app.config.poweredByHeader
app.config.poweredByHeader = false
const originalConfigValue = app.nextConfig.poweredByHeader
app.nextConfig.poweredByHeader = false
const res = {
getHeader () {
return false
......@@ -180,7 +180,7 @@ describe('Production Usage', () => {
}
await app.render(req, res, req.url)
app.config.poweredByHeader = originalConfigValue
app.nextConfig.poweredByHeader = originalConfigValue
})
})
......
const nonExistent = require('./non-existent-module')
module.exports = {
test: nonExistent
}
module.exports = (phase, {defaultConfig}) => {
return {
phase,
defaultConfig,
customConfig: true
}
}
/* global describe, it, expect */
import {join} from 'path'
import getConfig, {loadConfig} from '../../dist/server/config'
import {PHASE_DEVELOPMENT_SERVER} from '../../dist/lib/constants'
const pathToConfig = join(__dirname, '_resolvedata', 'without-function')
const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function')
describe('config', () => {
it('Should get the configuration', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)
expect(config.customConfig).toBe(true)
})
it('Should pass the phase correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
expect(config.phase).toBe(PHASE_DEVELOPMENT_SERVER)
})
it('Should pass the defaultConfig correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
expect(config.defaultConfig).toBeDefined()
})
it('Should pass the customConfig correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {customConfig: true})
expect(config.customConfig).toBe(true)
})
it('Should not pass the customConfig when it is null', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)
expect(config.webpack).toBe(null)
})
it('Should cache on getConfig', () => {
const config = getConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)
const config2 = getConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig, {extraConfig: true}) // won't add extraConfig because it's cached.
expect(config === config2).toBe(true)
})
})
......@@ -57,26 +57,42 @@ describe('getPagePath', () => {
})
describe('requirePage', () => {
it('Should require /index.js when using /', () => {
const page = requirePage('/', {dir: __dirname, dist: '_resolvedata'})
it('Should require /index.js when using /', async () => {
const page = await requirePage('/', {dir: __dirname, dist: '_resolvedata'})
expect(page.test).toBe('hello')
})
it('Should require /index.js when using /index', () => {
const page = requirePage('/index', {dir: __dirname, dist: '_resolvedata'})
it('Should require /index.js when using /index', async () => {
const page = await requirePage('/index', {dir: __dirname, dist: '_resolvedata'})
expect(page.test).toBe('hello')
})
it('Should require /world.js when using /world', () => {
const page = requirePage('/world', {dir: __dirname, dist: '_resolvedata'})
it('Should require /world.js when using /world', async () => {
const page = await requirePage('/world', {dir: __dirname, dist: '_resolvedata'})
expect(page.test).toBe('world')
})
it('Should throw when using /../../test.js', () => {
expect(() => requirePage('/../../test.js', {dir: __dirname, dist: '_resolvedata'})).toThrow()
it('Should throw when using /../../test.js', async () => {
try {
await requirePage('/../../test', {dir: __dirname, dist: '_resolvedata'})
} catch (err) {
expect(err.code).toBe('ENOENT')
}
})
it('Should throw when using non existent pages like /non-existent.js', () => {
expect(() => requirePage('/non-existent.js', {dir: __dirname, dist: '_resolvedata'})).toThrow()
it('Should throw when using non existent pages like /non-existent.js', async () => {
try {
await requirePage('/non-existent', {dir: __dirname, dist: '_resolvedata'})
} catch (err) {
expect(err.code).toBe('ENOENT')
}
})
it('Should bubble up errors in the child component', async () => {
try {
await requirePage('/non-existent-child', {dir: __dirname, dist: '_resolvedata'})
} catch (err) {
expect(err.code).toBe('MODULE_NOT_FOUND')
}
})
})
......@@ -5,6 +5,7 @@ import express from 'express'
import path from 'path'
import portfinder from 'portfinder'
import { spawn } from 'child_process'
import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs'
import fkill from 'fkill'
import server from '../../dist/server/next'
......@@ -146,3 +147,40 @@ export async function startStaticServer (dir) {
await promiseCall(server, 'listen')
return server
}
export async function check (contentFn, regex) {
while (true) {
try {
const newContent = await contentFn()
if (regex.test(newContent)) break
await waitFor(1000)
} catch (ex) {}
}
}
export class File {
constructor (path) {
this.path = path
this.originalContent = existsSync(this.path) ? readFileSync(this.path, 'utf8') : null
}
write (content) {
if (!this.originalContent) {
this.originalContent = content
}
writeFileSync(this.path, content, 'utf8')
}
replace (pattern, newValue) {
const newContent = this.originalContent.replace(pattern, newValue)
this.write(newContent)
}
delete () {
unlinkSync(this.path)
}
restore () {
this.write(this.originalContent)
}
}
......@@ -30,11 +30,11 @@
dependencies:
chokidar "^1.7.0"
"@zeit/check-updates@1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@zeit/check-updates/-/check-updates-1.1.0.tgz#d0f65026a36f27cd1fd54c647d8294447c1d2d8b"
"@zeit/check-updates@1.1.1":
version "1.1.1"
resolved "https://registry.yarnpkg.com/@zeit/check-updates/-/check-updates-1.1.1.tgz#1bee858fd3f9b8633b0fc23dff53cb17343331c0"
dependencies:
chalk "2.3.0"
chalk "2.3.2"
ms "2.1.1"
update-notifier "2.3.0"
......@@ -111,10 +111,14 @@ ajv-keywords@^1.0.0:
version "1.5.1"
resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-1.5.1.tgz#314dd0a4b3368fad3dfcdc54ede6171b886daf3c"
ajv-keywords@^2.0.0, ajv-keywords@^2.1.0:
ajv-keywords@^2.0.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-2.1.1.tgz#617997fc5f60576894c435f940d819e135b80762"
ajv-keywords@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.1.0.tgz#ac2b27939c543e95d2c06e7f7f5c27be4aa543be"
ajv@^4.7.0, ajv@^4.9.1:
version "4.11.8"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.11.8.tgz#82ffb02b29e662ae53bdc20af15947706739c536"
......@@ -131,6 +135,14 @@ ajv@^5.0.0, ajv@^5.1.0, ajv@^5.1.5:
fast-json-stable-stringify "^2.0.0"
json-schema-traverse "^0.3.0"
ajv@^6.1.0:
version "6.2.0"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.2.0.tgz#afac295bbaa0152449e522742e4547c1ae9328d2"
dependencies:
fast-deep-equal "^1.0.0"
fast-json-stable-stringify "^2.0.0"
json-schema-traverse "^0.3.0"
align-text@^0.1.1, align-text@^0.1.3:
version "0.1.4"
resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117"
......@@ -177,12 +189,18 @@ ansi-styles@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe"
ansi-styles@^3.1.0, ansi-styles@^3.2.0:
ansi-styles@^3.2.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.0.tgz#c159b8d5be0f9e5a6f346dab94f16ce022161b88"
dependencies:
color-convert "^1.9.0"
ansi-styles@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
dependencies:
color-convert "^1.9.0"
any-promise@^1.0.0, any-promise@^1.1.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/any-promise/-/any-promise-1.3.0.tgz#abc6afeedcea52e809cdc0376aed3ce39635d17f"
......@@ -245,8 +263,8 @@ are-we-there-yet@~1.1.2:
readable-stream "^2.0.6"
argparse@^1.0.7:
version "1.0.9"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86"
version "1.0.10"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
dependencies:
sprintf-js "~1.0.2"
......@@ -302,8 +320,8 @@ asap@~2.0.3:
resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46"
asn1.js@^4.0.0:
version "4.9.2"
resolved "https://registry.yarnpkg.com/asn1.js/-/asn1.js-4.9.2.tgz#8117ef4f7ed87cd8f89044b5bff97ac243a16c9a"
version "4.10.1"
resolved "https://registry.yarnpkg.com/asn1.js/-/asn1.js-4.10.1.tgz#b9c2bf5805f1e64aadeed6df3a2bfafb5a73f5a0"
dependencies:
bn.js "^4.0.0"
inherits "^2.0.1"
......@@ -1095,8 +1113,8 @@ balanced-match@^1.0.0:
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
base64-js@^1.0.2:
version "1.2.1"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.1.tgz#a91947da1f4a516ea38e5b4ec0ec3773675e0886"
version "1.2.3"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.3.tgz#fb13668233d9614cf5fb4bce95a9ba4096cdf801"
bcrypt-pbkdf@^1.0.0:
version "1.0.1"
......@@ -1131,7 +1149,7 @@ block-stream@*:
dependencies:
inherits "~2.0.0"
bluebird@^3.5.0:
bluebird@^3.5.0, bluebird@^3.5.1:
version "3.5.1"
resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.1.tgz#d9551f9de98f1fcda1e683d17ee91a0602ee2eb9"
......@@ -1174,8 +1192,8 @@ boxen@^1.2.1:
widest-line "^2.0.0"
brace-expansion@^1.1.7:
version "1.1.8"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292"
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
dependencies:
balanced-match "^1.0.0"
concat-map "0.0.1"
......@@ -1270,25 +1288,10 @@ bser@^2.0.0:
dependencies:
node-int64 "^0.4.0"
buffer-alloc-unsafe@^0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/buffer-alloc-unsafe/-/buffer-alloc-unsafe-0.1.1.tgz#ffe1f67551dd055737de253337bfe853dfab1a6a"
buffer-alloc@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/buffer-alloc/-/buffer-alloc-1.1.0.tgz#05514d33bf1656d3540c684f65b1202e90eca303"
dependencies:
buffer-alloc-unsafe "^0.1.0"
buffer-fill "^0.1.0"
buffer-crc32@^0.2.1:
version "0.2.13"
resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
buffer-fill@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/buffer-fill/-/buffer-fill-0.1.0.tgz#ca9470e8d4d1b977fd7543f4e2ab6a7dc95101a8"
buffer-xor@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/buffer-xor/-/buffer-xor-1.0.3.tgz#26e61ed1422fb70dd42e6e36729ed51d855fe8d9"
......@@ -1314,22 +1317,22 @@ bytes@3.0.0:
resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048"
cacache@^10.0.1:
version "10.0.2"
resolved "https://registry.yarnpkg.com/cacache/-/cacache-10.0.2.tgz#105a93a162bbedf3a25da42e1939ed99ffb145f8"
version "10.0.4"
resolved "https://registry.yarnpkg.com/cacache/-/cacache-10.0.4.tgz#6452367999eff9d4188aefd9a14e9d7c6a263460"
dependencies:
bluebird "^3.5.0"
bluebird "^3.5.1"
chownr "^1.0.1"
glob "^7.1.2"
graceful-fs "^4.1.11"
lru-cache "^4.1.1"
mississippi "^1.3.0"
mississippi "^2.0.0"
mkdirp "^0.5.1"
move-concurrently "^1.0.1"
promise-inflight "^1.0.1"
rimraf "^2.6.1"
ssri "^5.0.0"
rimraf "^2.6.2"
ssri "^5.2.4"
unique-filename "^1.1.0"
y18n "^3.2.1"
y18n "^4.0.0"
caching-transform@^1.0.0:
version "1.0.1"
......@@ -1375,12 +1378,12 @@ caniuse-api@^1.5.2:
lodash.uniq "^4.5.0"
caniuse-db@^1.0.30000529, caniuse-db@^1.0.30000634, caniuse-db@^1.0.30000639:
version "1.0.30000802"
resolved "https://registry.yarnpkg.com/caniuse-db/-/caniuse-db-1.0.30000802.tgz#f7dca342da1c12cf84ff2c80432e24c7e1cc36d9"
version "1.0.30000810"
resolved "https://registry.yarnpkg.com/caniuse-db/-/caniuse-db-1.0.30000810.tgz#bd25830c41efab64339a2e381f49677343c84509"
caniuse-lite@^1.0.30000792:
version "1.0.30000792"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000792.tgz#d0cea981f8118f3961471afbb43c9a1e5bbf0332"
version "1.0.30000810"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000810.tgz#47585fffce0e9f3593a6feea4673b945424351d9"
capture-stack-trace@^1.0.0:
version "1.0.0"
......@@ -1405,13 +1408,13 @@ center-align@^0.1.1:
align-text "^0.1.3"
lazy-cache "^1.0.3"
chalk@2.3.0, chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.0.tgz#b5ea48efc9c1793dccc9b4767c93914d3f2d52ba"
chalk@2.3.2:
version "2.3.2"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.2.tgz#250dc96b07491bfd601e648d66ddf5f60c7a5c65"
dependencies:
ansi-styles "^3.1.0"
ansi-styles "^3.2.1"
escape-string-regexp "^1.0.5"
supports-color "^4.0.0"
supports-color "^5.3.0"
chalk@^1.0.0, chalk@^1.1.1, chalk@^1.1.3:
version "1.1.3"
......@@ -1423,6 +1426,14 @@ chalk@^1.0.0, chalk@^1.1.1, chalk@^1.1.3:
strip-ansi "^3.0.0"
supports-color "^2.0.0"
chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.1:
version "2.3.1"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.1.tgz#523fe2678aec7b04e8041909292fe8b17059b796"
dependencies:
ansi-styles "^3.2.0"
escape-string-regexp "^1.0.5"
supports-color "^5.2.0"
cheerio@0.22.0:
version "0.22.0"
resolved "https://registry.yarnpkg.com/cheerio/-/cheerio-0.22.0.tgz#a9baa860a3f9b595a6b81b1a86873121ed3a269e"
......@@ -1601,13 +1612,17 @@ colors@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63"
combined-stream@^1.0.5, combined-stream@~1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009"
combined-stream@1.0.6, combined-stream@^1.0.5, combined-stream@~1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818"
dependencies:
delayed-stream "~1.0.0"
commander@^2.9.0, commander@~2.13.0:
commander@^2.9.0:
version "2.14.1"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.14.1.tgz#2235123e37af8ca3c65df45b026dbd357b01b9aa"
commander@~2.13.0:
version "2.13.0"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.13.0.tgz#6964bca67685df7c1f1430c584f07d7597885b9c"
......@@ -1853,8 +1868,8 @@ css-color-names@0.0.4:
resolved "https://registry.yarnpkg.com/css-color-names/-/css-color-names-0.0.4.tgz#808adc2e79cf84738069b646cb20ec27beb629e0"
css-loader@^0.28.9:
version "0.28.9"
resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-0.28.9.tgz#68064b85f4e271d7ce4c48a58300928e535d1c95"
version "0.28.10"
resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-0.28.10.tgz#40282e79230f7bcb4e483efa631d670b735ebf42"
dependencies:
babel-code-frame "^6.26.0"
css-selector-tokenizer "^0.7.0"
......@@ -2152,8 +2167,8 @@ domutils@1.5.1:
domelementtype "1"
domutils@^1.5.1:
version "1.6.2"
resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.6.2.tgz#1958cc0b4c9426e9ed367fb1c8e854891b0fa3ff"
version "1.7.0"
resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.7.0.tgz#56ea341e834e06e6748af7a1cb25da67ea9f8c2a"
dependencies:
dom-serializer "0"
domelementtype "1"
......@@ -2188,8 +2203,8 @@ ee-first@1.1.1:
resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d"
electron-to-chromium@^1.2.7, electron-to-chromium@^1.3.30:
version "1.3.32"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.32.tgz#11d0684c0840e003c4be8928f8ac5f35dbc2b4e6"
version "1.3.34"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.34.tgz#d93498f40391bb0c16a603d8241b9951404157ed"
elegant-spinner@^1.0.1:
version "1.0.1"
......@@ -2244,9 +2259,9 @@ entities@^1.1.1, entities@~1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0"
errno@^0.1.2, errno@^0.1.3, errno@^0.1.4:
version "0.1.6"
resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.6.tgz#c386ce8a6283f14fc09563b71560908c9bf53026"
errno@^0.1.2, errno@^0.1.3, errno@~0.1.7:
version "0.1.7"
resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618"
dependencies:
prr "~1.0.1"
......@@ -2281,8 +2296,8 @@ es-to-primitive@^1.1.1:
is-symbol "^1.0.1"
es5-ext@^0.10.14, es5-ext@^0.10.35, es5-ext@^0.10.9, es5-ext@~0.10.14:
version "0.10.38"
resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.38.tgz#fa7d40d65bbc9bb8a67e1d3f9cc656a00530eed3"
version "0.10.39"
resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.39.tgz#fca21b67559277ca4ac1a1ed7048b107b6f76d87"
dependencies:
es6-iterator "~2.0.3"
es6-symbol "~3.1.1"
......@@ -2475,6 +2490,10 @@ event-emitter@~0.3.5:
d "1"
es5-ext "~0.10.14"
event-source-polyfill@0.0.12:
version "0.0.12"
resolved "https://registry.yarnpkg.com/event-source-polyfill/-/event-source-polyfill-0.0.12.tgz#e539cd67fdef2760a16aa5262fa98134df52e3af"
events@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/events/-/events-1.1.1.tgz#9ebdb7635ad099c70dcc4c2a1f5004288e8bd924"
......@@ -2621,8 +2640,8 @@ extsprintf@^1.2.0:
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f"
fast-deep-equal@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz#96256a3bc975595eb36d82e9929d060d893439ff"
version "1.1.0"
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614"
fast-json-stable-stringify@^2.0.0:
version "2.0.0"
......@@ -2811,11 +2830,11 @@ form-data@~2.1.1:
mime-types "^2.1.12"
form-data@~2.3.1:
version "2.3.1"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.1.tgz#6fb94fbd71885306d73d15cc497fe4cc4ecd44bf"
version "2.3.2"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099"
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.5"
combined-stream "1.0.6"
mime-types "^2.1.12"
forwarded@~0.1.0:
......@@ -2959,16 +2978,6 @@ glob@7.1.2, glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6, glob@^7.1.1, glo
once "^1.3.0"
path-is-absolute "^1.0.0"
glob@^6.0.1:
version "6.0.4"
resolved "https://registry.yarnpkg.com/glob/-/glob-6.0.4.tgz#0f08860f6a155127b2fadd4f9ce24b1aab6e4d22"
dependencies:
inflight "^1.0.4"
inherits "2"
minimatch "2 || 3"
once "^1.3.0"
path-is-absolute "^1.0.0"
global-dirs@^0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/global-dirs/-/global-dirs-0.1.1.tgz#b319c0dd4607f353f3be9cca4c72fc148c49f445"
......@@ -3090,6 +3099,10 @@ has-flag@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-2.0.0.tgz#e8207af1cc7b30d446cc70b734b5e8be18f88d51"
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
has-symbols@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44"
......@@ -3155,8 +3168,8 @@ hoek@2.x.x:
resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed"
hoek@4.x.x:
version "4.2.0"
resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.0.tgz#72d9d0754f7fe25ca2d01ad8f8f9a9449a89526d"
version "4.2.1"
resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb"
hoist-non-react-statics@2.3.1:
version "2.3.1"
......@@ -3345,8 +3358,8 @@ interpret@^1.0.0:
resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.1.0.tgz#7ed1b1410c6a0e0f78cf95d3b8440c63f78b8614"
invariant@^2.2.0, invariant@^2.2.2:
version "2.2.2"
resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360"
version "2.2.3"
resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.3.tgz#1a827dfde7dcbd7c323f0ca826be8fa7c5e9d688"
dependencies:
loose-envify "^1.0.0"
......@@ -3457,12 +3470,17 @@ is-installed-globally@^0.1.0:
global-dirs "^0.1.0"
is-path-inside "^1.0.0"
is-my-ip-valid@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/is-my-ip-valid/-/is-my-ip-valid-1.0.0.tgz#7b351b8e8edd4d3995d4d066680e664d94696824"
is-my-json-valid@^2.10.0, is-my-json-valid@^2.12.4:
version "2.17.1"
resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.17.1.tgz#3da98914a70a22f0a8563ef1511a246c6fc55471"
version "2.17.2"
resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.17.2.tgz#6b2103a288e94ef3de5cf15d29dd85fc4b78d65c"
dependencies:
generate-function "^2.0.0"
generate-object-property "^1.1.0"
is-my-ip-valid "^1.0.0"
jsonpointer "^4.0.0"
xtend "^4.0.0"
......@@ -3567,8 +3585,8 @@ is-utf8@^0.2.0:
resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72"
is-windows@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.1.tgz#310db70f742d259a16a369202b51af84233310d9"
version "1.0.2"
resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0:
version "1.0.0"
......@@ -3596,24 +3614,24 @@ isstream@~0.1.2:
resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a"
istanbul-api@^1.1.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/istanbul-api/-/istanbul-api-1.2.1.tgz#0c60a0515eb11c7d65c6b50bba2c6e999acd8620"
version "1.2.2"
resolved "https://registry.yarnpkg.com/istanbul-api/-/istanbul-api-1.2.2.tgz#e17cd519dd5ec4141197f246fdf380b75487f3b1"
dependencies:
async "^2.1.4"
fileset "^2.0.2"
istanbul-lib-coverage "^1.1.1"
istanbul-lib-coverage "^1.1.2"
istanbul-lib-hook "^1.1.0"
istanbul-lib-instrument "^1.9.1"
istanbul-lib-report "^1.1.2"
istanbul-lib-source-maps "^1.2.2"
istanbul-reports "^1.1.3"
istanbul-lib-instrument "^1.9.2"
istanbul-lib-report "^1.1.3"
istanbul-lib-source-maps "^1.2.3"
istanbul-reports "^1.1.4"
js-yaml "^3.7.0"
mkdirp "^0.5.1"
once "^1.4.0"
istanbul-lib-coverage@^1.0.1, istanbul-lib-coverage@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.1.1.tgz#73bfb998885299415c93d38a3e9adf784a77a9da"
istanbul-lib-coverage@^1.0.1, istanbul-lib-coverage@^1.1.1, istanbul-lib-coverage@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.1.2.tgz#4113c8ff6b7a40a1ef7350b01016331f63afde14"
istanbul-lib-hook@^1.0.7, istanbul-lib-hook@^1.1.0:
version "1.1.0"
......@@ -3621,40 +3639,40 @@ istanbul-lib-hook@^1.0.7, istanbul-lib-hook@^1.1.0:
dependencies:
append-transform "^0.4.0"
istanbul-lib-instrument@^1.4.2, istanbul-lib-instrument@^1.7.5, istanbul-lib-instrument@^1.8.0, istanbul-lib-instrument@^1.9.1:
version "1.9.1"
resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.9.1.tgz#250b30b3531e5d3251299fdd64b0b2c9db6b558e"
istanbul-lib-instrument@^1.4.2, istanbul-lib-instrument@^1.7.5, istanbul-lib-instrument@^1.8.0, istanbul-lib-instrument@^1.9.2:
version "1.9.2"
resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.9.2.tgz#84905bf47f7e0b401d6b840da7bad67086b4aab6"
dependencies:
babel-generator "^6.18.0"
babel-template "^6.16.0"
babel-traverse "^6.18.0"
babel-types "^6.18.0"
babylon "^6.18.0"
istanbul-lib-coverage "^1.1.1"
istanbul-lib-coverage "^1.1.2"
semver "^5.3.0"
istanbul-lib-report@^1.1.1, istanbul-lib-report@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.1.2.tgz#922be27c13b9511b979bd1587359f69798c1d425"
istanbul-lib-report@^1.1.1, istanbul-lib-report@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.1.3.tgz#2df12188c0fa77990c0d2176d2d0ba3394188259"
dependencies:
istanbul-lib-coverage "^1.1.1"
istanbul-lib-coverage "^1.1.2"
mkdirp "^0.5.1"
path-parse "^1.0.5"
supports-color "^3.1.2"
istanbul-lib-source-maps@^1.1.0, istanbul-lib-source-maps@^1.2.1, istanbul-lib-source-maps@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.2.tgz#750578602435f28a0c04ee6d7d9e0f2960e62c1c"
istanbul-lib-source-maps@^1.1.0, istanbul-lib-source-maps@^1.2.1, istanbul-lib-source-maps@^1.2.3:
version "1.2.3"
resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.3.tgz#20fb54b14e14b3fb6edb6aca3571fd2143db44e6"
dependencies:
debug "^3.1.0"
istanbul-lib-coverage "^1.1.1"
istanbul-lib-coverage "^1.1.2"
mkdirp "^0.5.1"
rimraf "^2.6.1"
source-map "^0.5.3"
istanbul-reports@^1.1.1, istanbul-reports@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.1.3.tgz#3b9e1e8defb6d18b1d425da8e8b32c5a163f2d10"
istanbul-reports@^1.1.1, istanbul-reports@^1.1.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.1.4.tgz#5ccba5e22b7b5a5d91d5e0a830f89be334bf97bd"
dependencies:
handlebars "^4.0.3"
......@@ -3942,7 +3960,7 @@ jsesc@~0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d"
json-loader@0.5.7, json-loader@^0.5.4:
json-loader@^0.5.4:
version "0.5.7"
resolved "https://registry.yarnpkg.com/json-loader/-/json-loader-0.5.7.tgz#dca14a70235ff82f0ac9a3abeb60d337a365185d"
......@@ -4280,8 +4298,8 @@ macaddress@^0.2.8:
resolved "https://registry.yarnpkg.com/macaddress/-/macaddress-0.2.8.tgz#5904dc537c39ec6dbefeae902327135fa8511f12"
make-dir@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-1.1.0.tgz#19b4369fe48c116f53c2af95ad102c0e39e85d51"
version "1.2.0"
resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-1.2.0.tgz#6d6a49eead4aae296c53bbf3a1a008bd6c89469b"
dependencies:
pify "^3.0.0"
......@@ -4304,12 +4322,6 @@ maximatch@^0.1.0:
arrify "^1.0.0"
minimatch "^3.0.0"
md5-file@3.2.3:
version "3.2.3"
resolved "https://registry.yarnpkg.com/md5-file/-/md5-file-3.2.3.tgz#f9bceb941eca2214a4c0727f5e700314e770f06f"
dependencies:
buffer-alloc "^1.1.0"
md5-hex@^1.2.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4"
......@@ -4396,15 +4408,15 @@ miller-rabin@^4.0.0:
bn.js "^4.0.0"
brorand "^1.0.1"
mime-db@~1.30.0:
version "1.30.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.30.0.tgz#74c643da2dd9d6a45399963465b26d5ca7d71f01"
mime-db@~1.33.0:
version "1.33.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db"
mime-types@^2.1.12, mime-types@~2.1.15, mime-types@~2.1.16, mime-types@~2.1.17, mime-types@~2.1.7:
version "2.1.17"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.17.tgz#09d7a393f03e995a79f8af857b70a9e0ab16557a"
mime-types@^2.1.12, mime-types@~2.1.16, mime-types@~2.1.17, mime-types@~2.1.18, mime-types@~2.1.7:
version "2.1.18"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8"
dependencies:
mime-db "~1.30.0"
mime-db "~1.33.0"
mime@1.3.4:
version "1.3.4"
......@@ -4436,7 +4448,7 @@ minimalistic-crypto-utils@^1.0.0, minimalistic-crypto-utils@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a"
"minimatch@2 || 3", minimatch@^3.0.0, minimatch@^3.0.2, minimatch@^3.0.3, minimatch@^3.0.4:
minimatch@^3.0.0, minimatch@^3.0.2, minimatch@^3.0.3, minimatch@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
dependencies:
......@@ -4454,9 +4466,9 @@ minimist@~0.0.1:
version "0.0.10"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf"
mississippi@^1.3.0:
version "1.3.1"
resolved "https://registry.yarnpkg.com/mississippi/-/mississippi-1.3.1.tgz#2a8bb465e86550ac8b36a7b6f45599171d78671e"
mississippi@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/mississippi/-/mississippi-2.0.0.tgz#3442a508fafc28500486feea99409676e4ee5a6f"
dependencies:
concat-stream "^1.5.0"
duplexify "^3.4.2"
......@@ -4464,7 +4476,7 @@ mississippi@^1.3.0:
flush-write-stream "^1.0.0"
from2 "^2.1.0"
parallel-transform "^1.1.0"
pump "^1.0.0"
pump "^2.0.1"
pumpify "^1.3.3"
stream-each "^1.1.0"
through2 "^2.0.0"
......@@ -4523,14 +4535,6 @@ mute-stream@0.0.5:
version "0.0.5"
resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0"
mv@2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/mv/-/mv-2.1.1.tgz#ae6ce0d6f6d5e0a4f7d893798d03c1ea9559b6a2"
dependencies:
mkdirp "~0.5.1"
ncp "~2.0.0"
rimraf "~2.4.0"
mz@2.7.0:
version "2.7.0"
resolved "https://registry.yarnpkg.com/mz/-/mz-2.7.0.tgz#95008057a56cafadc2bc63dde7f9ff6955948e32"
......@@ -4540,17 +4544,13 @@ mz@2.7.0:
thenify-all "^1.0.0"
nan@^2.3.0:
version "2.8.0"
resolved "https://registry.yarnpkg.com/nan/-/nan-2.8.0.tgz#ed715f3fe9de02b57a5e6252d90a96675e1f085a"
version "2.9.2"
resolved "https://registry.yarnpkg.com/nan/-/nan-2.9.2.tgz#f564d75f5f8f36a6d9456cca7a6c4fe488ab7866"
natural-compare@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
ncp@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ncp/-/ncp-2.0.0.tgz#195a21d6c46e361d2fb1281ba38b91e9df7bdbb3"
negotiator@0.6.1:
version "0.6.1"
resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.1.tgz#2b327184e8992101177b28563fb5e7102acd0ca9"
......@@ -4844,8 +4844,8 @@ os-tmpdir@^1.0.0, os-tmpdir@^1.0.1:
resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
osenv@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.4.tgz#42fe6d5953df06c8064be6f176c3d05aaaa34644"
version "0.1.5"
resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410"
dependencies:
os-homedir "^1.0.0"
os-tmpdir "^1.0.0"
......@@ -5058,12 +5058,6 @@ pkg-dir@^2.0.0:
dependencies:
find-up "^2.1.0"
pkg-up@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/pkg-up/-/pkg-up-2.0.0.tgz#c819ac728059a461cab1c3889a2be3c49a004d7f"
dependencies:
find-up "^2.1.0"
platform@^1.3.3:
version "1.3.5"
resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.5.tgz#fb6958c696e07e2918d2eeda0f0bc9448d733444"
......@@ -5165,8 +5159,8 @@ postcss-load-plugins@^2.3.0:
object-assign "^4.1.0"
postcss-loader@^2.0.10:
version "2.1.0"
resolved "https://registry.yarnpkg.com/postcss-loader/-/postcss-loader-2.1.0.tgz#038c2d6d59753fef4667827fd3ae03f5dc5e6a7a"
version "2.1.1"
resolved "https://registry.yarnpkg.com/postcss-loader/-/postcss-loader-2.1.1.tgz#208935af3b1d65e1abb1a870a912dd12e7b36895"
dependencies:
loader-utils "^1.1.0"
postcss "^6.0.0"
......@@ -5351,12 +5345,12 @@ postcss@^5.0.10, postcss@^5.0.11, postcss@^5.0.12, postcss@^5.0.13, postcss@^5.0
supports-color "^3.2.3"
postcss@^6.0.0, postcss@^6.0.1:
version "6.0.17"
resolved "https://registry.yarnpkg.com/postcss/-/postcss-6.0.17.tgz#e259a051ca513f81e9afd0c21f7f82eda50c65c5"
version "6.0.19"
resolved "https://registry.yarnpkg.com/postcss/-/postcss-6.0.19.tgz#76a78386f670b9d9494a655bf23ac012effd1555"
dependencies:
chalk "^2.3.0"
chalk "^2.3.1"
source-map "^0.6.1"
supports-color "^5.1.0"
supports-color "^5.2.0"
prelude-ls@~1.1.2:
version "1.1.2"
......@@ -5381,9 +5375,9 @@ private@^0.1.6, private@^0.1.7:
version "0.1.8"
resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff"
process-nextick-args@~1.0.6:
version "1.0.7"
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3"
process-nextick-args@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
process@^0.11.10:
version "0.11.10"
......@@ -5447,14 +5441,7 @@ public-encrypt@^4.0.0:
parse-asn1 "^5.0.0"
randombytes "^2.0.1"
pump@^1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/pump/-/pump-1.0.3.tgz#5dfe8311c33bbf6fc18261f9f34702c47c08a954"
dependencies:
end-of-stream "^1.1.0"
once "^1.3.1"
pump@^2.0.0:
pump@^2.0.0, pump@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz#12399add6e4cf7526d973cbc8b5ce2e2908b3909"
dependencies:
......@@ -5530,8 +5517,8 @@ randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.5:
safe-buffer "^5.1.0"
randomfill@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/randomfill/-/randomfill-1.0.3.tgz#b96b7df587f01dd91726c418f30553b1418e3d62"
version "1.0.4"
resolved "https://registry.yarnpkg.com/randomfill/-/randomfill-1.0.4.tgz#c92196fc86ab42be983f1bf31778224931d61458"
dependencies:
randombytes "^2.0.5"
safe-buffer "^5.1.0"
......@@ -5567,9 +5554,9 @@ react-dom@16.2.0:
object-assign "^4.1.1"
prop-types "^15.6.0"
react-hot-loader@4.0.0-beta.23:
version "4.0.0-beta.23"
resolved "https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-4.0.0-beta.23.tgz#dced27e8e2400adb1690eb5b3a0a39b4e0b90615"
react-hot-loader@4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-4.0.0.tgz#3452fa9bc0d0ba9dfc5b0ccfa25101ca8dbd2de2"
dependencies:
fast-levenshtein "^2.0.6"
global "^4.3.0"
......@@ -5617,13 +5604,13 @@ read-pkg@^2.0.0:
path-type "^2.0.0"
"readable-stream@1 || 2", readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.4, readable-stream@^2.0.5, readable-stream@^2.0.6, readable-stream@^2.1.4, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.3:
version "2.3.3"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c"
version "2.3.4"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.4.tgz#c946c3f47fa7d8eabc0b6150f4a12f69a4574071"
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.3"
isarray "~1.0.0"
process-nextick-args "~1.0.6"
process-nextick-args "~2.0.0"
safe-buffer "~5.1.1"
string_decoder "~1.0.3"
util-deprecate "~1.0.1"
......@@ -5902,12 +5889,6 @@ rimraf@2, rimraf@2.6.2, rimraf@^2.2.8, rimraf@^2.5.1, rimraf@^2.5.4, rimraf@^2.6
dependencies:
glob "^7.0.5"
rimraf@~2.4.0:
version "2.4.5"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.4.5.tgz#ee710ce5d93a8fdb856fb5ea8ff0e2d75934b2da"
dependencies:
glob "^6.0.1"
ripemd160@^2.0.0, ripemd160@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.1.tgz#0f4584295c53a3628af7e6d79aca21ce57d1c6e7"
......@@ -5922,8 +5903,8 @@ run-async@^0.1.0:
once "^1.3.0"
run-parallel@^1.1.2:
version "1.1.6"
resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.6.tgz#29003c9a2163e01e2d2dfc90575f2c6c1d61a039"
version "1.1.7"
resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.7.tgz#d8f40854b9e19d18c2e0e70180cc05cfc86b650f"
run-queue@^1.0.0, run-queue@^1.0.3:
version "1.0.3"
......@@ -5946,8 +5927,8 @@ safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@~5.1.0,
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853"
sane@^2.0.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/sane/-/sane-2.3.0.tgz#3f3df584abf69e63d4bb74f0f8c42468e4d7d46b"
version "2.4.1"
resolved "https://registry.yarnpkg.com/sane/-/sane-2.4.1.tgz#29f991208cf28636720efdc584293e7fd66663a5"
dependencies:
anymatch "^1.3.0"
exec-sh "^0.2.0"
......@@ -5970,11 +5951,11 @@ schema-utils@^0.3.0:
ajv "^5.0.0"
schema-utils@^0.4.0, schema-utils@^0.4.2:
version "0.4.3"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.4.3.tgz#e2a594d3395834d5e15da22b48be13517859458e"
version "0.4.5"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.4.5.tgz#21836f0608aac17b78f9e3e24daff14a5ca13a3e"
dependencies:
ajv "^5.0.0"
ajv-keywords "^2.1.0"
ajv "^6.1.0"
ajv-keywords "^3.1.0"
semver-diff@^2.0.0:
version "2.1.0"
......@@ -6189,11 +6170,11 @@ sshpk@^1.7.0:
jsbn "~0.1.0"
tweetnacl "~0.14.0"
ssri@^5.0.0:
version "5.1.0"
resolved "https://registry.yarnpkg.com/ssri/-/ssri-5.1.0.tgz#2cbf1df36b74d0fc91fcf89640a4b3e1d10b1899"
ssri@^5.2.4:
version "5.2.4"
resolved "https://registry.yarnpkg.com/ssri/-/ssri-5.2.4.tgz#9985e14041e65fc397af96542be35724ac11da52"
dependencies:
safe-buffer "^5.1.0"
safe-buffer "^5.1.1"
stackframe@^1.0.3:
version "1.0.4"
......@@ -6308,8 +6289,8 @@ string_decoder@^1.0.0, string_decoder@~1.0.3:
safe-buffer "~5.1.0"
stringify-object@^3.2.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.2.1.tgz#2720c2eff940854c819f6ee252aaeb581f30624d"
version "3.2.2"
resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.2.2.tgz#9853052e5a88fb605a44cd27445aa257ad7ffbcd"
dependencies:
get-own-enumerable-property-symbols "^2.0.1"
is-obj "^1.0.1"
......@@ -6360,9 +6341,9 @@ style-loader@^0.19.1:
loader-utils "^1.0.2"
schema-utils "^0.3.0"
styled-jsx@2.2.5:
version "2.2.5"
resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-2.2.5.tgz#3eb98418720655421bfc1a680e2add581726a5e6"
styled-jsx@2.2.6:
version "2.2.6"
resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-2.2.6.tgz#7e826279e1ef718213ef9cc42ac7370b5008449d"
dependencies:
babel-plugin-syntax-jsx "6.18.0"
babel-types "6.26.0"
......@@ -6390,17 +6371,23 @@ supports-color@^3.1.2, supports-color@^3.2.3:
dependencies:
has-flag "^1.0.0"
supports-color@^4.0.0, supports-color@^4.2.1:
supports-color@^4.2.1:
version "4.5.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-4.5.0.tgz#be7a0de484dec5c5cddf8b3d59125044912f635b"
dependencies:
has-flag "^2.0.0"
supports-color@^5.1.0:
version "5.1.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.1.0.tgz#058a021d1b619f7ddf3980d712ea3590ce7de3d5"
supports-color@^5.2.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.2.0.tgz#b0d5333b1184dd3666cbe5aa0b45c5ac7ac17a4a"
dependencies:
has-flag "^2.0.0"
has-flag "^3.0.0"
supports-color@^5.3.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.3.0.tgz#5b24ac15db80fa927cf5227a4a33fd3c4c7676c0"
dependencies:
has-flag "^3.0.0"
svgo@^0.7.0:
version "0.7.2"
......@@ -6492,8 +6479,8 @@ term-size@^1.2.0:
execa "^0.7.0"
test-exclude@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-4.1.1.tgz#4d84964b0966b0087ecc334a2ce002d3d9341e26"
version "4.2.0"
resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-4.2.0.tgz#07e3613609a362c74516a717515e13322ab45b3c"
dependencies:
arrify "^1.0.1"
micromatch "^2.3.11"
......@@ -6611,11 +6598,11 @@ type-check@~0.3.2:
prelude-ls "~1.1.2"
type-is@~1.6.15:
version "1.6.15"
resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.15.tgz#cab10fb4909e441c82842eafe1ad646c81804410"
version "1.6.16"
resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.16.tgz#f89ce341541c672b25ee7ae3c73dee3b2be50194"
dependencies:
media-typer "0.3.0"
mime-types "~2.1.15"
mime-types "~2.1.18"
typedarray@^0.0.6:
version "0.0.6"
......@@ -6871,9 +6858,9 @@ webpack-dev-middleware@1.12.0:
range-parser "^1.0.3"
time-stamp "^2.0.0"
webpack-hot-middleware@2.21.0:
version "2.21.0"
resolved "https://registry.yarnpkg.com/webpack-hot-middleware/-/webpack-hot-middleware-2.21.0.tgz#7b3c113a7a4b301c91e0749573c7aab28b414b52"
webpack-hot-middleware@2.19.1:
version "2.19.1"
resolved "https://registry.yarnpkg.com/webpack-hot-middleware/-/webpack-hot-middleware-2.19.1.tgz#5db32c31c955c1ead114d37c7519ea554da0d405"
dependencies:
ansi-html "0.0.7"
html-entities "^1.2.0"
......@@ -6974,11 +6961,11 @@ wordwrap@~1.0.0:
resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb"
worker-farm@^1.3.1, worker-farm@^1.5.2:
version "1.5.2"
resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.5.2.tgz#32b312e5dc3d5d45d79ef44acc2587491cd729ae"
version "1.5.4"
resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.5.4.tgz#4debbe46b40edefcc717ebde74a90b1ae1e909a1"
dependencies:
errno "^0.1.4"
xtend "^4.0.1"
errno "~0.1.7"
xtend "~4.0.1"
wrap-ansi@^2.0.0:
version "2.1.0"
......@@ -7032,10 +7019,6 @@ xml-name-validator@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-2.0.1.tgz#4d8b8f1eccd3419aa362061becef515e1e559635"
xss-filters@1.2.7:
version "1.2.7"
resolved "https://registry.yarnpkg.com/xss-filters/-/xss-filters-1.2.7.tgz#59fa1de201f36f2f3470dcac5f58ccc2830b0a9a"
xtend@^4.0.0, xtend@^4.0.1, xtend@~4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"
......@@ -7044,6 +7027,10 @@ y18n@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41"
y18n@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b"
yallist@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
......
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