乐闻世界logo
搜索文章和话题

How to proxy to backend with default next js dev server

2个答案

1
2

In Next.js, you can use two primary strategies to proxy requests to the backend server:

1. Using a Custom Server

You can create a custom Node.js server using Express.js and configure the proxy within it. This enables you to capture specific API paths in the Next.js application and forward them to the backend server.

Here is an example of creating a proxy using Express and http-proxy-middleware:

First, you need to install http-proxy-middleware:

sh
npm install http-proxy-middleware

Then create a custom Express server and use http-proxy-middleware to set up the proxy:

js
const express = require('express'); const next = require('next'); const { createProxyMiddleware } = require('http-proxy-middleware'); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); // Set up proxy rules server.use( '/api', // Proxy path createProxyMiddleware({ target: 'http://backend-server.com', // Target backend server changeOrigin: true, pathRewrite: { '^/api': '', // Rewrite path }, }) ); // All other requests are handled by Next.js server.all('*', (req, res) => { return handle(req, res); }); server.listen(port, (err) => { if (err) throw err; console.log(`> Ready on http://localhost:${port}`); }); });

In this example, all requests to /api will be proxied to http://backend-server.com, and the request path will be rewritten to remove the /api prefix.

2. Using Next.js API Routes

Next.js allows you to create API routes in the pages/api directory. You can use Node.js code within these routes to handle HTTP requests and configure the proxy here.

js
// pages/api/some-route.js import { createProxyMiddleware } from 'http-proxy-middleware'; // Configure proxy middleware export const config = { api: { bodyParser: false, externalResolver: true, }, }; const proxy = createProxyMiddleware({ target: 'http://backend-server.com', changeOrigin: true, pathRewrite: { '^/api': '', // Rewrite path as needed }, }); export default (req, res) => { if (res.finished) return; // Use proxy middleware to handle the request return proxy(req, res, (result) => { if (result instanceof Error) { throw result; } throw new Error(`Request '${req.url}' is not proxied! We should never reach here!`); }); };

In this example, the pages/api/some-route.js file handles all requests to /api/some-route and forwards them through the proxy to the backend.

Note: In production environments, it is generally recommended to set up the proxy at the network level (e.g., using Nginx or features provided by cloud service providers) to improve performance and reliability.

Using these methods, you can set up a proxy server in your Next.js application and proxy requests to the required backend server.

2024年6月29日 12:07 回复

Currently, the configuration includes an official feature: Rewrites

In addition to normal path rewrites, this feature can also proxy requests to another network server.

next.config.js:

javascript
module.exports = { async rewrites() { return [ { source: '/api/:path*',' destination: 'http://localhost:8000/:path*' // Proxy to Backend Server } ] } }

See Next.js Rewrites Documentation

2024年6月29日 12:07 回复

你的答案