Set Up App Proxies

It is useful to set up frontend proxies to your backend app during local development. By proxying requests, you won't need to set up CORS when communicating with the backend.

Webpack Dev-Server

Webpack's dev-server has built-in support for proxies.

For example, if you want to proxy all requests to /api to http://localhost:3000, then you would use this configuration:

webpack.config.js
1// ... 2module.exports = { 3 //... 4 devServer: { 5 proxy: [ 6 { 7 context: ['/api'], 8 target: 'http://localhost:3000', 9 }, 10 ], 11 }, 12}; 13

Say that your frontend app is at port 4200, then requests to http://localhost:4200/api will proxy to the backend app at port 3000.

If you don't want /api to be passed along, then use pathRewrite.

webpack.config.js
1// ... 2module.exports = { 3 //... 4 devServer: { 5 proxy: [ 6 { 7 context: ['/api'], 8 target: 'http://localhost:3000', 9 pathRewrite: { '^/api': '' }, 10 }, 11 ], 12 }, 13}; 14

Vite Server

Vite's server has built-in support for proxies.

For example, if you want to proxy all requests to /api to http://localhost:3000, then you would use this configuration:

vite.config.ts
1// ... 2export default defineConfig({ 3 // ... 4 server: { 5 proxy: { 6 '/api': 'http://localhost:3000', 7 }, 8 }, 9}); 10

Say that your frontend app is at port 4200, then requests to http://localhost:4200/api will proxy to the backend app at port 3000.

If you don't want /api to be passed along, then use rewrite.

vite.config.ts
1// ... 2export default defineConfig({ 3 // ... 4 server: { 5 proxy: { 6 '/api': { 7 target: 'http://localhost:3000', 8 rewrite: (path) => path.replace(/^\/api/, ''), 9 }, 10 }, 11 }, 12}); 13

Automatically Configure Frontend Executors

Not recommended for new projects

We recommend configuring proxies using support from existing tooling. Webpack and Vite both come with proxy support out of the box, as do most modern tools. Using --frontendProject is meant for Nx prior to version 18.

Prior to Nx version 18, projects use executors to run tasks. If your frontend project is using executors, then the Node, Nest and Express app generators have an option to configure proxy API requests. This can be done by passing the --frontendProject with the project name you wish to enable proxy support for.

nx g @nx/node:app <node-app> --frontendProject my-react-app

nx g @nx/nest:app <nest-app> --frontendProject my-react-app

nx g @nx/express:app <express-app> --frontendProject my-react-app

This command will generate and configure a proxy.conf.json file that will be used by the frontend project's serve target to redirect calls to /api to instead go to http://localhost:3000/api.

/apps/my-react-app/proxy.conf.json
1{ 2 "/api": { 3 "target": "http://localhost:3000", 4 "secure": false 5 } 6} 7