Commit 898c131f authored by Karl Horky's avatar Karl Horky Committed by Joe Haddad

Remove pass-server-data example (#8992)

Ref: https://github.com/zeit/next.js/issues/8976
parent a48c8041
# Pass Server Data Directly to a Next.js Page during SSR
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example pass-server-data pass-server-data-app
# or
yarn create next-app --example pass-server-data pass-server-data-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/pass-server-data
cd pass-server-data
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
If you already have a custom server which has local data (for instance cached data from an API call, or data read
from a file at startup) that you wish to make available in the Next.js page, you can pass that data in the query
parameter of `nextApp.render()`.
This is not the only way to pass data. You could also expose an endpoint and make a `fetch()` call to localhost, or you could
import server-side code with `eval` (necessary to prevent webpack from trying to package your server code). However both
solutions leave something to be desired in either performance or elegance.
This example shows the express server at `server.js` reading in a file at load time with static data (this could also have been
data cached from an API call) in `operations/get-item.js`. It has two routes: a home page, and an item page. The item page uses
data from the get-item operation, passed as a query parameter in `routes/item.js`.
We use this data in `pages/item.js` if rendered server-side, or make a fetch request if rendered client-side.
The server knows whether or not to use next.js to render the route based on the Accept header, which will be
`application/json` when we fetch client-side.
Take a look at the following files:
- server.js
- routes/item.js
- pages/item.js
- operations/get-item.js
{
"title": "Now",
"subtitle": "Realtime global deployments",
"seller": "Zeit"
}
const fs = require('fs')
// In this case, data read from the fs, but it could also be a cached API result.
const data = fs.readFileSync('./data/item.json', 'utf8')
const parsedData = JSON.parse(data)
function getItem () {
console.log('Requested Item Data:', data)
return parsedData
}
module.exports = { getItem }
{
"name": "pass-server-data",
"version": "1.0.0",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"express": "^4.16.4",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"license": "ISC"
}
import React from 'react'
import Link from 'next/link'
export default () => (
<ul>
<li>
<Link href='/item'>
<a>View Item</a>
</Link>
</li>
</ul>
)
import { Component } from 'react'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
export default class extends Component {
static async getInitialProps ({ req, query }) {
const isServer = !!req
console.log('getInitialProps called:', isServer ? 'server' : 'client')
if (isServer) {
// When being rendered server-side, we have access to our data in query that we put there in routes/item.js,
// saving us an http call. Note that if we were to try to require('../operations/get-item') here,
// it would result in a webpack error.
return { item: query.itemData }
} else {
// On the client, we should fetch the data remotely
const res = await fetch('/_data/item', {
headers: { Accept: 'application/json' }
})
const json = await res.json()
return { item: json }
}
}
render () {
return (
<div className='item'>
<div>
<Link href='/'>
<a>Back Home</a>
</Link>
</div>
<h1>{this.props.item.title}</h1>
<h2>
{this.props.item.subtitle} - {this.props.item.seller}
</h2>
</div>
)
}
}
const express = require('express')
const next = require('next')
const api = require('./operations/get-item')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// Set up home page as a simple render of the page.
server.get('/', (req, res) => {
console.log('Render home page')
return app.render(req, res, '/', req.query)
})
// Serve the item webpage with next.js as the renderer
server.get('/item', (req, res) => {
const itemData = api.getItem()
app.render(req, res, '/item', { itemData })
})
// When rendering client-side, we will request the same data from this route
server.get('/_data/item', (req, res) => {
const itemData = api.getItem()
res.json(itemData)
})
// Fall-back on other next.js assets.
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
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