Our great sponsors
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
-
http-proxy-middleware
:zap: The one-liner node.js http-proxy middleware for connect, express, next.js and more
-
WorkOS
The modern identity platform for B2B SaaS. The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.
// In Vercel, any file inside the "api" directory is exposed on an "/api" endpoint. // For an API route to work, you need to export a function as default (a.k.a request handler), // which then receives the following parameters: // - req: The request object. // - res: The response object. // See https://vercel.com/docs/serverless-functions/supported-languages#node.js for details. export default async function handler(req, res) { res.status(200).send(`Hello world!`); }
I recently created a tiny proxy server to edit responses of a public API on the fly, and I was impressed by how easy it is to build and deploy such things on Vercel. In my case, the goal was to allow all origins to fetch the Pinboard API by adding an "Access-Control-Allow-Origin": "*" header to the API response, but there are plenty of other cases where a proxy server may come in handy.
// Create a proxy to redirect requests of the "/api/*" path to "https://example.org". // // Examples: // GET /api/hello β GET https://example.org/hello // POST /api/test?color=red β POST https://example.org/test?color=red // // Additionally, the proxy will: // - Add an "x-added" header // - Remove the "x-removed" header // From the proxied response. // // You can/should update the proxy to suit your needs. // See https://github.com/chimurai/http-proxy-middleware for more details. const { createProxyMiddleware } = require('http-proxy-middleware'); const apiProxy = createProxyMiddleware({ target: "https://example.org", changeOrigin: true, pathRewrite: { "^/api": "" // strip "/api" from the URL }, onProxyRes(proxyRes) { proxyRes.headers['x-added'] = 'foobar'; // add new header to response delete proxyRes.headers['x-removed']; // remove header from response } }); // Expose the proxy on the "/api/*" endpoint. export default function (req, res) { return apiProxy(req, res); };
Check the documentation of the http-proxy-middleware library (and of the node-http-proxy library, used under-the-hood) to learn how you can manipulate the proxied request & response.
So, hereβs how you can create and deploy a tiny but flexible Node.js proxy server on Vercel in 10 minutes.