diff --git a/examples/next-app/PROXY.md b/examples/next-app/PROXY.md new file mode 100644 index 0000000..42f8fba --- /dev/null +++ b/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 +``` diff --git a/examples/next-app/pages/api/_proxy.ts b/examples/next-app/pages/api/_proxy.ts new file mode 100644 index 0000000..16fdd0f --- /dev/null +++ b/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({ + target: 'http://jsonplaceholder.typicode.com', + changeOrigin: true, + pathRewrite: { + '^/api/users': '/users', + }, + logger: console, +}); diff --git a/examples/next-app/pages/api/users.ts b/examples/next-app/pages/api/users.ts new file mode 100644 index 0000000..6a6cd42 --- /dev/null +++ b/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, + }, +};