top of page

Ken's Code

Setting up Proxy in Vite for Backend API

  • Writer: ken quiggins
    ken quiggins
  • May 7, 2023
  • 2 min read




When developing web applications, it is common to have a backend API that needs to be accessed from the frontend. However, when developing locally, the backend API might be running on a different port or even a different server, which can cause CORS issues.


One way to solve this issue is to use a proxy in the frontend development server. In this tutorial, we will be using Vite as the frontend development server and Express as the backend API.


Prerequisites

  • Node.js installed

  • Basic knowledge of JavaScript, Node.js, and Express


Setup

Backend API

First, let's create a simple backend API using Express. Create a new directory and navigate into it:


mkdir backend
cd backend

Initialize a new Node.js project:


npm init -y

Install Express:


npm install express

Create a new file called server.js with the following code:


const express = require('express');
const app = express();

app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

app.listen(5000, () => {
  console.log('Server running on port 5000');
});

This creates an Express server that listens on port 5000 and responds with a JSON object when /api/data is requested.

Frontend

Next, let's create a new directory for the frontend:


mkdir frontend
cd frontend

Initialize a new Node.js project:


npm init -y

Install the required dependencies:


npm install react react-dom axios vite vite-plugin-react --save-dev

Create a new file called index.js in the src directory with the following code:


import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await axios.get('/api/data');
      setData(response.data);
    }

    fetchData();
  }, []);

  if (!data) {
    return <p>Loading...</p>;
  }

  return <p>{data.message}</p>;
}

export default App;

This creates a simple React component that fetches the data from the backend API and displays it.

Create a new file called vite.config.js in the root directory with the following code:


import react from 'vite-plugin-react';
import proxy from 'vite-plugin-proxy';

export default {
  plugins: [react(), proxy({
    '/api': {
      target: 'http://localhost:5000',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
  })],
};

This configures Vite to use the vite-plugin-react and vite-plugin-proxy plugins. The vite-plugin-proxy plugin is used to set up a proxy to the backend API. It tells Vite to proxy all requests that start with /api to http://localhost:5000, which is where the backend API is running.

Running the Application

To start the frontend development server, run the following command in the frontend directory:


npm run dev

This will start the Vite development server on port 5173.

To start the backend API server, run the following command in the backend directory:


node server.js

This will start the Express server on port 5000.

Now if you open your browser and go to http://localhost:5173 your message should be displayed. 😎 You are now setup to be able to fetch whatever data you need from the backend server. If you like this blog post please consider buying me a coffee.


HAPPY CODING!!!






 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page