Skip to main content

Monorepo Set Up

In order to link your front end to your backend you would need to set up a proxy.

Setup

In vite.config.js, change to

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': 'http://localhost:3000',
},
},
});
  • server.proxy: This section configures the development server to proxy requests.
  • "/api": This specifies that any request starting with /api should be proxied.
  • "http://localhost:3000": This is the target URL where the proxy should forward the requests.

Why do we need a proxy?

1. Seamless API Requests During Development

During development, your frontend (React) application typically runs on a different port (e.g., http://localhost:5173) than your backend (e.g., http://localhost:3000).

Browsers enforce the Same-Origin Policy, which restricts web pages from making requests to a different domain/port than the one that served the web page.

By setting up a proxy, you can make API requests to your backend as if they were coming from the same origin.

2. Avoiding CORS Issues

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent malicious sites from reading sensitive data from another site.

If your frontend tries to directly communicate with the backend running on a different port, you will likely encounter CORS errors.

`A proxy configuration in vite.config.js helps you avoid these issues by forwarding requests to the backend as if they originated from the same origin.

3. Simplifying Relative URLs

When you use a proxy, you can make requests using relative URLs in your frontend code.

Instead of writing the full backend URL for each request (e.g., http://localhost:3000/api/users), you can simply use /api/users, and the proxy will forward the request to the correct backend server. This simplifies the code and makes it more maintainable.

4. Better Development Experience

Setting up a proxy improves the development experience by creating a seamless environment where frontend and backend code can interact smoothly. It allows developers to focus on writing code rather than dealing with configuration issues or browser restrictions.