Skip to content

Commit

Permalink
docs(examples): next proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Apr 29, 2024
1 parent 26674ae commit a2f28df
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
9 changes: 9 additions & 0 deletions examples/next-app/PROXY.md
@@ -0,0 +1,9 @@
# Next.js + http-proxy-proxy

See example `pages/api/users.ts`

```shell
yarn dev

# visit http://localhost:3000/api/users
```
13 changes: 13 additions & 0 deletions examples/next-app/pages/api/_proxy.ts
@@ -0,0 +1,13 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { createProxyMiddleware } from '../../../../dist';

// Singleton
// prevent a new proxy being created for every request
export const proxyMiddleware = createProxyMiddleware<NextApiRequest, NextApiResponse>({
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
pathRewrite: {
'^/api/users': '/users',
},
logger: console,
});
21 changes: 21 additions & 0 deletions examples/next-app/pages/api/users.ts
@@ -0,0 +1,21 @@
import type { NextApiRequest, NextApiResponse, PageConfig } from 'next';
import { proxyMiddleware } from './_proxy';

// https://nextjs.org/docs/pages/building-your-application/routing/api-routes

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
return proxyMiddleware(req, res, (result: unknown) => {
if (result instanceof Error) {
throw result;
}
});
}

export const config: PageConfig = {
api: {
externalResolver: true,
// Uncomment to fix stalled POST requests
// https://github.com/chimurai/http-proxy-middleware/issues/795#issuecomment-1314464432
// bodyParser: false,
},
};

0 comments on commit a2f28df

Please sign in to comment.