From 1c9f680223d8857aa8d26e6e089bc44a24bd7e51 Mon Sep 17 00:00:00 2001 From: chimurai <655241+chimurai@users.noreply.github.com> Date: Mon, 16 Oct 2023 23:04:52 +0200 Subject: [PATCH] docs(nextjs): improve nextjs example --- recipes/servers.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/recipes/servers.md b/recipes/servers.md index 15a527e0..d4580522 100644 --- a/recipes/servers.md +++ b/recipes/servers.md @@ -65,20 +65,26 @@ https://github.com/vercel/next.js [![GitHub stars](https://img.shields.io/github/stars/vercel/next.js.svg?style=social&label=Star)](https://github.com/vercel/next.js) ![next.js downloads](https://img.shields.io/npm/dm/next) -Next project: `/pages/api/users.ts` - ```typescript -// Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import type { NextApiRequest, NextApiResponse } from 'next'; +// Next project: `/pages/api/users.proxy.ts` import { createProxyMiddleware } from 'http-proxy-middleware'; -const proxyMiddleware = createProxyMiddleware({ +// singleton +export const proxyMiddleware = createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, pathRewrite: { '^/api/users': '/users', }, }); +``` + +```typescript +// Next project: `/pages/api/users.ts` + +// Next.js API route support: https://nextjs.org/docs/api-routes/introduction +import type { NextApiRequest, NextApiResponse } from 'next'; +import { proxyMiddleware } from './users.proxy'; export default function handler(req: NextApiRequest, res: NextApiResponse) { proxyMiddleware(req, res, (result: unknown) => { @@ -170,7 +176,7 @@ app.use( createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, - }), + }) ); app.listen(3000); @@ -345,7 +351,7 @@ gulp.task('webserver', function () { directoryListing: true, open: true, middleware: [apiProxy], - }), + }) ); });