proxy
- Type:
Record<string, string> | Record<string, ProxyDetail>
- Default:
undefined
Configure proxy rules for the dev server or preview server to proxy requests to the specified service.
Example
Basic Usage
export default {
server: {
proxy: {
// http://localhost:8080/api -> http://localhost:3000/api
// http://localhost:8080/api/foo -> http://localhost:3000/api/foo
'/api': 'http://localhost:3000',
},
},
};
A request to /api/users
will now proxy the request to http://localhost:3000/api/users.
You can also proxy to an online domain name, such as:
export default {
server: {
proxy: {
// http://localhost:8080/api -> https://nodejs.org/api
// http://localhost:8080/api/foo -> https://nodejs.org/foo
'/api': 'https://nodejs.org',
},
},
};
Path Rewrite
If you don't want /api
to be passed along, we need to rewrite the path:
export default {
server: {
proxy: {
// http://localhost:8080/api -> http://localhost:3000
// http://localhost:8080/api/foo -> http://localhost:3000/foo
'/api': {
target: 'http://localhost:3000',
pathRewrite: { '^/api': '' },
},
},
},
};
Options
The Rsbuild Server Proxy makes use of the http-proxy-middleware package. Check out its documentation for more advanced usages.
The full type definition of Rsbuild Server Proxy is:
import type { Options as HttpProxyOptions } from 'http-proxy-middleware';
type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
type ProxyDetail = HttpProxyOptions & {
bypass?: (
req: IncomingMessage,
res: ServerResponse,
proxyOptions: ProxyOptions,
) => string | undefined | null | false;
context?: Filter;
};
type ProxyOptions =
| Record<string, string>
| Record<string, ProxyDetail>
| ProxyDetail[]
| ProxyDetail;
In addition to the http-proxy-middleware option, Rsbuild also support the bypass and context configuration.
bypass
Bypass the proxy based on the return value of a function.
- Return
null
or undefined
to continue processing the request with proxy.
- Return
false
to produce a 404 error for the request.
- Return a path to serve from, instead of continuing to proxy the request.
// custom bypass
export default {
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function (req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
},
},
},
},
};
context
If you want to proxy multiple, specific paths to the same target, you can use an array of one or more objects with a context property.
// proxy multiple
export default {
server: {
proxy: [
{
context: ['/auth', '/api'],
target: 'http://localhost:3000',
},
],
},
};