How to Configure Proxy in Angular for API Requests
To configure a proxy in Angular, create a
proxy.conf.json file with your proxy rules and update angular.json to use it in the serve options. This setup forwards API calls to your backend server during development, avoiding CORS errors.Syntax
The proxy configuration file is a JSON object where each key is a path to intercept and forward. Each path maps to an object with these properties:
- target: The backend server URL to forward requests to.
- secure: Boolean to accept self-signed SSL certificates (usually false for local dev).
- changeOrigin: Boolean to update the origin header to the target URL.
- pathRewrite: Optional object to rewrite the request path before forwarding.
json
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true,
"pathRewrite": { "^/api": "" }
}
}Example
This example shows how to create a proxy configuration file proxy.conf.json that forwards all requests starting with /api to http://localhost:3000. It also rewrites the path by removing /api before sending the request.
Update angular.json to use this proxy file during development.
json
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true,
"pathRewrite": { "^/api": "" }
}
}
// angular.json snippet
{
"projects": {
"your-app-name": {
"architect": {
"serve": {
"options": {
"proxyConfig": "proxy.conf.json"
}
}
}
}
}
}Output
When running 'ng serve', requests to '/api/users' will be forwarded to 'http://localhost:3000/users'.
Common Pitfalls
Common mistakes when configuring proxy in Angular include:
- Not specifying
proxyConfiginangular.jsonor the serve command. - Forgetting to remove the proxy prefix in
pathRewrite, causing backend 404 errors. - Setting
secureto true when using self-signed certificates locally. - Not restarting
ng serveafter changing proxy settings.
json
/* Wrong proxy config without pathRewrite */ { "/api": { "target": "http://localhost:3000", "secure": false, "changeOrigin": true } } /* Correct proxy config with pathRewrite */ { "/api": { "target": "http://localhost:3000", "secure": false, "changeOrigin": true, "pathRewrite": { "^/api": "" } } }
Quick Reference
| Property | Description | Typical Value |
|---|---|---|
| target | Backend server URL to forward requests | "http://localhost:3000" |
| secure | Accept self-signed SSL certificates | false |
| changeOrigin | Update origin header to target URL | true |
| pathRewrite | Rewrite request path before forwarding | {"^/api": ""} |
Key Takeaways
Create a proxy config JSON file to define backend forwarding rules.
Add the proxy config path in angular.json under serve options.
Use pathRewrite to remove API prefixes to match backend routes.
Set secure to false for local development with self-signed certs.
Restart ng serve after changing proxy settings to apply them.