Vite Proxy Config Avoids CORS Error with Nodejs

A simple proxy configuration in the vite.config.js file that avoids CORS error. As you might know, you can run both frontend and backend applications on the same domain and port using proxy configuration. Using a proxy in the development environment solves the CORS Error. If your frontend application (running on http:// localhost:5173) makes API requests to a backend server (running on http:// localhost:3030), the browser enforces CORS policies. Without proper CORS headers, the browser will block such requests. By using a proxy, the frontend makes requests to its own server (http:// localhost:5173), which then forwards them to the backend. This avoids CORS issues because the frontend and the proxy server share the same origin. And as frontend and backend are running on the same domain and port with this configuration, You can easily access cookies sent from the backend on the frontend. 𝗣𝗦: The proxy configuration is only active during development. It does not affect production builds. 𝗘𝘅𝘁𝗿𝗮 𝗧𝗶𝗽: It's always a good practice to start your backend API routes with /api like /api/users, /api/profile, etc. So if you deploy your application on the same server, you can easily differentiate between frontend and backend routes and will not face any issues with configuration. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nodejs #webdevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories