Unverified Commit 9506f15a authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Update custom server examples (#24814)

parent 33e09dff
# Custom Express Server example # Custom Express Server example
Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to customize routes or other kinds of app behavior. Next.js provides [Custom server and routing](https://github.com/vercel/next.js#custom-server-and-routing) options, so you can customize as much as you want. Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application. Next.js provides [a custom server api](https://nextjs.org/docs/advanced-features/custom-server).
Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. In this case we are using express to build a custom router on top of Next. Because the Next.js server is a Node.js module you can combine it with any other part of the Node.js ecosystem. In this case we are using express.
This example demonstrates a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`.
## How to use ## How to use
...@@ -15,15 +13,3 @@ npx create-next-app --example custom-server-express custom-server-express-app ...@@ -15,15 +13,3 @@ npx create-next-app --example custom-server-express custom-server-express-app
# or # or
yarn create next-app --example custom-server-express custom-server-express-app yarn create next-app --example custom-server-express custom-server-express-app
``` ```
### Populate body property
Without the use of body parsing middleware `req.body` will return undefined. To get express to populate `req.body` you need to use middleware within server.js:
```js
app.prepare().then(() => {
const server = express()
server.use(express.urlencoded({ extended: true }))
server.use(express.json())
})
```
...@@ -9,14 +9,6 @@ const handle = app.getRequestHandler() ...@@ -9,14 +9,6 @@ const handle = app.getRequestHandler()
app.prepare().then(() => { app.prepare().then(() => {
const server = express() const server = express()
server.get('/a', (req, res) => {
return app.render(req, res, '/a', req.query)
})
server.get('/b', (req, res) => {
return app.render(req, res, '/b', req.query)
})
server.all('*', (req, res) => { server.all('*', (req, res) => {
return handle(req, res) return handle(req, res)
}) })
......
# Custom server using Hapi example # Custom server using Hapi example
Most of the times the default Next server will be enough but sometimes you want to run your own server to customize routes or other kind of the app behavior. Next provides a [Custom server and routing](https://github.com/vercel/next.js#custom-server-and-routing) so you can customize as much as you want. Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application. Next.js provides [a custom server api](https://nextjs.org/docs/advanced-features/custom-server).
Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. in this case we are using [Hapi](https://hapijs.com) to build a custom router on top of Next. Because the Next.js server is a Node.js module you can combine it with any other part of the node.js ecosystem. In this case we are using [Hapi](https://hapijs.com).
The example shows a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`.
## How to use ## How to use
......
const next = require('next') const next = require('next')
const Hapi = require('@hapi/hapi') const Hapi = require('@hapi/hapi')
const { pathWrapper, nextHandlerWrapper } = require('./next-wrapper') const { /* pathWrapper, */ nextHandlerWrapper } = require('./next-wrapper')
const port = parseInt(process.env.PORT, 10) || 3000 const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production' const dev = process.env.NODE_ENV !== 'production'
...@@ -10,18 +10,6 @@ const server = new Hapi.Server({ ...@@ -10,18 +10,6 @@ const server = new Hapi.Server({
}) })
app.prepare().then(async () => { app.prepare().then(async () => {
server.route({
method: 'GET',
path: '/a',
handler: pathWrapper(app, '/a'),
})
server.route({
method: 'GET',
path: '/b',
handler: pathWrapper(app, '/b'),
})
server.route({ server.route({
method: 'GET', method: 'GET',
path: '/_next/{p*}' /* next specific routes */, path: '/_next/{p*}' /* next specific routes */,
......
# Custom Koa Server example # Custom Koa Server example
Most of the times the default Next server will be enough but sometimes you want to run your own server to customize routes or other kind of the app behavior. Next provides a [Custom server and routing](https://nextjs.org/docs/advanced-features/custom-server) so you can customize as much as you want. Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application. Next.js provides [a custom server api](https://nextjs.org/docs/advanced-features/custom-server).
Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. in this case we are using [Koa](https://koajs.com/) to build a custom router on top of Next. Because the Next.js server is a Node.js module you can combine it with any other part of the Node.js ecosystem. In this case we are using [Koa](https://koajs.com/).
The example shows a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`.
## How to use ## How to use
......
...@@ -11,16 +11,6 @@ app.prepare().then(() => { ...@@ -11,16 +11,6 @@ app.prepare().then(() => {
const server = new Koa() const server = new Koa()
const router = new Router() const router = new Router()
router.get('/a', async (ctx) => {
await app.render(ctx.req, ctx.res, '/a', ctx.query)
ctx.respond = false
})
router.get('/b', async (ctx) => {
await app.render(ctx.req, ctx.res, '/b', ctx.query)
ctx.respond = false
})
router.all('(.*)', async (ctx) => { router.all('(.*)', async (ctx) => {
await handle(ctx.req, ctx.res) await handle(ctx.req, ctx.res)
ctx.respond = false ctx.respond = false
......
# Custom [Polka](https://github.com/lukeed/polka) Server example # Custom [Polka](https://github.com/lukeed/polka) Server example
Most of the times the default Next server will be enough but sometimes you want to run your own server to customize routes or other kind of the app behavior. Next provides a [Custom server and routing](https://github.com/vercel/next.js#custom-server-and-routing) so you can customize as much as you want. Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application. Next.js provides [a custom server api](https://nextjs.org/docs/advanced-features/custom-server).
Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. in this case we are using express to build a custom router on top of Next. Because the Next.js server is a Node.js module you can combine it with any other part of the Node.js ecosystem. In this case we are using Polka.
The example shows a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`.
## How to use ## How to use
......
...@@ -9,10 +9,6 @@ const handle = app.getRequestHandler() ...@@ -9,10 +9,6 @@ const handle = app.getRequestHandler()
app.prepare().then(() => { app.prepare().then(() => {
const server = polka() const server = polka()
server.get('/a', (req, res) => app.render(req, res, '/a', req.query))
server.get('/b', (req, res) => app.render(req, res, '/b', req.query))
server.all('*', (req, res) => handle(req, res)) server.all('*', (req, res) => handle(req, res))
server.listen(port, (err) => { server.listen(port, (err) => {
......
{ {
"env": { "presets": ["next/babel"]
"development": {
"presets": ["next/babel"]
},
"production": {
"presets": ["next/babel"]
},
"test": {
"presets": [["next/babel", { "preset-env": { "modules": "commonjs" } }]]
}
}
} }
...@@ -10,15 +10,7 @@ const handle = app.getRequestHandler() ...@@ -10,15 +10,7 @@ const handle = app.getRequestHandler()
app.prepare().then(() => { app.prepare().then(() => {
createServer((req, res) => { createServer((req, res) => {
const parsedUrl = parse(req.url!, true) const parsedUrl = parse(req.url!, true)
const { pathname, query } = parsedUrl handle(req, res, 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) }).listen(port)
// tslint:disable-next-line:no-console // tslint:disable-next-line:no-console
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# Custom server example This example has been moved to the documentation: [https://nextjs.org/docs/advanced-features/custom-server](https://nextjs.org/docs/advanced-features/custom-server)
Most of the times the default Next server will be enough but sometimes you want to run your own server to customize routes or other kind of the app behavior. Next provides a [Custom server and routing](https://github.com/vercel/next.js#custom-server-and-routing) so you can customize as much as you want.
The example shows a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`.
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example custom-server custom-server-app
# or
yarn create next-app --example custom-server custom-server-app
```
{
"name": "custom-server",
"version": "1.0.0",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "cross-env NODE_ENV=production node server.js"
},
"dependencies": {
"cross-env": "^7.0.2",
"next": "latest",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"license": "MIT"
}
export default function A() {
return <div>a</div>
}
export default function B() {
return <div>b</div>
}
import Link from 'next/link'
export default function Home() {
return (
<ul>
<li>
<Link href="/b" as="/a">
<a>a</a>
</Link>
</li>
<li>
<Link href="/a" as="/b">
<a>b</a>
</Link>
</li>
</ul>
)
}
const { createServer } = require('http')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = new URL(req.url, 'http://w.w')
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}`)
})
})
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