Unverified Commit 0a416acd authored by Sam Ko's avatar Sam Ko Committed by GitHub

Remove with-custom-reverse-proxy example (#35340)

Removing a dated Next.js example.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`
- [X] Removing a dated example

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent ed1eedaa
# 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
# Reverse Proxy example
This example applies this gist https://gist.github.com/jamsesso/67fd937b74989dc52e33 to Nextjs and provides:
- Reverse proxy in development mode by add `http-proxy-middleware` to custom server
- NOT a recommended approach to production scale (hence explicit dev flag) as we should scope proxy as outside UI applications and have separate web server taking care of that.
Sorry for the extra packages. I belong to the minority camp of writing ES6 code on Windows developers. Essentially you only need `http-proxy-middleware` on top of bare-bone Nextjs setup to run this example.
## 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 with-custom-reverse-proxy with-custom-reverse-proxy-app
# or
yarn create next-app --example with-custom-reverse-proxy with-custom-reverse-proxy-app
```
## What it does
Take any random query string to the index page and does a GET to `/api/<query string>` which gets routed internally to `https://swapi.co/api/<query string>`, or any API endpoint you wish to configure through the proxy.
## Expectation
/api/people/2 routed to https://swapi.co/api/people/2
Try Reset
```json
{
"name": "C-3PO",
"height": "167",
"mass": "75",
"hair_color": "n/a",
"skin_color": "gold",
"eye_color": "yellow",
"birth_year": "112BBY",
"gender": "n/a",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/5/",
"https://swapi.co/api/films/4/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/"
],
"species": ["https://swapi.co/api/species/2/"],
"vehicles": [],
"starships": [],
"created": "2014-12-10T15:10:51.357000Z",
"edited": "2014-12-20T21:17:50.309000Z",
"url": "https://swapi.co/api/people/2/"
}
```
{
"private": true,
"dependencies": {
"express": "^4.15.3",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"swr": "0.2.0"
},
"devDependencies": {
"cross-env": "^5.0.1",
"http-proxy-middleware": "^1.0.4"
},
"scripts": {
"dev": "cross-env NODE_ENV=development PORT=3000 node server.js",
"build": "next build",
"prod": "cross-env NODE_ENV=production PORT=3000 node server.js"
}
}
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
const useMounted = () => {
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
return mounted
}
export default function Index() {
const mounted = useMounted()
const router = useRouter()
const queryString = `/api/${Object.keys(router.query).join('')}`
const { data, error } = useSWR(() => (mounted ? queryString : null), fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return (
<content>
<p>
{queryString} routed to https://swapi.co{queryString}
</p>
<p>
<a href="?people/2">Try</a>
&nbsp;
<a href="/">Reset</a>
</p>
<pre>{data ? JSON.stringify(data, null, 2) : 'Loading...'}</pre>
</content>
)
}
/* eslint-disable no-console */
const express = require('express')
const next = require('next')
const devProxy = {
'/api': {
target: 'https://swapi.co/api/',
pathRewrite: { '^/api': '/' },
changeOrigin: true,
},
}
const port = parseInt(process.env.PORT, 10) || 3000
const env = process.env.NODE_ENV
const dev = env !== 'production'
const app = next({
dir: '.', // base directory where everything is, could move to src later
dev,
})
const handle = app.getRequestHandler()
let server
app
.prepare()
.then(() => {
server = express()
// Set up the proxy.
if (dev && devProxy) {
const { createProxyMiddleware } = require('http-proxy-middleware')
Object.keys(devProxy).forEach(function (context) {
server.use(context, createProxyMiddleware(devProxy[context]))
})
}
// Default catch-all handler to allow Next.js to handle all other routes
server.all('*', (req, res) => handle(req, res))
server.listen(port, (err) => {
if (err) {
throw err
}
console.log(`> Ready on port ${port} [${env}]`)
})
})
.catch((err) => {
console.log('An error occurred, unable to start the server')
console.log(err)
})
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