From a2f28dfce81dd038b0e8892b1aedbd3ff2e4dfa0 Mon Sep 17 00:00:00 2001 From: chimurai <655241+chimurai@users.noreply.github.com> Date: Sat, 27 Apr 2024 20:37:15 +0000 Subject: [PATCH] docs(examples): next proxy https://nextjs.org/docs/pages/building-your-application/routing/api-routes https://github.com/chimurai/http-proxy-middleware/blob/example-nextjs/recipes/servers.md#nextjs --- examples/next-app/PROXY.md | 9 +++++++++ examples/next-app/pages/api/_proxy.ts | 13 +++++++++++++ examples/next-app/pages/api/users.ts | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 examples/next-app/PROXY.md create mode 100644 examples/next-app/pages/api/_proxy.ts create mode 100644 examples/next-app/pages/api/users.ts 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, + }, +};